From b9c1b51e45b845debb76d8658edabca70ca56079 Mon Sep 17 00:00:00 2001 From: Kate Stone Date: Tue, 6 Sep 2016 20:57:50 +0000 Subject: *** This commit represents a complete reformatting of the LLDB source code *** to conform to clang-format’s LLVM style. This kind of mass change has *** two obvious implications: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Firstly, merging this particular commit into a downstream fork may be a huge effort. Alternatively, it may be worth merging all changes up to this commit, performing the same reformatting operation locally, and then discarding the merge for this particular commit. The commands used to accomplish this reformatting were as follows (with current working directory as the root of the repository): find . \( -iname "*.c" -or -iname "*.cpp" -or -iname "*.h" -or -iname "*.mm" \) -exec clang-format -i {} + find . -iname "*.py" -exec autopep8 --in-place --aggressive --aggressive {} + ; The version of clang-format used was 3.9.0, and autopep8 was 1.2.4. Secondly, “blame” style tools will generally point to this commit instead of a meaningful prior commit. There are alternatives available that will attempt to look through this change and find the appropriate prior commit. YMMV. llvm-svn: 280751 --- lldb/source/API/SBAddress.cpp | 413 +- lldb/source/API/SBAttachInfo.cpp | 259 +- lldb/source/API/SBBlock.cpp | 526 +- lldb/source/API/SBBreakpoint.cpp | 1198 +- lldb/source/API/SBBreakpointLocation.cpp | 521 +- lldb/source/API/SBBroadcaster.cpp | 243 +- lldb/source/API/SBCommandInterpreter.cpp | 1017 +- lldb/source/API/SBCommandReturnObject.cpp | 453 +- lldb/source/API/SBCommunication.cpp | 370 +- lldb/source/API/SBCompileUnit.cpp | 368 +- lldb/source/API/SBData.cpp | 1324 +- lldb/source/API/SBDebugger.cpp | 1937 +- lldb/source/API/SBDeclaration.cpp | 240 +- lldb/source/API/SBError.cpp | 266 +- lldb/source/API/SBEvent.cpp | 309 +- lldb/source/API/SBExecutionContext.cpp | 149 +- lldb/source/API/SBExpressionOptions.cpp | 229 +- lldb/source/API/SBFileSpec.cpp | 253 +- lldb/source/API/SBFileSpecList.cpp | 148 +- lldb/source/API/SBFrame.cpp | 2708 +-- lldb/source/API/SBFunction.cpp | 417 +- lldb/source/API/SBHostOS.cpp | 167 +- lldb/source/API/SBInstruction.cpp | 417 +- lldb/source/API/SBInstructionList.cpp | 174 +- lldb/source/API/SBLanguageRuntime.cpp | 10 +- lldb/source/API/SBLaunchInfo.cpp | 306 +- lldb/source/API/SBLineEntry.cpp | 311 +- lldb/source/API/SBListener.cpp | 561 +- lldb/source/API/SBMemoryRegionInfo.cpp | 127 +- lldb/source/API/SBMemoryRegionInfoList.cpp | 189 +- lldb/source/API/SBModule.cpp | 1100 +- lldb/source/API/SBModuleSpec.cpp | 237 +- lldb/source/API/SBPlatform.cpp | 886 +- lldb/source/API/SBProcess.cpp | 2695 +-- lldb/source/API/SBQueue.cpp | 663 +- lldb/source/API/SBQueueItem.cpp | 205 +- lldb/source/API/SBSection.cpp | 393 +- lldb/source/API/SBSourceManager.cpp | 173 +- lldb/source/API/SBStream.cpp | 271 +- lldb/source/API/SBStringList.cpp | 165 +- lldb/source/API/SBStructuredData.cpp | 172 +- lldb/source/API/SBSymbol.cpp | 296 +- lldb/source/API/SBSymbolContext.cpp | 327 +- lldb/source/API/SBSymbolContextList.cpp | 122 +- lldb/source/API/SBTarget.cpp | 4108 ++-- lldb/source/API/SBThread.cpp | 2587 +-- lldb/source/API/SBThreadCollection.cpp | 92 +- lldb/source/API/SBThreadPlan.cpp | 319 +- lldb/source/API/SBType.cpp | 1221 +- lldb/source/API/SBTypeCategory.cpp | 923 +- lldb/source/API/SBTypeEnumMember.cpp | 224 +- lldb/source/API/SBTypeFilter.cpp | 238 +- lldb/source/API/SBTypeFormat.cpp | 237 +- lldb/source/API/SBTypeNameSpecifier.cpp | 169 +- lldb/source/API/SBTypeSummary.cpp | 717 +- lldb/source/API/SBTypeSynthetic.cpp | 269 +- lldb/source/API/SBUnixSignals.cpp | 213 +- lldb/source/API/SBValue.cpp | 3182 ++- lldb/source/API/SBValueList.cpp | 366 +- lldb/source/API/SBVariablesOptions.cpp | 293 +- lldb/source/API/SBWatchpoint.cpp | 392 +- lldb/source/API/SystemInitializerFull.cpp | 626 +- lldb/source/Breakpoint/Breakpoint.cpp | 1599 +- lldb/source/Breakpoint/BreakpointID.cpp | 167 +- lldb/source/Breakpoint/BreakpointIDList.cpp | 678 +- lldb/source/Breakpoint/BreakpointList.cpp | 343 +- lldb/source/Breakpoint/BreakpointLocation.cpp | 1115 +- .../Breakpoint/BreakpointLocationCollection.cpp | 272 +- lldb/source/Breakpoint/BreakpointLocationList.cpp | 503 +- lldb/source/Breakpoint/BreakpointOptions.cpp | 373 +- lldb/source/Breakpoint/BreakpointResolver.cpp | 323 +- .../Breakpoint/BreakpointResolverAddress.cpp | 218 +- .../Breakpoint/BreakpointResolverFileLine.cpp | 145 +- .../Breakpoint/BreakpointResolverFileRegex.cpp | 166 +- lldb/source/Breakpoint/BreakpointResolverName.cpp | 572 +- lldb/source/Breakpoint/BreakpointSite.cpp | 315 +- lldb/source/Breakpoint/BreakpointSiteList.cpp | 342 +- lldb/source/Breakpoint/Stoppoint.cpp | 23 +- .../source/Breakpoint/StoppointCallbackContext.cpp | 27 +- lldb/source/Breakpoint/StoppointLocation.cpp | 38 +- lldb/source/Breakpoint/Watchpoint.cpp | 655 +- lldb/source/Breakpoint/WatchpointList.cpp | 407 +- lldb/source/Breakpoint/WatchpointOptions.cpp | 282 +- lldb/source/Commands/CommandCompletions.cpp | 1063 +- lldb/source/Commands/CommandObjectApropos.cpp | 159 +- lldb/source/Commands/CommandObjectApropos.h | 15 +- lldb/source/Commands/CommandObjectArgs.cpp | 387 +- lldb/source/Commands/CommandObjectArgs.h | 77 +- lldb/source/Commands/CommandObjectBreakpoint.cpp | 3819 ++-- lldb/source/Commands/CommandObjectBreakpoint.h | 34 +- .../Commands/CommandObjectBreakpointCommand.cpp | 1221 +- .../Commands/CommandObjectBreakpointCommand.h | 13 +- lldb/source/Commands/CommandObjectBugreport.cpp | 176 +- lldb/source/Commands/CommandObjectBugreport.h | 7 +- lldb/source/Commands/CommandObjectCommands.cpp | 3582 ++- lldb/source/Commands/CommandObjectCommands.h | 13 +- lldb/source/Commands/CommandObjectDisassemble.cpp | 1001 +- lldb/source/Commands/CommandObjectDisassemble.h | 121 +- lldb/source/Commands/CommandObjectExpression.cpp | 1063 +- lldb/source/Commands/CommandObjectExpression.h | 147 +- lldb/source/Commands/CommandObjectFrame.cpp | 1289 +- lldb/source/Commands/CommandObjectFrame.h | 10 +- lldb/source/Commands/CommandObjectGUI.cpp | 65 +- lldb/source/Commands/CommandObjectGUI.h | 12 +- lldb/source/Commands/CommandObjectHelp.cpp | 416 +- lldb/source/Commands/CommandObjectHelp.h | 162 +- lldb/source/Commands/CommandObjectLanguage.cpp | 14 +- lldb/source/Commands/CommandObjectLanguage.h | 22 +- lldb/source/Commands/CommandObjectLog.cpp | 709 +- lldb/source/Commands/CommandObjectLog.h | 21 +- lldb/source/Commands/CommandObjectMemory.cpp | 3240 ++- lldb/source/Commands/CommandObjectMemory.h | 7 +- lldb/source/Commands/CommandObjectMultiword.cpp | 752 +- lldb/source/Commands/CommandObjectPlatform.cpp | 3485 ++- lldb/source/Commands/CommandObjectPlatform.h | 9 +- lldb/source/Commands/CommandObjectPlugin.cpp | 141 +- lldb/source/Commands/CommandObjectPlugin.h | 19 +- lldb/source/Commands/CommandObjectProcess.cpp | 2930 ++- lldb/source/Commands/CommandObjectProcess.h | 7 +- lldb/source/Commands/CommandObjectQuit.cpp | 111 +- lldb/source/Commands/CommandObjectQuit.h | 17 +- lldb/source/Commands/CommandObjectRegister.cpp | 743 +- lldb/source/Commands/CommandObjectRegister.h | 21 +- lldb/source/Commands/CommandObjectSettings.cpp | 1902 +- lldb/source/Commands/CommandObjectSettings.h | 9 +- lldb/source/Commands/CommandObjectSource.cpp | 2520 +- lldb/source/Commands/CommandObjectSource.h | 13 +- lldb/source/Commands/CommandObjectSyntax.cpp | 149 +- lldb/source/Commands/CommandObjectSyntax.h | 12 +- lldb/source/Commands/CommandObjectTarget.cpp | 8821 ++++--- lldb/source/Commands/CommandObjectTarget.h | 10 +- lldb/source/Commands/CommandObjectThread.cpp | 3597 ++- lldb/source/Commands/CommandObjectThread.h | 8 +- lldb/source/Commands/CommandObjectType.cpp | 5754 +++-- lldb/source/Commands/CommandObjectType.h | 9 +- lldb/source/Commands/CommandObjectVersion.cpp | 39 +- lldb/source/Commands/CommandObjectVersion.h | 12 +- lldb/source/Commands/CommandObjectWatchpoint.cpp | 2068 +- lldb/source/Commands/CommandObjectWatchpoint.h | 13 +- .../Commands/CommandObjectWatchpointCommand.cpp | 1010 +- .../Commands/CommandObjectWatchpointCommand.h | 12 +- lldb/source/Core/Address.cpp | 1843 +- lldb/source/Core/AddressRange.cpp | 259 +- lldb/source/Core/AddressResolver.cpp | 39 +- lldb/source/Core/AddressResolverFileLine.cpp | 109 +- lldb/source/Core/AddressResolverName.cpp | 321 +- lldb/source/Core/ArchSpec.cpp | 2694 +-- lldb/source/Core/Baton.cpp | 5 +- lldb/source/Core/Broadcaster.cpp | 802 +- lldb/source/Core/Communication.cpp | 687 +- lldb/source/Core/Connection.cpp | 18 +- lldb/source/Core/ConnectionMachPort.cpp | 462 +- lldb/source/Core/ConnectionSharedMemory.cpp | 193 +- lldb/source/Core/ConstString.cpp | 543 +- lldb/source/Core/CxaDemangle.cpp | 8109 +++---- lldb/source/Core/DataBufferHeap.cpp | 75 +- lldb/source/Core/DataBufferMemoryMap.cpp | 398 +- lldb/source/Core/DataEncoder.cpp | 348 +- lldb/source/Core/DataExtractor.cpp | 3448 ++- lldb/source/Core/Debugger.cpp | 2763 +-- lldb/source/Core/Disassembler.cpp | 2023 +- lldb/source/Core/DynamicLoader.cpp | 360 +- lldb/source/Core/EmulateInstruction.cpp | 1070 +- lldb/source/Core/Error.cpp | 448 +- lldb/source/Core/Event.cpp | 415 +- lldb/source/Core/FastDemangle.cpp | 4173 ++-- lldb/source/Core/FileLineResolver.cpp | 126 +- lldb/source/Core/FileSpecList.cpp | 162 +- lldb/source/Core/FormatEntity.cpp | 4377 ++-- lldb/source/Core/History.cpp | 6 +- lldb/source/Core/IOHandler.cpp | 9305 ++++---- lldb/source/Core/Listener.cpp | 807 +- lldb/source/Core/Log.cpp | 748 +- lldb/source/Core/Logging.cpp | 489 +- lldb/source/Core/Mangled.cpp | 573 +- lldb/source/Core/Module.cpp | 3113 ++- lldb/source/Core/ModuleChild.cpp | 38 +- lldb/source/Core/ModuleList.cpp | 1787 +- lldb/source/Core/Opcode.cpp | 225 +- lldb/source/Core/PluginManager.cpp | 4673 ++-- lldb/source/Core/RegisterValue.cpp | 1782 +- lldb/source/Core/RegularExpression.cpp | 259 +- lldb/source/Core/Scalar.cpp | 5162 ++--- lldb/source/Core/SearchFilter.cpp | 997 +- lldb/source/Core/Section.cpp | 929 +- lldb/source/Core/SourceManager.cpp | 1070 +- lldb/source/Core/State.cpp | 176 +- lldb/source/Core/Stream.cpp | 1010 +- lldb/source/Core/StreamAsynchronousIO.cpp | 41 +- lldb/source/Core/StreamCallback.cpp | 59 +- lldb/source/Core/StreamFile.cpp | 66 +- lldb/source/Core/StreamGDBRemote.cpp | 64 +- lldb/source/Core/StreamString.cpp | 123 +- lldb/source/Core/StringList.cpp | 494 +- lldb/source/Core/StructuredData.cpp | 469 +- lldb/source/Core/Timer.cpp | 359 +- lldb/source/Core/UUID.cpp | 403 +- lldb/source/Core/UserID.cpp | 8 +- lldb/source/Core/UserSettingsController.cpp | 158 +- lldb/source/Core/VMRange.cpp | 135 +- lldb/source/Core/Value.cpp | 1383 +- lldb/source/Core/ValueObject.cpp | 7395 +++--- lldb/source/Core/ValueObjectCast.cpp | 139 +- lldb/source/Core/ValueObjectChild.cpp | 401 +- lldb/source/Core/ValueObjectConstResult.cpp | 498 +- lldb/source/Core/ValueObjectConstResultCast.cpp | 66 +- lldb/source/Core/ValueObjectConstResultChild.cpp | 96 +- lldb/source/Core/ValueObjectConstResultImpl.cpp | 290 +- lldb/source/Core/ValueObjectDynamicValue.cpp | 680 +- lldb/source/Core/ValueObjectList.cpp | 184 +- lldb/source/Core/ValueObjectMemory.cpp | 388 +- lldb/source/Core/ValueObjectRegister.cpp | 600 +- lldb/source/Core/ValueObjectSyntheticFilter.cpp | 656 +- lldb/source/Core/ValueObjectVariable.cpp | 674 +- lldb/source/DataFormatters/CXXFunctionPointer.cpp | 76 +- lldb/source/DataFormatters/DataVisualization.cpp | 310 +- .../DataFormatters/DumpValueObjectOptions.cpp | 345 +- lldb/source/DataFormatters/FormatCache.cpp | 339 +- lldb/source/DataFormatters/FormatClasses.cpp | 59 +- lldb/source/DataFormatters/FormatManager.cpp | 1956 +- lldb/source/DataFormatters/FormattersHelpers.cpp | 218 +- lldb/source/DataFormatters/LanguageCategory.cpp | 403 +- lldb/source/DataFormatters/StringPrinter.cpp | 1062 +- lldb/source/DataFormatters/TypeCategory.cpp | 1139 +- lldb/source/DataFormatters/TypeCategoryMap.cpp | 633 +- lldb/source/DataFormatters/TypeFormat.cpp | 370 +- lldb/source/DataFormatters/TypeSummary.cpp | 392 +- lldb/source/DataFormatters/TypeSynthetic.cpp | 355 +- lldb/source/DataFormatters/TypeValidator.cpp | 63 +- lldb/source/DataFormatters/ValueObjectPrinter.cpp | 1637 +- lldb/source/DataFormatters/VectorType.cpp | 551 +- lldb/source/Expression/DWARFExpression.cpp | 6375 +++--- lldb/source/Expression/DiagnosticManager.cpp | 100 +- lldb/source/Expression/Expression.cpp | 25 +- lldb/source/Expression/ExpressionSourceCode.cpp | 605 +- lldb/source/Expression/ExpressionVariable.cpp | 122 +- lldb/source/Expression/FunctionCaller.cpp | 634 +- lldb/source/Expression/IRDynamicChecks.cpp | 933 +- lldb/source/Expression/IRExecutionUnit.cpp | 2047 +- lldb/source/Expression/IRInterpreter.cpp | 3190 ++- lldb/source/Expression/IRMemoryMap.cpp | 1432 +- lldb/source/Expression/LLVMUserExpression.cpp | 570 +- lldb/source/Expression/Materializer.cpp | 2295 +- lldb/source/Expression/REPL.cpp | 1083 +- lldb/source/Expression/UserExpression.cpp | 633 +- lldb/source/Expression/UtilityFunction.cpp | 138 +- lldb/source/Host/android/HostInfoAndroid.cpp | 145 +- lldb/source/Host/android/LibcGlue.cpp | 14 +- lldb/source/Host/common/Editline.cpp | 2392 +- lldb/source/Host/common/File.cpp | 1633 +- lldb/source/Host/common/FileCache.cpp | 183 +- lldb/source/Host/common/FileSpec.cpp | 2393 +- lldb/source/Host/common/FileSystem.cpp | 131 +- lldb/source/Host/common/GetOptInc.cpp | 708 +- lldb/source/Host/common/Host.cpp | 1531 +- lldb/source/Host/common/HostInfoBase.cpp | 665 +- lldb/source/Host/common/HostNativeThreadBase.cpp | 73 +- lldb/source/Host/common/HostProcess.cpp | 51 +- lldb/source/Host/common/HostThread.cpp | 65 +- lldb/source/Host/common/LockFileBase.cpp | 136 +- .../Host/common/MonitoringProcessLauncher.cpp | 116 +- lldb/source/Host/common/NativeBreakpoint.cpp | 159 +- lldb/source/Host/common/NativeBreakpointList.cpp | 349 +- lldb/source/Host/common/NativeProcessProtocol.cpp | 681 +- lldb/source/Host/common/NativeRegisterContext.cpp | 662 +- .../common/NativeRegisterContextRegisterInfo.cpp | 49 +- lldb/source/Host/common/NativeThreadProtocol.cpp | 79 +- lldb/source/Host/common/NativeWatchpointList.cpp | 24 +- lldb/source/Host/common/OptionParser.cpp | 135 +- lldb/source/Host/common/PipeBase.cpp | 15 +- lldb/source/Host/common/ProcessRunLock.cpp | 102 +- lldb/source/Host/common/Socket.cpp | 660 +- lldb/source/Host/common/SocketAddress.cpp | 440 +- lldb/source/Host/common/SoftwareBreakpoint.cpp | 558 +- lldb/source/Host/common/StringConvert.cpp | 169 +- lldb/source/Host/common/Symbols.cpp | 465 +- lldb/source/Host/common/TCPSocket.cpp | 391 +- lldb/source/Host/common/Terminal.cpp | 332 +- lldb/source/Host/common/ThisThread.cpp | 58 +- lldb/source/Host/common/ThreadLauncher.cpp | 100 +- lldb/source/Host/common/TimeValue.cpp | 195 +- lldb/source/Host/common/UDPSocket.cpp | 193 +- lldb/source/Host/common/XML.cpp | 944 +- lldb/source/Host/freebsd/Host.cpp | 418 +- lldb/source/Host/freebsd/HostInfoFreeBSD.cpp | 100 +- lldb/source/Host/freebsd/HostThreadFreeBSD.cpp | 77 +- lldb/source/Host/freebsd/ThisThread.cpp | 24 +- lldb/source/Host/linux/AbstractSocket.cpp | 15 +- lldb/source/Host/linux/Host.cpp | 608 +- lldb/source/Host/linux/HostInfoLinux.cpp | 403 +- lldb/source/Host/linux/HostThreadLinux.cpp | 43 +- lldb/source/Host/linux/LibcGlue.cpp | 27 +- lldb/source/Host/linux/ProcessLauncherLinux.cpp | 330 +- lldb/source/Host/linux/ThisThread.cpp | 14 +- lldb/source/Host/macosx/Host.mm | 2336 +- lldb/source/Host/macosx/HostInfoMacOSX.mm | 519 +- lldb/source/Host/macosx/HostThreadMacOSX.mm | 78 +- lldb/source/Host/macosx/Symbols.cpp | 1040 +- lldb/source/Host/macosx/ThisThread.cpp | 16 +- lldb/source/Host/macosx/cfcpp/CFCBundle.cpp | 112 +- lldb/source/Host/macosx/cfcpp/CFCBundle.h | 38 +- lldb/source/Host/macosx/cfcpp/CFCData.cpp | 78 +- lldb/source/Host/macosx/cfcpp/CFCData.h | 30 +- lldb/source/Host/macosx/cfcpp/CFCMutableArray.cpp | 214 +- lldb/source/Host/macosx/cfcpp/CFCMutableArray.h | 47 +- .../Host/macosx/cfcpp/CFCMutableDictionary.cpp | 856 +- .../Host/macosx/cfcpp/CFCMutableDictionary.h | 108 +- lldb/source/Host/macosx/cfcpp/CFCMutableSet.cpp | 115 +- lldb/source/Host/macosx/cfcpp/CFCMutableSet.h | 58 +- lldb/source/Host/macosx/cfcpp/CFCReleaser.h | 218 +- lldb/source/Host/macosx/cfcpp/CFCString.cpp | 230 +- lldb/source/Host/macosx/cfcpp/CFCString.h | 40 +- lldb/source/Host/macosx/cfcpp/CoreFoundationCPP.h | 4 +- lldb/source/Host/netbsd/Host.cpp | 393 +- lldb/source/Host/netbsd/HostInfoNetBSD.cpp | 142 +- lldb/source/Host/netbsd/HostThreadNetBSD.cpp | 27 +- lldb/source/Host/netbsd/ThisThread.cpp | 14 +- .../Host/posix/ConnectionFileDescriptorPosix.cpp | 1316 +- lldb/source/Host/posix/DomainSocket.cpp | 141 +- lldb/source/Host/posix/FileSystem.cpp | 401 +- lldb/source/Host/posix/HostInfoPosix.cpp | 309 +- lldb/source/Host/posix/HostProcessPosix.cpp | 122 +- lldb/source/Host/posix/HostThreadPosix.cpp | 83 +- lldb/source/Host/posix/LockFilePosix.cpp | 69 +- lldb/source/Host/posix/MainLoopPosix.cpp | 286 +- lldb/source/Host/posix/PipePosix.cpp | 479 +- lldb/source/Host/posix/ProcessLauncherPosix.cpp | 21 +- .../Host/windows/ConnectionGenericFileWindows.cpp | 560 +- lldb/source/Host/windows/EditLineWin.cpp | 621 +- lldb/source/Host/windows/FileSystem.cpp | 418 +- lldb/source/Host/windows/Host.cpp | 503 +- lldb/source/Host/windows/HostInfoWindows.cpp | 171 +- lldb/source/Host/windows/HostProcessWindows.cpp | 164 +- lldb/source/Host/windows/HostThreadWindows.cpp | 103 +- lldb/source/Host/windows/LockFileWindows.cpp | 91 +- lldb/source/Host/windows/PipeWindows.cpp | 477 +- .../source/Host/windows/ProcessLauncherWindows.cpp | 235 +- lldb/source/Host/windows/ProcessRunLock.cpp | 115 +- lldb/source/Host/windows/ThisThread.cpp | 57 +- lldb/source/Host/windows/Windows.cpp | 401 +- lldb/source/Initialization/SystemInitializer.cpp | 8 +- .../Initialization/SystemInitializerCommon.cpp | 132 +- .../Initialization/SystemLifetimeManager.cpp | 59 +- lldb/source/Interpreter/Args.cpp | 3053 ++- lldb/source/Interpreter/CommandAlias.cpp | 463 +- lldb/source/Interpreter/CommandHistory.cpp | 175 +- lldb/source/Interpreter/CommandInterpreter.cpp | 6026 +++-- lldb/source/Interpreter/CommandObject.cpp | 1845 +- .../Interpreter/CommandObjectRegexCommand.cpp | 190 +- lldb/source/Interpreter/CommandObjectScript.cpp | 96 +- lldb/source/Interpreter/CommandObjectScript.h | 12 +- .../source/Interpreter/CommandOptionValidators.cpp | 32 +- lldb/source/Interpreter/CommandReturnObject.cpp | 304 +- .../source/Interpreter/OptionGroupArchitecture.cpp | 85 +- lldb/source/Interpreter/OptionGroupBoolean.cpp | 78 +- lldb/source/Interpreter/OptionGroupFile.cpp | 116 +- lldb/source/Interpreter/OptionGroupFormat.cpp | 456 +- lldb/source/Interpreter/OptionGroupOutputFile.cpp | 86 +- lldb/source/Interpreter/OptionGroupPlatform.cpp | 270 +- lldb/source/Interpreter/OptionGroupString.cpp | 60 +- lldb/source/Interpreter/OptionGroupUInt64.cpp | 60 +- lldb/source/Interpreter/OptionGroupUUID.cpp | 76 +- .../Interpreter/OptionGroupValueObjectDisplay.cpp | 364 +- lldb/source/Interpreter/OptionGroupVariable.cpp | 212 +- lldb/source/Interpreter/OptionGroupWatchpoint.cpp | 162 +- lldb/source/Interpreter/OptionValue.cpp | 1220 +- lldb/source/Interpreter/OptionValueArch.cpp | 127 +- lldb/source/Interpreter/OptionValueArgs.cpp | 29 +- lldb/source/Interpreter/OptionValueArray.cpp | 576 +- lldb/source/Interpreter/OptionValueBoolean.cpp | 182 +- lldb/source/Interpreter/OptionValueChar.cpp | 86 +- lldb/source/Interpreter/OptionValueDictionary.cpp | 696 +- lldb/source/Interpreter/OptionValueEnumeration.cpp | 219 +- lldb/source/Interpreter/OptionValueFileSpec.cpp | 228 +- .../source/Interpreter/OptionValueFileSpecLIst.cpp | 290 +- lldb/source/Interpreter/OptionValueFormat.cpp | 87 +- .../source/Interpreter/OptionValueFormatEntity.cpp | 183 +- lldb/source/Interpreter/OptionValueLanguage.cpp | 111 +- .../source/Interpreter/OptionValuePathMappings.cpp | 379 +- lldb/source/Interpreter/OptionValueProperties.cpp | 1269 +- lldb/source/Interpreter/OptionValueRegex.cpp | 102 +- lldb/source/Interpreter/OptionValueSInt64.cpp | 116 +- lldb/source/Interpreter/OptionValueString.cpp | 268 +- lldb/source/Interpreter/OptionValueUInt64.cpp | 114 +- lldb/source/Interpreter/OptionValueUUID.cpp | 162 +- lldb/source/Interpreter/Options.cpp | 1786 +- lldb/source/Interpreter/Property.cpp | 517 +- lldb/source/Interpreter/ScriptInterpreter.cpp | 116 +- lldb/source/Interpreter/embedded_interpreter.py | 44 +- .../Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp | 2764 ++- lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h | 176 +- .../Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp | 3270 ++- .../Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h | 185 +- .../Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp | 1573 +- .../Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h | 188 +- lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp | 2995 ++- lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h | 176 +- .../Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp | 3227 ++- lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h | 186 +- .../Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp | 1630 +- .../Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h | 197 +- lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp | 1967 +- lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h | 204 +- lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp | 1523 +- lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h | 136 +- .../Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp | 1841 +- .../Plugins/ABI/SysV-mips64/ABISysV_mips64.h | 199 +- lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp | 1631 +- lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h | 190 +- .../Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp | 1640 +- lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h | 192 +- .../Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp | 1172 +- lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h | 131 +- .../Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp | 2727 ++- .../Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h | 195 +- .../Disassembler/llvm/DisassemblerLLVMC.cpp | 2607 +-- .../Plugins/Disassembler/llvm/DisassemblerLLVMC.h | 232 +- .../Darwin-Kernel/DynamicLoaderDarwinKernel.cpp | 2577 +-- .../Darwin-Kernel/DynamicLoaderDarwinKernel.h | 549 +- .../Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp | 1033 +- .../Hexagon-DYLD/DynamicLoaderHexagonDYLD.h | 227 +- .../Hexagon-DYLD/HexagonDYLDRendezvous.cpp | 572 +- .../Hexagon-DYLD/HexagonDYLDRendezvous.h | 412 +- .../MacOSX-DYLD/DynamicLoaderDarwin.cpp | 2011 +- .../MacOSX-DYLD/DynamicLoaderDarwin.h | 438 +- .../MacOSX-DYLD/DynamicLoaderMacOS.cpp | 834 +- .../DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h | 130 +- .../MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp | 2101 +- .../MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h | 302 +- .../Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp | 142 +- .../Plugins/DynamicLoader/POSIX-DYLD/AuxVector.h | 129 +- .../DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp | 979 +- .../DynamicLoader/POSIX-DYLD/DYLDRendezvous.h | 399 +- .../POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp | 1135 +- .../POSIX-DYLD/DynamicLoaderPOSIXDYLD.h | 251 +- .../DynamicLoader/Static/DynamicLoaderStatic.cpp | 230 +- .../DynamicLoader/Static/DynamicLoaderStatic.h | 76 +- .../Windows-DYLD/DynamicLoaderWindowsDYLD.cpp | 102 +- .../Windows-DYLD/DynamicLoaderWindowsDYLD.h | 35 +- .../Plugins/ExpressionParser/Clang/ASTDumper.cpp | 162 +- .../Plugins/ExpressionParser/Clang/ASTDumper.h | 33 +- .../Clang/ASTResultSynthesizer.cpp | 795 +- .../ExpressionParser/Clang/ASTResultSynthesizer.h | 357 +- .../ExpressionParser/Clang/ASTStructExtractor.cpp | 277 +- .../ExpressionParser/Clang/ASTStructExtractor.h | 246 +- .../ExpressionParser/Clang/ClangASTSource.cpp | 3146 ++- .../ExpressionParser/Clang/ClangASTSource.h | 937 +- .../ExpressionParser/Clang/ClangDiagnostic.h | 58 +- .../Clang/ClangExpressionDeclMap.cpp | 3645 ++- .../Clang/ClangExpressionDeclMap.h | 1226 +- .../ExpressionParser/Clang/ClangExpressionHelper.h | 75 +- .../Clang/ClangExpressionParser.cpp | 1639 +- .../ExpressionParser/Clang/ClangExpressionParser.h | 254 +- .../Clang/ClangExpressionVariable.cpp | 79 +- .../Clang/ClangExpressionVariable.h | 359 +- .../ExpressionParser/Clang/ClangFunctionCaller.cpp | 317 +- .../ExpressionParser/Clang/ClangFunctionCaller.h | 195 +- .../Clang/ClangModulesDeclVendor.cpp | 1215 +- .../Clang/ClangModulesDeclVendor.h | 197 +- .../Clang/ClangPersistentVariables.cpp | 106 +- .../Clang/ClangPersistentVariables.h | 127 +- .../ExpressionParser/Clang/ClangUserExpression.cpp | 1093 +- .../ExpressionParser/Clang/ClangUserExpression.h | 302 +- .../Clang/ClangUtilityFunction.cpp | 210 +- .../ExpressionParser/Clang/ClangUtilityFunction.h | 152 +- .../Plugins/ExpressionParser/Clang/IRForTarget.cpp | 3143 ++- .../Plugins/ExpressionParser/Clang/IRForTarget.h | 1191 +- lldb/source/Plugins/ExpressionParser/Go/GoAST.h | 4405 ++-- .../source/Plugins/ExpressionParser/Go/GoLexer.cpp | 650 +- lldb/source/Plugins/ExpressionParser/Go/GoLexer.h | 322 +- .../Plugins/ExpressionParser/Go/GoParser.cpp | 1717 +- lldb/source/Plugins/ExpressionParser/Go/GoParser.h | 272 +- .../ExpressionParser/Go/GoUserExpression.cpp | 1154 +- .../Plugins/ExpressionParser/Go/GoUserExpression.h | 108 +- .../Plugins/ExpressionParser/Go/gen_go_ast.py | 150 +- .../Instruction/ARM/EmulateInstructionARM.cpp | 22871 ++++++++++--------- .../Instruction/ARM/EmulateInstructionARM.h | 1695 +- .../Plugins/Instruction/ARM/EmulationStateARM.cpp | 669 +- .../Plugins/Instruction/ARM/EmulationStateARM.h | 130 +- .../Instruction/ARM64/EmulateInstructionARM64.cpp | 1882 +- .../Instruction/ARM64/EmulateInstructionARM64.h | 418 +- .../Instruction/MIPS/EmulateInstructionMIPS.cpp | 4990 ++-- .../Instruction/MIPS/EmulateInstructionMIPS.h | 342 +- .../MIPS64/EmulateInstructionMIPS64.cpp | 3809 +-- .../Instruction/MIPS64/EmulateInstructionMIPS64.h | 284 +- .../AddressSanitizer/AddressSanitizerRuntime.cpp | 433 +- .../AddressSanitizer/AddressSanitizerRuntime.h | 105 +- .../ThreadSanitizer/ThreadSanitizerRuntime.cpp | 1344 +- .../ThreadSanitizer/ThreadSanitizerRuntime.h | 134 +- lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp | 753 +- lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.h | 107 +- .../Plugins/Language/CPlusPlus/BlockPointer.cpp | 316 +- .../Plugins/Language/CPlusPlus/BlockPointer.h | 13 +- .../Language/CPlusPlus/CPlusPlusLanguage.cpp | 1625 +- .../Plugins/Language/CPlusPlus/CPlusPlusLanguage.h | 274 +- .../Plugins/Language/CPlusPlus/CxxStringTypes.cpp | 344 +- .../Plugins/Language/CPlusPlus/CxxStringTypes.h | 47 +- lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp | 1036 +- lldb/source/Plugins/Language/CPlusPlus/LibCxx.h | 251 +- .../Plugins/Language/CPlusPlus/LibCxxAtomic.cpp | 154 +- .../Plugins/Language/CPlusPlus/LibCxxAtomic.h | 20 +- .../Language/CPlusPlus/LibCxxInitializerList.cpp | 179 +- .../Plugins/Language/CPlusPlus/LibCxxList.cpp | 672 +- .../Plugins/Language/CPlusPlus/LibCxxMap.cpp | 713 +- .../Language/CPlusPlus/LibCxxUnorderedMap.cpp | 232 +- .../Plugins/Language/CPlusPlus/LibCxxVector.cpp | 206 +- .../Plugins/Language/CPlusPlus/LibStdcpp.cpp | 694 +- lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.h | 46 +- .../Plugins/Language/Go/GoFormatterFunctions.cpp | 247 +- .../Plugins/Language/Go/GoFormatterFunctions.h | 12 +- lldb/source/Plugins/Language/Go/GoLanguage.cpp | 164 +- lldb/source/Plugins/Language/Go/GoLanguage.h | 51 +- .../Language/Java/JavaFormatterFunctions.cpp | 281 +- .../Plugins/Language/Java/JavaFormatterFunctions.h | 19 +- lldb/source/Plugins/Language/Java/JavaLanguage.cpp | 114 +- lldb/source/Plugins/Language/Java/JavaLanguage.h | 38 +- .../Plugins/Language/OCaml/OCamlLanguage.cpp | 59 +- lldb/source/Plugins/Language/OCaml/OCamlLanguage.h | 38 +- lldb/source/Plugins/Language/ObjC/CF.cpp | 539 +- lldb/source/Plugins/Language/ObjC/CF.h | 27 +- lldb/source/Plugins/Language/ObjC/Cocoa.cpp | 1712 +- lldb/source/Plugins/Language/ObjC/Cocoa.h | 179 +- lldb/source/Plugins/Language/ObjC/CoreMedia.cpp | 142 +- lldb/source/Plugins/Language/ObjC/CoreMedia.h | 14 +- lldb/source/Plugins/Language/ObjC/NSArray.cpp | 1295 +- lldb/source/Plugins/Language/ObjC/NSDictionary.cpp | 1317 +- lldb/source/Plugins/Language/ObjC/NSDictionary.h | 53 +- lldb/source/Plugins/Language/ObjC/NSError.cpp | 347 +- lldb/source/Plugins/Language/ObjC/NSException.cpp | 341 +- lldb/source/Plugins/Language/ObjC/NSIndexPath.cpp | 620 +- lldb/source/Plugins/Language/ObjC/NSSet.cpp | 1086 +- lldb/source/Plugins/Language/ObjC/NSSet.h | 38 +- lldb/source/Plugins/Language/ObjC/NSString.cpp | 717 +- lldb/source/Plugins/Language/ObjC/NSString.h | 44 +- lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp | 1730 +- lldb/source/Plugins/Language/ObjC/ObjCLanguage.h | 308 +- .../Language/ObjCPlusPlus/ObjCPlusPlusLanguage.cpp | 56 +- .../Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h | 68 +- .../ItaniumABI/ItaniumABILanguageRuntime.cpp | 975 +- .../ItaniumABI/ItaniumABILanguageRuntime.h | 192 +- .../LanguageRuntime/Go/GoLanguageRuntime.cpp | 310 +- .../Plugins/LanguageRuntime/Go/GoLanguageRuntime.h | 133 +- .../LanguageRuntime/Java/JavaLanguageRuntime.cpp | 237 +- .../LanguageRuntime/Java/JavaLanguageRuntime.h | 80 +- .../AppleObjCClassDescriptorV2.cpp | 997 +- .../AppleObjCRuntime/AppleObjCClassDescriptorV2.h | 665 +- .../ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp | 1175 +- .../ObjC/AppleObjCRuntime/AppleObjCDeclVendor.h | 46 +- .../ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp | 829 +- .../ObjC/AppleObjCRuntime/AppleObjCRuntime.h | 221 +- .../ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp | 711 +- .../ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h | 308 +- .../ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp | 3992 ++-- .../ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h | 644 +- .../AppleObjCTrampolineHandler.cpp | 1648 +- .../AppleObjCRuntime/AppleObjCTrampolineHandler.h | 295 +- .../AppleObjCTypeEncodingParser.cpp | 660 +- .../AppleObjCRuntime/AppleObjCTypeEncodingParser.h | 112 +- .../AppleThreadPlanStepThroughObjCTrampoline.cpp | 334 +- .../AppleThreadPlanStepThroughObjCTrampoline.h | 118 +- .../RenderScriptExpressionOpts.cpp | 276 +- .../RenderScriptExpressionOpts.h | 35 +- .../RenderScriptRuntime/RenderScriptRuntime.cpp | 7609 +++--- .../RenderScriptRuntime/RenderScriptRuntime.h | 529 +- .../RenderScriptx86ABIFixups.cpp | 469 +- .../RenderScriptRuntime/RenderScriptx86ABIFixups.h | 12 +- .../MemoryHistory/asan/MemoryHistoryASan.cpp | 276 +- .../Plugins/MemoryHistory/asan/MemoryHistoryASan.h | 57 +- .../BSD-Archive/ObjectContainerBSDArchive.cpp | 939 +- .../BSD-Archive/ObjectContainerBSDArchive.h | 342 +- .../ObjectContainerUniversalMachO.cpp | 421 +- .../ObjectContainerUniversalMachO.h | 141 +- lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp | 607 +- lldb/source/Plugins/ObjectFile/ELF/ELFHeader.h | 645 +- .../Plugins/ObjectFile/ELF/ObjectFileELF.cpp | 5927 +++-- lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h | 766 +- .../Plugins/ObjectFile/JIT/ObjectFileJIT.cpp | 429 +- lldb/source/Plugins/ObjectFile/JIT/ObjectFileJIT.h | 201 +- .../Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp | 11200 +++++---- .../Plugins/ObjectFile/Mach-O/ObjectFileMachO.h | 396 +- .../Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp | 1715 +- .../Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h | 532 +- .../Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp | 63 +- .../Plugins/ObjectFile/PECOFF/WindowsMiniDump.h | 9 +- .../OperatingSystem/Go/OperatingSystemGo.cpp | 825 +- .../Plugins/OperatingSystem/Go/OperatingSystemGo.h | 83 +- .../Python/OperatingSystemPython.cpp | 679 +- .../OperatingSystem/Python/OperatingSystemPython.h | 139 +- lldb/source/Plugins/Platform/Android/AdbClient.cpp | 995 +- lldb/source/Plugins/Platform/Android/AdbClient.h | 158 +- .../Plugins/Platform/Android/PlatformAndroid.cpp | 603 +- .../Plugins/Platform/Android/PlatformAndroid.h | 152 +- .../Android/PlatformAndroidRemoteGDBServer.cpp | 370 +- .../Android/PlatformAndroidRemoteGDBServer.h | 50 +- .../Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp | 1031 +- .../Plugins/Platform/FreeBSD/PlatformFreeBSD.h | 192 +- .../Plugins/Platform/Kalimba/PlatformKalimba.cpp | 433 +- .../Plugins/Platform/Kalimba/PlatformKalimba.h | 99 +- .../Plugins/Platform/Linux/PlatformLinux.cpp | 1149 +- lldb/source/Plugins/Platform/Linux/PlatformLinux.h | 158 +- .../Platform/MacOSX/PlatformAppleSimulator.cpp | 378 +- .../Platform/MacOSX/PlatformAppleSimulator.h | 94 +- .../Platform/MacOSX/PlatformAppleTVSimulator.cpp | 659 +- .../Platform/MacOSX/PlatformAppleTVSimulator.h | 167 +- .../MacOSX/PlatformAppleWatchSimulator.cpp | 662 +- .../Platform/MacOSX/PlatformAppleWatchSimulator.h | 166 +- .../Plugins/Platform/MacOSX/PlatformDarwin.cpp | 3226 +-- .../Plugins/Platform/MacOSX/PlatformDarwin.h | 248 +- .../Platform/MacOSX/PlatformDarwinKernel.cpp | 1407 +- .../Plugins/Platform/MacOSX/PlatformDarwinKernel.h | 301 +- .../Plugins/Platform/MacOSX/PlatformMacOSX.cpp | 544 +- .../Plugins/Platform/MacOSX/PlatformMacOSX.h | 147 +- .../Platform/MacOSX/PlatformRemoteAppleTV.cpp | 1615 +- .../Platform/MacOSX/PlatformRemoteAppleTV.h | 241 +- .../Platform/MacOSX/PlatformRemoteAppleWatch.cpp | 1704 +- .../Platform/MacOSX/PlatformRemoteAppleWatch.h | 243 +- .../Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp | 1518 +- .../Plugins/Platform/MacOSX/PlatformRemoteiOS.h | 249 +- .../Platform/MacOSX/PlatformiOSSimulator.cpp | 731 +- .../Plugins/Platform/MacOSX/PlatformiOSSimulator.h | 163 +- .../PlatformiOSSimulatorCoreSimulatorSupport.h | 474 +- .../PlatformiOSSimulatorCoreSimulatorSupport.mm | 1164 +- .../Plugins/Platform/NetBSD/PlatformNetBSD.cpp | 948 +- .../Plugins/Platform/NetBSD/PlatformNetBSD.h | 187 +- .../Plugins/Platform/POSIX/PlatformPOSIX.cpp | 1575 +- lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h | 349 +- .../Plugins/Platform/Windows/PlatformWindows.cpp | 1036 +- .../Plugins/Platform/Windows/PlatformWindows.h | 177 +- .../gdb-server/PlatformRemoteGDBServer.cpp | 1618 +- .../Platform/gdb-server/PlatformRemoteGDBServer.h | 403 +- lldb/source/Plugins/Process/Darwin/CFBundle.cpp | 90 +- lldb/source/Plugins/Process/Darwin/CFBundle.h | 31 +- lldb/source/Plugins/Process/Darwin/CFString.cpp | 232 +- lldb/source/Plugins/Process/Darwin/CFString.h | 38 +- lldb/source/Plugins/Process/Darwin/CFUtils.h | 91 +- .../Process/Darwin/DarwinProcessLauncher.cpp | 1185 +- .../Plugins/Process/Darwin/DarwinProcessLauncher.h | 11 +- lldb/source/Plugins/Process/Darwin/LaunchFlavor.h | 19 +- .../Plugins/Process/Darwin/MachException.cpp | 967 +- lldb/source/Plugins/Process/Darwin/MachException.h | 239 +- .../Plugins/Process/Darwin/NativeProcessDarwin.cpp | 2795 ++- .../Plugins/Process/Darwin/NativeProcessDarwin.h | 603 +- .../Plugins/Process/Darwin/NativeThreadDarwin.cpp | 264 +- .../Plugins/Process/Darwin/NativeThreadDarwin.h | 200 +- .../Process/Darwin/NativeThreadListDarwin.cpp | 399 +- .../Process/Darwin/NativeThreadListDarwin.h | 113 +- .../Plugins/Process/FreeBSD/FreeBSDThread.cpp | 1089 +- .../source/Plugins/Process/FreeBSD/FreeBSDThread.h | 163 +- .../Plugins/Process/FreeBSD/POSIXStopInfo.cpp | 69 +- .../source/Plugins/Process/FreeBSD/POSIXStopInfo.h | 68 +- .../Plugins/Process/FreeBSD/ProcessFreeBSD.cpp | 1476 +- .../Plugins/Process/FreeBSD/ProcessFreeBSD.h | 286 +- .../Plugins/Process/FreeBSD/ProcessMonitor.cpp | 2144 +- .../Plugins/Process/FreeBSD/ProcessMonitor.h | 460 +- .../Plugins/Process/FreeBSD/RegisterContextPOSIX.h | 73 +- .../RegisterContextPOSIXProcessMonitor_arm.cpp | 428 +- .../RegisterContextPOSIXProcessMonitor_arm.h | 89 +- .../RegisterContextPOSIXProcessMonitor_arm64.cpp | 423 +- .../RegisterContextPOSIXProcessMonitor_arm64.h | 90 +- .../RegisterContextPOSIXProcessMonitor_mips64.cpp | 411 +- .../RegisterContextPOSIXProcessMonitor_mips64.h | 90 +- .../RegisterContextPOSIXProcessMonitor_powerpc.cpp | 448 +- .../RegisterContextPOSIXProcessMonitor_powerpc.h | 102 +- .../RegisterContextPOSIXProcessMonitor_x86.cpp | 1033 +- .../RegisterContextPOSIXProcessMonitor_x86.h | 93 +- .../Plugins/Process/Linux/NativeProcessLinux.cpp | 4416 ++-- .../Plugins/Process/Linux/NativeProcessLinux.h | 291 +- .../Process/Linux/NativeRegisterContextLinux.cpp | 315 +- .../Process/Linux/NativeRegisterContextLinux.h | 105 +- .../Linux/NativeRegisterContextLinux_arm.cpp | 1645 +- .../Process/Linux/NativeRegisterContextLinux_arm.h | 219 +- .../Linux/NativeRegisterContextLinux_arm64.cpp | 1630 +- .../Linux/NativeRegisterContextLinux_arm64.h | 220 +- .../Linux/NativeRegisterContextLinux_mips64.cpp | 2148 +- .../Linux/NativeRegisterContextLinux_mips64.h | 162 +- .../Linux/NativeRegisterContextLinux_s390x.cpp | 1050 +- .../Linux/NativeRegisterContextLinux_s390x.h | 131 +- .../Linux/NativeRegisterContextLinux_x86_64.cpp | 1958 +- .../Linux/NativeRegisterContextLinux_x86_64.h | 181 +- .../Plugins/Process/Linux/NativeThreadLinux.cpp | 759 +- .../Plugins/Process/Linux/NativeThreadLinux.h | 145 +- .../Plugins/Process/Linux/ProcFileReader.cpp | 139 +- lldb/source/Plugins/Process/Linux/ProcFileReader.h | 24 +- lldb/source/Plugins/Process/Linux/Procfs.h | 14 +- .../Plugins/Process/Linux/SingleStepCheck.cpp | 249 +- .../source/Plugins/Process/Linux/SingleStepCheck.h | 35 +- .../Process/MacOSX-Kernel/CommunicationKDP.cpp | 2397 +- .../Process/MacOSX-Kernel/CommunicationKDP.h | 548 +- .../Plugins/Process/MacOSX-Kernel/ProcessKDP.cpp | 1830 +- .../Plugins/Process/MacOSX-Kernel/ProcessKDP.h | 417 +- .../Process/MacOSX-Kernel/ProcessKDPLog.cpp | 302 +- .../Plugins/Process/MacOSX-Kernel/ProcessKDPLog.h | 55 +- .../MacOSX-Kernel/RegisterContextKDP_arm.cpp | 224 +- .../Process/MacOSX-Kernel/RegisterContextKDP_arm.h | 53 +- .../MacOSX-Kernel/RegisterContextKDP_arm64.cpp | 227 +- .../MacOSX-Kernel/RegisterContextKDP_arm64.h | 56 +- .../MacOSX-Kernel/RegisterContextKDP_i386.cpp | 170 +- .../MacOSX-Kernel/RegisterContextKDP_i386.h | 48 +- .../MacOSX-Kernel/RegisterContextKDP_x86_64.cpp | 171 +- .../MacOSX-Kernel/RegisterContextKDP_x86_64.h | 49 +- .../Plugins/Process/MacOSX-Kernel/ThreadKDP.cpp | 268 +- .../Plugins/Process/MacOSX-Kernel/ThreadKDP.h | 101 +- lldb/source/Plugins/Process/POSIX/CrashReason.cpp | 501 +- lldb/source/Plugins/Process/POSIX/CrashReason.h | 72 +- .../Plugins/Process/POSIX/ProcessMessage.cpp | 103 +- lldb/source/Plugins/Process/POSIX/ProcessMessage.h | 299 +- .../Plugins/Process/POSIX/ProcessPOSIXLog.cpp | 311 +- .../source/Plugins/Process/POSIX/ProcessPOSIXLog.h | 169 +- lldb/source/Plugins/Process/Utility/ARMDefines.h | 252 +- lldb/source/Plugins/Process/Utility/ARMUtils.h | 567 +- .../Process/Utility/DynamicRegisterInfo.cpp | 1379 +- .../Plugins/Process/Utility/DynamicRegisterInfo.h | 115 +- .../Plugins/Process/Utility/FreeBSDSignals.cpp | 146 +- .../Plugins/Process/Utility/FreeBSDSignals.h | 8 +- .../Plugins/Process/Utility/GDBRemoteSignals.cpp | 16 +- .../Plugins/Process/Utility/GDBRemoteSignals.h | 10 +- .../Plugins/Process/Utility/HistoryThread.cpp | 106 +- .../source/Plugins/Process/Utility/HistoryThread.h | 158 +- .../Plugins/Process/Utility/HistoryUnwind.cpp | 86 +- .../source/Plugins/Process/Utility/HistoryUnwind.h | 31 +- .../Plugins/Process/Utility/InferiorCallPOSIX.cpp | 386 +- .../Plugins/Process/Utility/InferiorCallPOSIX.h | 8 +- .../Plugins/Process/Utility/InstructionUtils.h | 138 +- .../Plugins/Process/Utility/LinuxSignals.cpp | 153 +- lldb/source/Plugins/Process/Utility/LinuxSignals.h | 8 +- .../Plugins/Process/Utility/MipsLinuxSignals.cpp | 156 +- .../Plugins/Process/Utility/MipsLinuxSignals.h | 11 +- .../Plugins/Process/Utility/NetBSDSignals.cpp | 22 +- .../source/Plugins/Process/Utility/NetBSDSignals.h | 8 +- .../Process/Utility/RegisterContextDarwin_arm.cpp | 2654 ++- .../Process/Utility/RegisterContextDarwin_arm.h | 447 +- .../Utility/RegisterContextDarwin_arm64.cpp | 1551 +- .../Process/Utility/RegisterContextDarwin_arm64.h | 428 +- .../Process/Utility/RegisterContextDarwin_i386.cpp | 1582 +- .../Process/Utility/RegisterContextDarwin_i386.h | 393 +- .../Utility/RegisterContextDarwin_x86_64.cpp | 1756 +- .../Process/Utility/RegisterContextDarwin_x86_64.h | 434 +- .../Process/Utility/RegisterContextDummy.cpp | 148 +- .../Plugins/Process/Utility/RegisterContextDummy.h | 76 +- .../Process/Utility/RegisterContextFreeBSD_arm.cpp | 100 +- .../Process/Utility/RegisterContextFreeBSD_arm.h | 98 +- .../Utility/RegisterContextFreeBSD_arm64.cpp | 105 +- .../Process/Utility/RegisterContextFreeBSD_arm64.h | 91 +- .../Utility/RegisterContextFreeBSD_i386.cpp | 102 +- .../Process/Utility/RegisterContextFreeBSD_i386.h | 15 +- .../Utility/RegisterContextFreeBSD_mips64.cpp | 120 +- .../Utility/RegisterContextFreeBSD_mips64.h | 16 +- .../Utility/RegisterContextFreeBSD_powerpc.cpp | 406 +- .../Utility/RegisterContextFreeBSD_powerpc.h | 55 +- .../Utility/RegisterContextFreeBSD_x86_64.cpp | 222 +- .../Utility/RegisterContextFreeBSD_x86_64.h | 20 +- .../Process/Utility/RegisterContextHistory.cpp | 151 +- .../Process/Utility/RegisterContextHistory.h | 80 +- .../Process/Utility/RegisterContextLLDB.cpp | 3708 ++- .../Plugins/Process/Utility/RegisterContextLLDB.h | 437 +- .../Process/Utility/RegisterContextLinux_arm.cpp | 100 +- .../Process/Utility/RegisterContextLinux_arm.h | 99 +- .../Process/Utility/RegisterContextLinux_arm64.cpp | 106 +- .../Process/Utility/RegisterContextLinux_arm64.h | 94 +- .../Process/Utility/RegisterContextLinux_i386.cpp | 200 +- .../Process/Utility/RegisterContextLinux_i386.h | 24 +- .../Process/Utility/RegisterContextLinux_mips.cpp | 62 +- .../Process/Utility/RegisterContextLinux_mips.h | 23 +- .../Utility/RegisterContextLinux_mips64.cpp | 139 +- .../Process/Utility/RegisterContextLinux_mips64.h | 29 +- .../Process/Utility/RegisterContextLinux_s390x.cpp | 95 +- .../Process/Utility/RegisterContextLinux_s390x.h | 29 +- .../Utility/RegisterContextLinux_x86_64.cpp | 304 +- .../Process/Utility/RegisterContextLinux_x86_64.h | 31 +- .../RegisterContextMacOSXFrameBackchain.cpp | 252 +- .../Utility/RegisterContextMacOSXFrameBackchain.h | 59 +- .../Process/Utility/RegisterContextMach_arm.cpp | 72 +- .../Process/Utility/RegisterContextMach_arm.h | 49 +- .../Process/Utility/RegisterContextMach_i386.cpp | 57 +- .../Process/Utility/RegisterContextMach_i386.h | 45 +- .../Process/Utility/RegisterContextMach_x86_64.cpp | 60 +- .../Process/Utility/RegisterContextMach_x86_64.h | 48 +- .../Process/Utility/RegisterContextMemory.cpp | 204 +- .../Process/Utility/RegisterContextMemory.h | 107 +- .../Utility/RegisterContextNetBSD_x86_64.cpp | 552 +- .../Process/Utility/RegisterContextNetBSD_x86_64.h | 20 +- .../Process/Utility/RegisterContextPOSIX_arm.cpp | 385 +- .../Process/Utility/RegisterContextPOSIX_arm.h | 158 +- .../Process/Utility/RegisterContextPOSIX_arm64.cpp | 352 +- .../Process/Utility/RegisterContextPOSIX_arm64.h | 157 +- .../Utility/RegisterContextPOSIX_mips64.cpp | 265 +- .../Process/Utility/RegisterContextPOSIX_mips64.h | 83 +- .../Utility/RegisterContextPOSIX_powerpc.cpp | 368 +- .../Process/Utility/RegisterContextPOSIX_powerpc.h | 330 +- .../Process/Utility/RegisterContextPOSIX_s390x.cpp | 289 +- .../Process/Utility/RegisterContextPOSIX_s390x.h | 111 +- .../Process/Utility/RegisterContextPOSIX_x86.cpp | 1035 +- .../Process/Utility/RegisterContextPOSIX_x86.h | 321 +- .../Utility/RegisterContextThreadMemory.cpp | 390 +- .../Process/Utility/RegisterContextThreadMemory.h | 163 +- .../Plugins/Process/Utility/RegisterContext_mips.h | 699 +- .../Process/Utility/RegisterContext_powerpc.h | 219 +- .../Process/Utility/RegisterContext_s390x.h | 148 +- .../Plugins/Process/Utility/RegisterContext_x86.h | 512 +- .../Process/Utility/RegisterInfoInterface.h | 99 +- .../Plugins/Process/Utility/RegisterInfos_arm.h | 2027 +- .../Plugins/Process/Utility/RegisterInfos_arm64.h | 1345 +- .../Plugins/Process/Utility/RegisterInfos_i386.h | 336 +- .../Plugins/Process/Utility/RegisterInfos_mips.h | 430 +- .../Plugins/Process/Utility/RegisterInfos_mips64.h | 579 +- .../Process/Utility/RegisterInfos_powerpc.h | 329 +- .../Plugins/Process/Utility/RegisterInfos_s390x.h | 93 +- .../Plugins/Process/Utility/RegisterInfos_x86_64.h | 708 +- .../Process/Utility/StopInfoMachException.cpp | 1020 +- .../Process/Utility/StopInfoMachException.h | 71 +- .../Plugins/Process/Utility/ThreadMemory.cpp | 171 +- lldb/source/Plugins/Process/Utility/ThreadMemory.h | 201 +- lldb/source/Plugins/Process/Utility/UnwindLLDB.cpp | 880 +- lldb/source/Plugins/Process/Utility/UnwindLLDB.h | 248 +- .../Process/Utility/UnwindMacOSXFrameBackchain.cpp | 443 +- .../Process/Utility/UnwindMacOSXFrameBackchain.h | 68 +- .../Process/Utility/lldb-arm-register-enums.h | 363 +- .../Process/Utility/lldb-arm64-register-enums.h | 300 +- .../Utility/lldb-mips-freebsd-register-enums.h | 107 +- .../Utility/lldb-mips-linux-register-enums.h | 522 +- .../Process/Utility/lldb-s390x-register-enums.h | 139 +- .../Process/Utility/lldb-x86-register-enums.h | 532 +- .../Process/Windows/Common/ExceptionRecord.h | 103 +- .../Plugins/Process/Windows/Common/NtStructures.h | 23 +- .../Process/Windows/Common/ProcessWindows.cpp | 85 +- .../Process/Windows/Common/ProcessWindows.h | 44 +- .../Process/Windows/Common/ProcessWindowsLog.cpp | 260 +- .../Process/Windows/Common/ProcessWindowsLog.h | 151 +- .../Windows/Common/RegisterContextWindows.cpp | 169 +- .../Windows/Common/RegisterContextWindows.h | 64 +- .../Process/Windows/Common/TargetThreadWindows.cpp | 103 +- .../Process/Windows/Common/TargetThreadWindows.h | 46 +- .../Common/x64/RegisterContextWindows_x64.cpp | 437 +- .../Common/x64/RegisterContextWindows_x64.h | 40 +- .../Common/x86/RegisterContextWindows_x86.cpp | 266 +- .../Common/x86/RegisterContextWindows_x86.h | 42 +- .../Process/Windows/Live/DebuggerThread.cpp | 858 +- .../Plugins/Process/Windows/Live/DebuggerThread.h | 139 +- .../Plugins/Process/Windows/Live/ForwardDecl.h | 19 +- .../Plugins/Process/Windows/Live/IDebugDelegate.h | 30 +- .../Process/Windows/Live/LocalDebugDelegate.cpp | 90 +- .../Process/Windows/Live/LocalDebugDelegate.h | 43 +- .../Process/Windows/Live/ProcessWindowsLive.cpp | 1765 +- .../Process/Windows/Live/ProcessWindowsLive.h | 178 +- .../Windows/Live/TargetThreadWindowsLive.cpp | 153 +- .../Process/Windows/Live/TargetThreadWindowsLive.h | 55 +- .../Live/x64/RegisterContextWindowsLive_x64.cpp | 277 +- .../Live/x64/RegisterContextWindowsLive_x64.h | 32 +- .../Live/x86/RegisterContextWindowsLive_x86.cpp | 152 +- .../Live/x86/RegisterContextWindowsLive_x86.h | 24 +- .../Windows/MiniDump/ProcessWinMiniDump.cpp | 1093 +- .../Process/Windows/MiniDump/ProcessWinMiniDump.h | 96 +- .../Process/Windows/MiniDump/ThreadWinMiniDump.cpp | 97 +- .../Process/Windows/MiniDump/ThreadWinMiniDump.h | 32 +- .../x64/RegisterContextWindowsMiniDump_x64.cpp | 45 +- .../x64/RegisterContextWindowsMiniDump_x64.h | 24 +- .../x86/RegisterContextWindowsMiniDump_x86.cpp | 45 +- .../x86/RegisterContextWindowsMiniDump_x86.h | 27 +- .../Plugins/Process/elf-core/ProcessElfCore.cpp | 1042 +- .../Plugins/Process/elf-core/ProcessElfCore.h | 229 +- .../elf-core/RegisterContextPOSIXCore_arm.cpp | 96 +- .../elf-core/RegisterContextPOSIXCore_arm.h | 50 +- .../elf-core/RegisterContextPOSIXCore_arm64.cpp | 96 +- .../elf-core/RegisterContextPOSIXCore_arm64.h | 50 +- .../elf-core/RegisterContextPOSIXCore_mips64.cpp | 96 +- .../elf-core/RegisterContextPOSIXCore_mips64.h | 50 +- .../elf-core/RegisterContextPOSIXCore_powerpc.cpp | 165 +- .../elf-core/RegisterContextPOSIXCore_powerpc.h | 66 +- .../elf-core/RegisterContextPOSIXCore_s390x.cpp | 131 +- .../elf-core/RegisterContextPOSIXCore_s390x.h | 50 +- .../elf-core/RegisterContextPOSIXCore_x86_64.cpp | 106 +- .../elf-core/RegisterContextPOSIXCore_x86_64.h | 48 +- .../Plugins/Process/elf-core/ThreadElfCore.cpp | 542 +- .../Plugins/Process/elf-core/ThreadElfCore.h | 265 +- .../Process/gdb-remote/GDBRemoteClientBase.cpp | 658 +- .../Process/gdb-remote/GDBRemoteClientBase.h | 257 +- .../Process/gdb-remote/GDBRemoteCommunication.cpp | 2441 +- .../Process/gdb-remote/GDBRemoteCommunication.h | 507 +- .../gdb-remote/GDBRemoteCommunicationClient.cpp | 6892 +++--- .../gdb-remote/GDBRemoteCommunicationClient.h | 1187 +- .../gdb-remote/GDBRemoteCommunicationServer.cpp | 157 +- .../gdb-remote/GDBRemoteCommunicationServer.h | 60 +- .../GDBRemoteCommunicationServerCommon.cpp | 2030 +- .../GDBRemoteCommunicationServerCommon.h | 195 +- .../GDBRemoteCommunicationServerLLGS.cpp | 5417 ++--- .../gdb-remote/GDBRemoteCommunicationServerLLGS.h | 364 +- .../GDBRemoteCommunicationServerPlatform.cpp | 896 +- .../GDBRemoteCommunicationServerPlatform.h | 128 +- .../gdb-remote/GDBRemoteRegisterContext.cpp | 1497 +- .../Process/gdb-remote/GDBRemoteRegisterContext.h | 164 +- .../Process/gdb-remote/ProcessGDBRemote.cpp | 9240 ++++---- .../Plugins/Process/gdb-remote/ProcessGDBRemote.h | 774 +- .../Process/gdb-remote/ProcessGDBRemoteLog.cpp | 342 +- .../Process/gdb-remote/ProcessGDBRemoteLog.h | 58 +- .../Plugins/Process/gdb-remote/ThreadGDBRemote.cpp | 569 +- .../Plugins/Process/gdb-remote/ThreadGDBRemote.h | 153 +- .../Plugins/Process/mach-core/ProcessMachCore.cpp | 1026 +- .../Plugins/Process/mach-core/ProcessMachCore.h | 258 +- .../Plugins/Process/mach-core/ThreadMachCore.cpp | 139 +- .../Plugins/Process/mach-core/ThreadMachCore.h | 87 +- .../Plugins/Process/minidump/MinidumpParser.cpp | 222 +- .../Plugins/Process/minidump/MinidumpParser.h | 50 +- .../Plugins/Process/minidump/MinidumpTypes.cpp | 122 +- .../Plugins/Process/minidump/MinidumpTypes.h | 436 +- .../None/ScriptInterpreterNone.cpp | 80 +- .../ScriptInterpreter/None/ScriptInterpreterNone.h | 55 +- .../ScriptInterpreter/Python/PythonDataObjects.cpp | 1671 +- .../ScriptInterpreter/Python/PythonDataObjects.h | 714 +- .../Python/PythonExceptionState.cpp | 266 +- .../Python/PythonExceptionState.h | 55 +- .../Python/ScriptInterpreterPython.cpp | 5638 +++-- .../Python/ScriptInterpreterPython.h | 1067 +- .../Plugins/ScriptInterpreter/Python/lldb-python.h | 9 +- .../DarwinLog/StructuredDataDarwinLog.cpp | 3863 ++-- .../DarwinLog/StructuredDataDarwinLog.h | 187 +- lldb/source/Plugins/SymbolFile/DWARF/DIERef.cpp | 113 +- lldb/source/Plugins/SymbolFile/DWARF/DIERef.h | 60 +- .../Plugins/SymbolFile/DWARF/DWARFASTParser.h | 45 +- .../SymbolFile/DWARF/DWARFASTParserClang.cpp | 7612 +++--- .../Plugins/SymbolFile/DWARF/DWARFASTParserClang.h | 246 +- .../Plugins/SymbolFile/DWARF/DWARFASTParserGo.cpp | 1391 +- .../Plugins/SymbolFile/DWARF/DWARFASTParserGo.h | 88 +- .../SymbolFile/DWARF/DWARFASTParserJava.cpp | 932 +- .../Plugins/SymbolFile/DWARF/DWARFASTParserJava.h | 93 +- .../SymbolFile/DWARF/DWARFASTParserOCaml.cpp | 355 +- .../Plugins/SymbolFile/DWARF/DWARFASTParserOCaml.h | 60 +- .../DWARF/DWARFAbbreviationDeclaration.cpp | 139 +- .../DWARF/DWARFAbbreviationDeclaration.h | 101 +- .../Plugins/SymbolFile/DWARF/DWARFAttribute.cpp | 108 +- .../Plugins/SymbolFile/DWARF/DWARFAttribute.h | 106 +- .../Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp | 1997 +- .../Plugins/SymbolFile/DWARF/DWARFCompileUnit.h | 438 +- lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp | 784 +- lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h | 350 +- .../SymbolFile/DWARF/DWARFDIECollection.cpp | 34 +- .../Plugins/SymbolFile/DWARF/DWARFDIECollection.h | 36 +- .../SymbolFile/DWARF/DWARFDataExtractor.cpp | 19 +- .../Plugins/SymbolFile/DWARF/DWARFDataExtractor.h | 31 +- .../Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp | 209 +- .../Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.h | 84 +- .../SymbolFile/DWARF/DWARFDebugArangeSet.cpp | 472 +- .../Plugins/SymbolFile/DWARF/DWARFDebugArangeSet.h | 100 +- .../Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp | 204 +- .../Plugins/SymbolFile/DWARF/DWARFDebugAranges.h | 108 +- .../Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp | 941 +- .../Plugins/SymbolFile/DWARF/DWARFDebugInfo.h | 116 +- .../SymbolFile/DWARF/DWARFDebugInfoEntry.cpp | 3300 ++- .../Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h | 629 +- .../Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp | 1903 +- .../Plugins/SymbolFile/DWARF/DWARFDebugLine.h | 398 +- .../Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.cpp | 43 +- .../Plugins/SymbolFile/DWARF/DWARFDebugMacinfo.h | 17 +- .../SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp | 179 +- .../SymbolFile/DWARF/DWARFDebugMacinfoEntry.h | 47 +- .../Plugins/SymbolFile/DWARF/DWARFDebugMacro.cpp | 187 +- .../Plugins/SymbolFile/DWARF/DWARFDebugMacro.h | 60 +- .../SymbolFile/DWARF/DWARFDebugPubnames.cpp | 436 +- .../Plugins/SymbolFile/DWARF/DWARFDebugPubnames.h | 32 +- .../SymbolFile/DWARF/DWARFDebugPubnamesSet.cpp | 234 +- .../SymbolFile/DWARF/DWARFDebugPubnamesSet.h | 123 +- .../Plugins/SymbolFile/DWARF/DWARFDebugRanges.cpp | 220 +- .../Plugins/SymbolFile/DWARF/DWARFDebugRanges.h | 37 +- .../Plugins/SymbolFile/DWARF/DWARFDeclContext.cpp | 152 +- .../Plugins/SymbolFile/DWARF/DWARFDeclContext.h | 143 +- .../Plugins/SymbolFile/DWARF/DWARFDefines.cpp | 900 +- .../source/Plugins/SymbolFile/DWARF/DWARFDefines.h | 126 +- .../Plugins/SymbolFile/DWARF/DWARFFormValue.cpp | 1068 +- .../Plugins/SymbolFile/DWARF/DWARFFormValue.h | 154 +- .../Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp | 1249 +- .../Plugins/SymbolFile/DWARF/HashedNameToDIE.h | 350 +- .../Plugins/SymbolFile/DWARF/LogChannelDWARF.cpp | 350 +- .../Plugins/SymbolFile/DWARF/LogChannelDWARF.h | 89 +- lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.cpp | 102 +- lldb/source/Plugins/SymbolFile/DWARF/NameToDIE.h | 51 +- .../Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp | 7818 +++---- .../Plugins/SymbolFile/DWARF/SymbolFileDWARF.h | 897 +- .../SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp | 2577 +-- .../SymbolFile/DWARF/SymbolFileDWARFDebugMap.h | 712 +- .../SymbolFile/DWARF/SymbolFileDWARFDwo.cpp | 149 +- .../Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h | 74 +- .../SymbolFile/DWARF/UniqueDWARFASTType.cpp | 118 +- .../Plugins/SymbolFile/DWARF/UniqueDWARFASTType.h | 182 +- .../source/Plugins/SymbolFile/PDB/PDBASTParser.cpp | 367 +- lldb/source/Plugins/SymbolFile/PDB/PDBASTParser.h | 30 +- .../Plugins/SymbolFile/PDB/SymbolFilePDB.cpp | 1167 +- lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h | 244 +- .../Plugins/SymbolFile/Symtab/SymbolFileSymtab.cpp | 445 +- .../Plugins/SymbolFile/Symtab/SymbolFileSymtab.h | 142 +- .../Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp | 249 +- .../Plugins/SymbolVendor/ELF/SymbolVendorELF.h | 52 +- .../SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp | 455 +- .../SymbolVendor/MacOSX/SymbolVendorMacOSX.h | 55 +- .../MacOSX/AppleGetItemInfoHandler.cpp | 519 +- .../SystemRuntime/MacOSX/AppleGetItemInfoHandler.h | 134 +- .../MacOSX/AppleGetPendingItemsHandler.cpp | 523 +- .../MacOSX/AppleGetPendingItemsHandler.h | 141 +- .../SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp | 508 +- .../SystemRuntime/MacOSX/AppleGetQueuesHandler.h | 126 +- .../MacOSX/AppleGetThreadItemInfoHandler.cpp | 523 +- .../MacOSX/AppleGetThreadItemInfoHandler.h | 135 +- .../SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp | 1681 +- .../SystemRuntime/MacOSX/SystemRuntimeMacOSX.h | 506 +- .../InstEmulation/UnwindAssemblyInstEmulation.cpp | 1151 +- .../InstEmulation/UnwindAssemblyInstEmulation.h | 288 +- .../UnwindAssembly/x86/UnwindAssembly-x86.cpp | 2480 +- .../UnwindAssembly/x86/UnwindAssembly-x86.h | 98 +- lldb/source/Symbol/ArmUnwindInfo.cpp | 696 +- lldb/source/Symbol/Block.cpp | 962 +- lldb/source/Symbol/ClangASTContext.cpp | 18296 ++++++++------- lldb/source/Symbol/ClangASTImporter.cpp | 1952 +- .../Symbol/ClangExternalASTSourceCallbacks.cpp | 238 +- .../source/Symbol/ClangExternalASTSourceCommon.cpp | 131 +- lldb/source/Symbol/ClangUtil.cpp | 50 +- lldb/source/Symbol/CompactUnwindInfo.cpp | 2944 ++- lldb/source/Symbol/CompileUnit.cpp | 712 +- lldb/source/Symbol/CompilerDecl.cpp | 60 +- lldb/source/Symbol/CompilerDeclContext.cpp | 94 +- lldb/source/Symbol/CompilerType.cpp | 1786 +- lldb/source/Symbol/DWARFCallFrameInfo.cpp | 1642 +- lldb/source/Symbol/DebugMacros.cpp | 55 +- lldb/source/Symbol/Declaration.cpp | 138 +- lldb/source/Symbol/FuncUnwinders.cpp | 665 +- lldb/source/Symbol/Function.cpp | 1011 +- lldb/source/Symbol/GoASTContext.cpp | 2488 +- lldb/source/Symbol/JavaASTContext.cpp | 2290 +- lldb/source/Symbol/LineEntry.cpp | 445 +- lldb/source/Symbol/LineTable.cpp | 1000 +- lldb/source/Symbol/OCamlASTContext.cpp | 1018 +- lldb/source/Symbol/ObjectFile.cpp | 1142 +- lldb/source/Symbol/Symbol.cpp | 1109 +- lldb/source/Symbol/SymbolContext.cpp | 2400 +- lldb/source/Symbol/SymbolFile.cpp | 218 +- lldb/source/Symbol/SymbolVendor.cpp | 893 +- lldb/source/Symbol/Symtab.cpp | 2061 +- lldb/source/Symbol/Type.cpp | 2151 +- lldb/source/Symbol/TypeList.cpp | 326 +- lldb/source/Symbol/TypeMap.cpp | 382 +- lldb/source/Symbol/TypeSystem.cpp | 360 +- lldb/source/Symbol/UnwindPlan.cpp | 967 +- lldb/source/Symbol/UnwindTable.cpp | 269 +- lldb/source/Symbol/Variable.cpp | 1518 +- lldb/source/Symbol/VariableList.cpp | 346 +- lldb/source/Symbol/VerifyDecl.cpp | 5 +- lldb/source/Target/ABI.cpp | 340 +- lldb/source/Target/CPPLanguageRuntime.cpp | 32 +- lldb/source/Target/ExecutionContext.cpp | 1228 +- lldb/source/Target/FileAction.cpp | 142 +- lldb/source/Target/InstrumentationRuntime.cpp | 98 +- .../Target/InstrumentationRuntimeStopInfo.cpp | 29 +- lldb/source/Target/JITLoader.cpp | 29 +- lldb/source/Target/JITLoaderList.cpp | 74 +- lldb/source/Target/Language.cpp | 670 +- lldb/source/Target/LanguageRuntime.cpp | 527 +- lldb/source/Target/Memory.cpp | 865 +- lldb/source/Target/MemoryHistory.cpp | 26 +- lldb/source/Target/ObjCLanguageRuntime.cpp | 622 +- lldb/source/Target/OperatingSystem.cpp | 65 +- lldb/source/Target/PathMappingList.cpp | 488 +- lldb/source/Target/Platform.cpp | 3330 ++- lldb/source/Target/Process.cpp | 11792 +++++----- lldb/source/Target/ProcessInfo.cpp | 189 +- lldb/source/Target/ProcessLaunchInfo.cpp | 789 +- lldb/source/Target/Queue.cpp | 137 +- lldb/source/Target/QueueItem.cpp | 175 +- lldb/source/Target/QueueList.cpp | 106 +- lldb/source/Target/RegisterContext.cpp | 821 +- lldb/source/Target/SectionLoadHistory.cpp | 257 +- lldb/source/Target/SectionLoadList.cpp | 431 +- lldb/source/Target/StackFrame.cpp | 3680 ++- lldb/source/Target/StackFrameList.cpp | 1522 +- lldb/source/Target/StackID.cpp | 144 +- lldb/source/Target/StopInfo.cpp | 2042 +- lldb/source/Target/StructuredDataPlugin.cpp | 92 +- lldb/source/Target/SystemRuntime.cpp | 66 +- lldb/source/Target/Target.cpp | 7281 +++--- lldb/source/Target/TargetList.cpp | 1152 +- lldb/source/Target/Thread.cpp | 4190 ++-- lldb/source/Target/ThreadCollection.cpp | 90 +- lldb/source/Target/ThreadList.cpp | 1356 +- lldb/source/Target/ThreadPlan.cpp | 438 +- lldb/source/Target/ThreadPlanBase.cpp | 325 +- lldb/source/Target/ThreadPlanCallFunction.cpp | 885 +- .../Target/ThreadPlanCallFunctionUsingABI.cpp | 83 +- .../source/Target/ThreadPlanCallOnFunctionExit.cpp | 145 +- .../source/Target/ThreadPlanCallUserExpression.cpp | 130 +- lldb/source/Target/ThreadPlanPython.cpp | 294 +- lldb/source/Target/ThreadPlanRunToAddress.cpp | 352 +- lldb/source/Target/ThreadPlanShouldStopHere.cpp | 275 +- lldb/source/Target/ThreadPlanStepInRange.cpp | 891 +- lldb/source/Target/ThreadPlanStepInstruction.cpp | 426 +- lldb/source/Target/ThreadPlanStepOut.cpp | 871 +- .../source/Target/ThreadPlanStepOverBreakpoint.cpp | 266 +- lldb/source/Target/ThreadPlanStepOverRange.cpp | 730 +- lldb/source/Target/ThreadPlanStepRange.cpp | 818 +- lldb/source/Target/ThreadPlanStepThrough.cpp | 420 +- lldb/source/Target/ThreadPlanStepUntil.cpp | 596 +- lldb/source/Target/ThreadPlanTracer.cpp | 373 +- lldb/source/Target/ThreadSpec.cpp | 193 +- lldb/source/Target/UnixSignals.cpp | 478 +- lldb/source/Target/UnwindAssembly.cpp | 35 +- lldb/source/Utility/ARM64_DWARF_Registers.cpp | 314 +- lldb/source/Utility/ARM64_DWARF_Registers.h | 158 +- lldb/source/Utility/ARM64_ehframe_Registers.h | 145 +- lldb/source/Utility/ARM_DWARF_Registers.cpp | 1310 +- lldb/source/Utility/ARM_DWARF_Registers.h | 394 +- lldb/source/Utility/ARM_ehframe_Registers.h | 41 +- lldb/source/Utility/ConvertEnum.cpp | 210 +- lldb/source/Utility/JSON.cpp | 1083 +- lldb/source/Utility/KQueue.cpp | 105 +- lldb/source/Utility/KQueue.h | 55 +- lldb/source/Utility/LLDBAssert.cpp | 35 +- lldb/source/Utility/ModuleCache.cpp | 540 +- lldb/source/Utility/ModuleCache.h | 55 +- lldb/source/Utility/NameMatches.cpp | 59 +- lldb/source/Utility/PseudoTerminal.cpp | 322 +- lldb/source/Utility/Range.cpp | 117 +- lldb/source/Utility/RegisterNumber.cpp | 208 +- lldb/source/Utility/SelectHelper.cpp | 413 +- lldb/source/Utility/SharingPtr.cpp | 193 +- lldb/source/Utility/StdStringExtractor.cpp | 685 +- lldb/source/Utility/StringExtractor.cpp | 714 +- lldb/source/Utility/StringExtractorGDBRemote.cpp | 965 +- lldb/source/Utility/StringExtractorGDBRemote.h | 368 +- lldb/source/Utility/StringLexer.cpp | 144 +- lldb/source/Utility/TaskPool.cpp | 102 +- lldb/source/Utility/TimeSpecTimeout.cpp | 50 +- lldb/source/Utility/TimeSpecTimeout.h | 121 +- lldb/source/Utility/UriParser.cpp | 111 +- lldb/source/Utility/UriParser.h | 29 +- lldb/source/lldb.cpp | 132 +- 1130 files changed, 379158 insertions(+), 417744 deletions(-) (limited to 'lldb/source') diff --git a/lldb/source/API/SBAddress.cpp b/lldb/source/API/SBAddress.cpp index 470ea5659f2..0ef374f47a9 100644 --- a/lldb/source/API/SBAddress.cpp +++ b/lldb/source/API/SBAddress.cpp @@ -18,312 +18,227 @@ #include "lldb/Symbol/LineEntry.h" #include "lldb/Target/Target.h" - using namespace lldb; using namespace lldb_private; +SBAddress::SBAddress() : m_opaque_ap(new Address()) {} -SBAddress::SBAddress () : - m_opaque_ap (new Address()) -{ -} - -SBAddress::SBAddress (const Address *lldb_object_ptr) : - m_opaque_ap (new Address()) -{ - if (lldb_object_ptr) - ref() = *lldb_object_ptr; +SBAddress::SBAddress(const Address *lldb_object_ptr) + : m_opaque_ap(new Address()) { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; } -SBAddress::SBAddress (const SBAddress &rhs) : - m_opaque_ap (new Address()) -{ - if (rhs.IsValid()) - ref() = rhs.ref(); +SBAddress::SBAddress(const SBAddress &rhs) : m_opaque_ap(new Address()) { + if (rhs.IsValid()) + ref() = rhs.ref(); } - -SBAddress::SBAddress (lldb::SBSection section, lldb::addr_t offset) : - m_opaque_ap(new Address (section.GetSP(), offset)) -{ -} +SBAddress::SBAddress(lldb::SBSection section, lldb::addr_t offset) + : m_opaque_ap(new Address(section.GetSP(), offset)) {} // Create an address by resolving a load address using the supplied target -SBAddress::SBAddress (lldb::addr_t load_addr, lldb::SBTarget &target) : - m_opaque_ap(new Address()) -{ - SetLoadAddress (load_addr, target); +SBAddress::SBAddress(lldb::addr_t load_addr, lldb::SBTarget &target) + : m_opaque_ap(new Address()) { + SetLoadAddress(load_addr, target); } +SBAddress::~SBAddress() {} - -SBAddress::~SBAddress () -{ -} - -const SBAddress & -SBAddress::operator = (const SBAddress &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset (new Address()); - } - return *this; +const SBAddress &SBAddress::operator=(const SBAddress &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + ref() = rhs.ref(); + else + m_opaque_ap.reset(new Address()); + } + return *this; } -bool -SBAddress::IsValid () const -{ - return m_opaque_ap.get() != NULL && m_opaque_ap->IsValid(); +bool SBAddress::IsValid() const { + return m_opaque_ap.get() != NULL && m_opaque_ap->IsValid(); } -void -SBAddress::Clear () -{ - m_opaque_ap.reset (new Address()); -} +void SBAddress::Clear() { m_opaque_ap.reset(new Address()); } -void -SBAddress::SetAddress (lldb::SBSection section, lldb::addr_t offset) -{ - Address &addr = ref(); - addr.SetSection (section.GetSP()); - addr.SetOffset (offset); +void SBAddress::SetAddress(lldb::SBSection section, lldb::addr_t offset) { + Address &addr = ref(); + addr.SetSection(section.GetSP()); + addr.SetOffset(offset); } - -void -SBAddress::SetAddress (const Address *lldb_object_ptr) -{ - if (lldb_object_ptr) - ref() = *lldb_object_ptr; - else - m_opaque_ap.reset (new Address()); +void SBAddress::SetAddress(const Address *lldb_object_ptr) { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; + else + m_opaque_ap.reset(new Address()); } -lldb::addr_t -SBAddress::GetFileAddress () const -{ - if (m_opaque_ap->IsValid()) - return m_opaque_ap->GetFileAddress(); - else - return LLDB_INVALID_ADDRESS; +lldb::addr_t SBAddress::GetFileAddress() const { + if (m_opaque_ap->IsValid()) + return m_opaque_ap->GetFileAddress(); + else + return LLDB_INVALID_ADDRESS; } -lldb::addr_t -SBAddress::GetLoadAddress (const SBTarget &target) const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - lldb::addr_t addr = LLDB_INVALID_ADDRESS; - TargetSP target_sp (target.GetSP()); - if (target_sp) - { - if (m_opaque_ap->IsValid()) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - addr = m_opaque_ap->GetLoadAddress (target_sp.get()); - } - } +lldb::addr_t SBAddress::GetLoadAddress(const SBTarget &target) const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - { - if (addr == LLDB_INVALID_ADDRESS) - log->Printf ("SBAddress::GetLoadAddress (SBTarget(%p)) => LLDB_INVALID_ADDRESS", - static_cast(target_sp.get())); - else - log->Printf ("SBAddress::GetLoadAddress (SBTarget(%p)) => 0x%" PRIx64, - static_cast(target_sp.get()), addr); + lldb::addr_t addr = LLDB_INVALID_ADDRESS; + TargetSP target_sp(target.GetSP()); + if (target_sp) { + if (m_opaque_ap->IsValid()) { + std::lock_guard guard(target_sp->GetAPIMutex()); + addr = m_opaque_ap->GetLoadAddress(target_sp.get()); } + } - return addr; -} - -void -SBAddress::SetLoadAddress (lldb::addr_t load_addr, lldb::SBTarget &target) -{ - // Create the address object if we don't already have one - ref(); - if (target.IsValid()) - *this = target.ResolveLoadAddress(load_addr); + if (log) { + if (addr == LLDB_INVALID_ADDRESS) + log->Printf( + "SBAddress::GetLoadAddress (SBTarget(%p)) => LLDB_INVALID_ADDRESS", + static_cast(target_sp.get())); else - m_opaque_ap->Clear(); - - // Check if we weren't were able to resolve a section offset address. - // If we weren't it is ok, the load address might be a location on the - // stack or heap, so we should just have an address with no section and - // a valid offset - if (!m_opaque_ap->IsValid()) - m_opaque_ap->SetOffset(load_addr); -} - -bool -SBAddress::OffsetAddress (addr_t offset) -{ - if (m_opaque_ap->IsValid()) - { - addr_t addr_offset = m_opaque_ap->GetOffset(); - if (addr_offset != LLDB_INVALID_ADDRESS) - { - m_opaque_ap->SetOffset(addr_offset + offset); - return true; - } + log->Printf("SBAddress::GetLoadAddress (SBTarget(%p)) => 0x%" PRIx64, + static_cast(target_sp.get()), addr); + } + + return addr; +} + +void SBAddress::SetLoadAddress(lldb::addr_t load_addr, lldb::SBTarget &target) { + // Create the address object if we don't already have one + ref(); + if (target.IsValid()) + *this = target.ResolveLoadAddress(load_addr); + else + m_opaque_ap->Clear(); + + // Check if we weren't were able to resolve a section offset address. + // If we weren't it is ok, the load address might be a location on the + // stack or heap, so we should just have an address with no section and + // a valid offset + if (!m_opaque_ap->IsValid()) + m_opaque_ap->SetOffset(load_addr); +} + +bool SBAddress::OffsetAddress(addr_t offset) { + if (m_opaque_ap->IsValid()) { + addr_t addr_offset = m_opaque_ap->GetOffset(); + if (addr_offset != LLDB_INVALID_ADDRESS) { + m_opaque_ap->SetOffset(addr_offset + offset); + return true; } - return false; + } + return false; } -lldb::SBSection -SBAddress::GetSection () -{ - lldb::SBSection sb_section; - if (m_opaque_ap->IsValid()) - sb_section.SetSP (m_opaque_ap->GetSection()); - return sb_section; +lldb::SBSection SBAddress::GetSection() { + lldb::SBSection sb_section; + if (m_opaque_ap->IsValid()) + sb_section.SetSP(m_opaque_ap->GetSection()); + return sb_section; } -lldb::addr_t -SBAddress::GetOffset () -{ - if (m_opaque_ap->IsValid()) - return m_opaque_ap->GetOffset(); - return 0; +lldb::addr_t SBAddress::GetOffset() { + if (m_opaque_ap->IsValid()) + return m_opaque_ap->GetOffset(); + return 0; } -Address * -SBAddress::operator->() -{ - return m_opaque_ap.get(); -} +Address *SBAddress::operator->() { return m_opaque_ap.get(); } -const Address * -SBAddress::operator->() const -{ - return m_opaque_ap.get(); -} +const Address *SBAddress::operator->() const { return m_opaque_ap.get(); } -Address & -SBAddress::ref () -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new Address()); - return *m_opaque_ap; +Address &SBAddress::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new Address()); + return *m_opaque_ap; } -const Address & -SBAddress::ref () const -{ - // This object should already have checked with "IsValid()" - // prior to calling this function. In case you didn't we will assert - // and die to let you know. - assert (m_opaque_ap.get()); - return *m_opaque_ap; +const Address &SBAddress::ref() const { + // This object should already have checked with "IsValid()" + // prior to calling this function. In case you didn't we will assert + // and die to let you know. + assert(m_opaque_ap.get()); + return *m_opaque_ap; } -Address * -SBAddress::get () -{ - return m_opaque_ap.get(); -} +Address *SBAddress::get() { return m_opaque_ap.get(); } -bool -SBAddress::GetDescription (SBStream &description) -{ - // Call "ref()" on the stream to make sure it creates a backing stream in - // case there isn't one already... - Stream &strm = description.ref(); - if (m_opaque_ap->IsValid()) - { - m_opaque_ap->Dump (&strm, - NULL, - Address::DumpStyleResolvedDescription, - Address::DumpStyleModuleWithFileAddress, - 4); - StreamString sstrm; -// m_opaque_ap->Dump (&sstrm, NULL, Address::DumpStyleResolvedDescription, Address::DumpStyleInvalid, 4); -// if (sstrm.GetData()) -// strm.Printf (" (%s)", sstrm.GetData()); - } - else - strm.PutCString ("No value"); +bool SBAddress::GetDescription(SBStream &description) { + // Call "ref()" on the stream to make sure it creates a backing stream in + // case there isn't one already... + Stream &strm = description.ref(); + if (m_opaque_ap->IsValid()) { + m_opaque_ap->Dump(&strm, NULL, Address::DumpStyleResolvedDescription, + Address::DumpStyleModuleWithFileAddress, 4); + StreamString sstrm; + // m_opaque_ap->Dump (&sstrm, NULL, + // Address::DumpStyleResolvedDescription, Address::DumpStyleInvalid, + // 4); + // if (sstrm.GetData()) + // strm.Printf (" (%s)", sstrm.GetData()); + } else + strm.PutCString("No value"); - return true; + return true; } -SBModule -SBAddress::GetModule () -{ - SBModule sb_module; - if (m_opaque_ap->IsValid()) - sb_module.SetSP (m_opaque_ap->GetModule()); - return sb_module; +SBModule SBAddress::GetModule() { + SBModule sb_module; + if (m_opaque_ap->IsValid()) + sb_module.SetSP(m_opaque_ap->GetModule()); + return sb_module; } -SBSymbolContext -SBAddress::GetSymbolContext (uint32_t resolve_scope) -{ - SBSymbolContext sb_sc; - if (m_opaque_ap->IsValid()) - m_opaque_ap->CalculateSymbolContext (&sb_sc.ref(), resolve_scope); - return sb_sc; +SBSymbolContext SBAddress::GetSymbolContext(uint32_t resolve_scope) { + SBSymbolContext sb_sc; + if (m_opaque_ap->IsValid()) + m_opaque_ap->CalculateSymbolContext(&sb_sc.ref(), resolve_scope); + return sb_sc; } -SBCompileUnit -SBAddress::GetCompileUnit () -{ - SBCompileUnit sb_comp_unit; - if (m_opaque_ap->IsValid()) - sb_comp_unit.reset(m_opaque_ap->CalculateSymbolContextCompileUnit()); - return sb_comp_unit; +SBCompileUnit SBAddress::GetCompileUnit() { + SBCompileUnit sb_comp_unit; + if (m_opaque_ap->IsValid()) + sb_comp_unit.reset(m_opaque_ap->CalculateSymbolContextCompileUnit()); + return sb_comp_unit; } -SBFunction -SBAddress::GetFunction () -{ - SBFunction sb_function; - if (m_opaque_ap->IsValid()) - sb_function.reset(m_opaque_ap->CalculateSymbolContextFunction()); - return sb_function; +SBFunction SBAddress::GetFunction() { + SBFunction sb_function; + if (m_opaque_ap->IsValid()) + sb_function.reset(m_opaque_ap->CalculateSymbolContextFunction()); + return sb_function; } -SBBlock -SBAddress::GetBlock () -{ - SBBlock sb_block; - if (m_opaque_ap->IsValid()) - sb_block.SetPtr(m_opaque_ap->CalculateSymbolContextBlock()); - return sb_block; +SBBlock SBAddress::GetBlock() { + SBBlock sb_block; + if (m_opaque_ap->IsValid()) + sb_block.SetPtr(m_opaque_ap->CalculateSymbolContextBlock()); + return sb_block; } -SBSymbol -SBAddress::GetSymbol () -{ - SBSymbol sb_symbol; - if (m_opaque_ap->IsValid()) - sb_symbol.reset(m_opaque_ap->CalculateSymbolContextSymbol()); - return sb_symbol; +SBSymbol SBAddress::GetSymbol() { + SBSymbol sb_symbol; + if (m_opaque_ap->IsValid()) + sb_symbol.reset(m_opaque_ap->CalculateSymbolContextSymbol()); + return sb_symbol; } -SBLineEntry -SBAddress::GetLineEntry () -{ - SBLineEntry sb_line_entry; - if (m_opaque_ap->IsValid()) - { - LineEntry line_entry; - if (m_opaque_ap->CalculateSymbolContextLineEntry (line_entry)) - sb_line_entry.SetLineEntry (line_entry); - } - return sb_line_entry; +SBLineEntry SBAddress::GetLineEntry() { + SBLineEntry sb_line_entry; + if (m_opaque_ap->IsValid()) { + LineEntry line_entry; + if (m_opaque_ap->CalculateSymbolContextLineEntry(line_entry)) + sb_line_entry.SetLineEntry(line_entry); + } + return sb_line_entry; } -AddressClass -SBAddress::GetAddressClass () -{ - if (m_opaque_ap->IsValid()) - return m_opaque_ap->GetAddressClass(); - return eAddressClassInvalid; +AddressClass SBAddress::GetAddressClass() { + if (m_opaque_ap->IsValid()) + return m_opaque_ap->GetAddressClass(); + return eAddressClassInvalid; } - diff --git a/lldb/source/API/SBAttachInfo.cpp b/lldb/source/API/SBAttachInfo.cpp index 0f2ab7afc9c..e6500c468ec 100644 --- a/lldb/source/API/SBAttachInfo.cpp +++ b/lldb/source/API/SBAttachInfo.cpp @@ -16,243 +16,152 @@ using namespace lldb; using namespace lldb_private; +SBAttachInfo::SBAttachInfo() : m_opaque_sp(new ProcessAttachInfo()) {} -SBAttachInfo::SBAttachInfo () : - m_opaque_sp (new ProcessAttachInfo()) -{ +SBAttachInfo::SBAttachInfo(lldb::pid_t pid) + : m_opaque_sp(new ProcessAttachInfo()) { + m_opaque_sp->SetProcessID(pid); } -SBAttachInfo::SBAttachInfo (lldb::pid_t pid) : - m_opaque_sp (new ProcessAttachInfo()) -{ - m_opaque_sp->SetProcessID (pid); +SBAttachInfo::SBAttachInfo(const char *path, bool wait_for) + : m_opaque_sp(new ProcessAttachInfo()) { + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, false); + m_opaque_sp->SetWaitForLaunch(wait_for); } -SBAttachInfo::SBAttachInfo (const char *path, bool wait_for) : - m_opaque_sp (new ProcessAttachInfo()) -{ - if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); - m_opaque_sp->SetWaitForLaunch (wait_for); +SBAttachInfo::SBAttachInfo(const char *path, bool wait_for, bool async) + : m_opaque_sp(new ProcessAttachInfo()) { + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, false); + m_opaque_sp->SetWaitForLaunch(wait_for); + m_opaque_sp->SetAsync(async); } -SBAttachInfo::SBAttachInfo (const char *path, bool wait_for, bool async) : - m_opaque_sp (new ProcessAttachInfo()) -{ - if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); - m_opaque_sp->SetWaitForLaunch (wait_for); - m_opaque_sp->SetAsync(async); +SBAttachInfo::SBAttachInfo(const SBAttachInfo &rhs) + : m_opaque_sp(new ProcessAttachInfo()) { + *m_opaque_sp = *rhs.m_opaque_sp; } -SBAttachInfo::SBAttachInfo (const SBAttachInfo &rhs) : - m_opaque_sp (new ProcessAttachInfo()) -{ - *m_opaque_sp = *rhs.m_opaque_sp; -} +SBAttachInfo::~SBAttachInfo() {} -SBAttachInfo::~SBAttachInfo() -{ -} +lldb_private::ProcessAttachInfo &SBAttachInfo::ref() { return *m_opaque_sp; } -lldb_private::ProcessAttachInfo & -SBAttachInfo::ref () -{ - return *m_opaque_sp; -} - -SBAttachInfo & -SBAttachInfo::operator = (const SBAttachInfo &rhs) -{ - if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; +SBAttachInfo &SBAttachInfo::operator=(const SBAttachInfo &rhs) { + if (this != &rhs) + *m_opaque_sp = *rhs.m_opaque_sp; + return *this; } -lldb::pid_t -SBAttachInfo::GetProcessID () -{ - return m_opaque_sp->GetProcessID(); -} +lldb::pid_t SBAttachInfo::GetProcessID() { return m_opaque_sp->GetProcessID(); } -void -SBAttachInfo::SetProcessID (lldb::pid_t pid) -{ - m_opaque_sp->SetProcessID (pid); +void SBAttachInfo::SetProcessID(lldb::pid_t pid) { + m_opaque_sp->SetProcessID(pid); } - -uint32_t -SBAttachInfo::GetResumeCount () -{ - return m_opaque_sp->GetResumeCount(); +uint32_t SBAttachInfo::GetResumeCount() { + return m_opaque_sp->GetResumeCount(); } -void -SBAttachInfo::SetResumeCount (uint32_t c) -{ - m_opaque_sp->SetResumeCount (c); +void SBAttachInfo::SetResumeCount(uint32_t c) { + m_opaque_sp->SetResumeCount(c); } -const char * -SBAttachInfo::GetProcessPluginName () -{ - return m_opaque_sp->GetProcessPluginName(); +const char *SBAttachInfo::GetProcessPluginName() { + return m_opaque_sp->GetProcessPluginName(); } -void -SBAttachInfo::SetProcessPluginName (const char *plugin_name) -{ - return m_opaque_sp->SetProcessPluginName (plugin_name); +void SBAttachInfo::SetProcessPluginName(const char *plugin_name) { + return m_opaque_sp->SetProcessPluginName(plugin_name); } -void -SBAttachInfo::SetExecutable (const char *path) -{ - if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); - else - m_opaque_sp->GetExecutableFile().Clear(); +void SBAttachInfo::SetExecutable(const char *path) { + if (path && path[0]) + m_opaque_sp->GetExecutableFile().SetFile(path, false); + else + m_opaque_sp->GetExecutableFile().Clear(); } -void -SBAttachInfo::SetExecutable (SBFileSpec exe_file) -{ - if (exe_file.IsValid()) - m_opaque_sp->GetExecutableFile() = exe_file.ref(); - else - m_opaque_sp->GetExecutableFile().Clear(); +void SBAttachInfo::SetExecutable(SBFileSpec exe_file) { + if (exe_file.IsValid()) + m_opaque_sp->GetExecutableFile() = exe_file.ref(); + else + m_opaque_sp->GetExecutableFile().Clear(); } -bool -SBAttachInfo::GetWaitForLaunch () -{ - return m_opaque_sp->GetWaitForLaunch(); +bool SBAttachInfo::GetWaitForLaunch() { + return m_opaque_sp->GetWaitForLaunch(); } -void -SBAttachInfo::SetWaitForLaunch (bool b) -{ - m_opaque_sp->SetWaitForLaunch (b); +void SBAttachInfo::SetWaitForLaunch(bool b) { + m_opaque_sp->SetWaitForLaunch(b); } -void -SBAttachInfo::SetWaitForLaunch (bool b, bool async) -{ - m_opaque_sp->SetWaitForLaunch (b); - m_opaque_sp->SetAsync(async); +void SBAttachInfo::SetWaitForLaunch(bool b, bool async) { + m_opaque_sp->SetWaitForLaunch(b); + m_opaque_sp->SetAsync(async); } -bool -SBAttachInfo::GetIgnoreExisting () -{ - return m_opaque_sp->GetIgnoreExisting(); +bool SBAttachInfo::GetIgnoreExisting() { + return m_opaque_sp->GetIgnoreExisting(); } -void -SBAttachInfo::SetIgnoreExisting (bool b) -{ - m_opaque_sp->SetIgnoreExisting (b); +void SBAttachInfo::SetIgnoreExisting(bool b) { + m_opaque_sp->SetIgnoreExisting(b); } -uint32_t -SBAttachInfo::GetUserID() -{ - return m_opaque_sp->GetUserID(); -} +uint32_t SBAttachInfo::GetUserID() { return m_opaque_sp->GetUserID(); } -uint32_t -SBAttachInfo::GetGroupID() -{ - return m_opaque_sp->GetGroupID(); -} +uint32_t SBAttachInfo::GetGroupID() { return m_opaque_sp->GetGroupID(); } -bool -SBAttachInfo::UserIDIsValid () -{ - return m_opaque_sp->UserIDIsValid(); -} +bool SBAttachInfo::UserIDIsValid() { return m_opaque_sp->UserIDIsValid(); } -bool -SBAttachInfo::GroupIDIsValid () -{ - return m_opaque_sp->GroupIDIsValid(); -} +bool SBAttachInfo::GroupIDIsValid() { return m_opaque_sp->GroupIDIsValid(); } -void -SBAttachInfo::SetUserID (uint32_t uid) -{ - m_opaque_sp->SetUserID (uid); -} +void SBAttachInfo::SetUserID(uint32_t uid) { m_opaque_sp->SetUserID(uid); } -void -SBAttachInfo::SetGroupID (uint32_t gid) -{ - m_opaque_sp->SetGroupID (gid); -} +void SBAttachInfo::SetGroupID(uint32_t gid) { m_opaque_sp->SetGroupID(gid); } -uint32_t -SBAttachInfo::GetEffectiveUserID() -{ - return m_opaque_sp->GetEffectiveUserID(); +uint32_t SBAttachInfo::GetEffectiveUserID() { + return m_opaque_sp->GetEffectiveUserID(); } -uint32_t -SBAttachInfo::GetEffectiveGroupID() -{ - return m_opaque_sp->GetEffectiveGroupID(); +uint32_t SBAttachInfo::GetEffectiveGroupID() { + return m_opaque_sp->GetEffectiveGroupID(); } -bool -SBAttachInfo::EffectiveUserIDIsValid () -{ - return m_opaque_sp->EffectiveUserIDIsValid(); +bool SBAttachInfo::EffectiveUserIDIsValid() { + return m_opaque_sp->EffectiveUserIDIsValid(); } -bool -SBAttachInfo::EffectiveGroupIDIsValid () -{ - return m_opaque_sp->EffectiveGroupIDIsValid (); +bool SBAttachInfo::EffectiveGroupIDIsValid() { + return m_opaque_sp->EffectiveGroupIDIsValid(); } -void -SBAttachInfo::SetEffectiveUserID (uint32_t uid) -{ - m_opaque_sp->SetEffectiveUserID(uid); +void SBAttachInfo::SetEffectiveUserID(uint32_t uid) { + m_opaque_sp->SetEffectiveUserID(uid); } -void -SBAttachInfo::SetEffectiveGroupID (uint32_t gid) -{ - m_opaque_sp->SetEffectiveGroupID(gid); +void SBAttachInfo::SetEffectiveGroupID(uint32_t gid) { + m_opaque_sp->SetEffectiveGroupID(gid); } -lldb::pid_t -SBAttachInfo::GetParentProcessID () -{ - return m_opaque_sp->GetParentProcessID(); +lldb::pid_t SBAttachInfo::GetParentProcessID() { + return m_opaque_sp->GetParentProcessID(); } -void -SBAttachInfo::SetParentProcessID (lldb::pid_t pid) -{ - m_opaque_sp->SetParentProcessID (pid); +void SBAttachInfo::SetParentProcessID(lldb::pid_t pid) { + m_opaque_sp->SetParentProcessID(pid); } -bool -SBAttachInfo::ParentProcessIDIsValid() -{ - return m_opaque_sp->ParentProcessIDIsValid(); +bool SBAttachInfo::ParentProcessIDIsValid() { + return m_opaque_sp->ParentProcessIDIsValid(); } -SBListener -SBAttachInfo::GetListener () -{ - return SBListener(m_opaque_sp->GetListener()); +SBListener SBAttachInfo::GetListener() { + return SBListener(m_opaque_sp->GetListener()); } -void -SBAttachInfo::SetListener (SBListener &listener) -{ - m_opaque_sp->SetListener(listener.GetSP()); +void SBAttachInfo::SetListener(SBListener &listener) { + m_opaque_sp->SetListener(listener.GetSP()); } diff --git a/lldb/source/API/SBBlock.cpp b/lldb/source/API/SBBlock.cpp index 03ee7343c9f..471b7fbebb2 100644 --- a/lldb/source/API/SBBlock.cpp +++ b/lldb/source/API/SBBlock.cpp @@ -26,362 +26,272 @@ using namespace lldb; using namespace lldb_private; +SBBlock::SBBlock() : m_opaque_ptr(NULL) {} -SBBlock::SBBlock () : - m_opaque_ptr (NULL) -{ -} +SBBlock::SBBlock(lldb_private::Block *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} -SBBlock::SBBlock (lldb_private::Block *lldb_object_ptr) : - m_opaque_ptr (lldb_object_ptr) -{ -} +SBBlock::SBBlock(const SBBlock &rhs) : m_opaque_ptr(rhs.m_opaque_ptr) {} -SBBlock::SBBlock(const SBBlock &rhs) : - m_opaque_ptr (rhs.m_opaque_ptr) -{ +const SBBlock &SBBlock::operator=(const SBBlock &rhs) { + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; } -const SBBlock & -SBBlock::operator = (const SBBlock &rhs) -{ - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; -} +SBBlock::~SBBlock() { m_opaque_ptr = NULL; } -SBBlock::~SBBlock () -{ - m_opaque_ptr = NULL; -} +bool SBBlock::IsValid() const { return m_opaque_ptr != NULL; } -bool -SBBlock::IsValid () const -{ - return m_opaque_ptr != NULL; +bool SBBlock::IsInlined() const { + if (m_opaque_ptr) + return m_opaque_ptr->GetInlinedFunctionInfo() != NULL; + return false; } -bool -SBBlock::IsInlined () const -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetInlinedFunctionInfo () != NULL; - return false; -} - -const char * -SBBlock::GetInlinedName () const -{ - if (m_opaque_ptr) - { - const InlineFunctionInfo* inlined_info = m_opaque_ptr->GetInlinedFunctionInfo (); - if (inlined_info) - { - Function *function = m_opaque_ptr->CalculateSymbolContextFunction(); - LanguageType language; - if (function) - language = function->GetLanguage(); - else - language = lldb::eLanguageTypeUnknown; - return inlined_info->GetName(language).AsCString (NULL); - } +const char *SBBlock::GetInlinedName() const { + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) { + Function *function = m_opaque_ptr->CalculateSymbolContextFunction(); + LanguageType language; + if (function) + language = function->GetLanguage(); + else + language = lldb::eLanguageTypeUnknown; + return inlined_info->GetName(language).AsCString(NULL); } - return NULL; + } + return NULL; } -SBFileSpec -SBBlock::GetInlinedCallSiteFile () const -{ - SBFileSpec sb_file; - if (m_opaque_ptr) - { - const InlineFunctionInfo* inlined_info = m_opaque_ptr->GetInlinedFunctionInfo (); - if (inlined_info) - sb_file.SetFileSpec (inlined_info->GetCallSite().GetFile()); - } - return sb_file; +SBFileSpec SBBlock::GetInlinedCallSiteFile() const { + SBFileSpec sb_file; + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + sb_file.SetFileSpec(inlined_info->GetCallSite().GetFile()); + } + return sb_file; } -uint32_t -SBBlock::GetInlinedCallSiteLine () const -{ - if (m_opaque_ptr) - { - const InlineFunctionInfo* inlined_info = m_opaque_ptr->GetInlinedFunctionInfo (); - if (inlined_info) - return inlined_info->GetCallSite().GetLine(); - } - return 0; +uint32_t SBBlock::GetInlinedCallSiteLine() const { + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + return inlined_info->GetCallSite().GetLine(); + } + return 0; } -uint32_t -SBBlock::GetInlinedCallSiteColumn () const -{ - if (m_opaque_ptr) - { - const InlineFunctionInfo* inlined_info = m_opaque_ptr->GetInlinedFunctionInfo (); - if (inlined_info) - return inlined_info->GetCallSite().GetColumn(); - } - return 0; +uint32_t SBBlock::GetInlinedCallSiteColumn() const { + if (m_opaque_ptr) { + const InlineFunctionInfo *inlined_info = + m_opaque_ptr->GetInlinedFunctionInfo(); + if (inlined_info) + return inlined_info->GetCallSite().GetColumn(); + } + return 0; } -void -SBBlock::AppendVariables (bool can_create, bool get_parent_variables, lldb_private::VariableList *var_list) -{ - if (IsValid()) - { - bool show_inline = true; - m_opaque_ptr->AppendVariables (can_create, - get_parent_variables, - show_inline, - [](Variable*) { return true; }, - var_list); - } +void SBBlock::AppendVariables(bool can_create, bool get_parent_variables, + lldb_private::VariableList *var_list) { + if (IsValid()) { + bool show_inline = true; + m_opaque_ptr->AppendVariables(can_create, get_parent_variables, show_inline, + [](Variable *) { return true; }, var_list); + } } -SBBlock -SBBlock::GetParent () -{ - SBBlock sb_block; - if (m_opaque_ptr) - sb_block.m_opaque_ptr = m_opaque_ptr->GetParent(); - return sb_block; +SBBlock SBBlock::GetParent() { + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetParent(); + return sb_block; } -lldb::SBBlock -SBBlock::GetContainingInlinedBlock () -{ - SBBlock sb_block; - if (m_opaque_ptr) - sb_block.m_opaque_ptr = m_opaque_ptr->GetContainingInlinedBlock (); - return sb_block; +lldb::SBBlock SBBlock::GetContainingInlinedBlock() { + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetContainingInlinedBlock(); + return sb_block; } -SBBlock -SBBlock::GetSibling () -{ - SBBlock sb_block; - if (m_opaque_ptr) - sb_block.m_opaque_ptr = m_opaque_ptr->GetSibling(); - return sb_block; +SBBlock SBBlock::GetSibling() { + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetSibling(); + return sb_block; } -SBBlock -SBBlock::GetFirstChild () -{ - SBBlock sb_block; - if (m_opaque_ptr) - sb_block.m_opaque_ptr = m_opaque_ptr->GetFirstChild(); - return sb_block; +SBBlock SBBlock::GetFirstChild() { + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.m_opaque_ptr = m_opaque_ptr->GetFirstChild(); + return sb_block; } -lldb_private::Block * -SBBlock::GetPtr () -{ - return m_opaque_ptr; -} +lldb_private::Block *SBBlock::GetPtr() { return m_opaque_ptr; } -void -SBBlock::SetPtr (lldb_private::Block *block) -{ - m_opaque_ptr = block; -} +void SBBlock::SetPtr(lldb_private::Block *block) { m_opaque_ptr = block; } -bool -SBBlock::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - - if (m_opaque_ptr) - { - lldb::user_id_t id = m_opaque_ptr->GetID(); - strm.Printf ("Block: {id: %" PRIu64 "} ", id); - if (IsInlined()) - { - strm.Printf (" (inlined, '%s') ", GetInlinedName()); - } - lldb_private::SymbolContext sc; - m_opaque_ptr->CalculateSymbolContext (&sc); - if (sc.function) - { - m_opaque_ptr->DumpAddressRanges (&strm, - sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()); - } +bool SBBlock::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + + if (m_opaque_ptr) { + lldb::user_id_t id = m_opaque_ptr->GetID(); + strm.Printf("Block: {id: %" PRIu64 "} ", id); + if (IsInlined()) { + strm.Printf(" (inlined, '%s') ", GetInlinedName()); } - else - strm.PutCString ("No value"); - - return true; + lldb_private::SymbolContext sc; + m_opaque_ptr->CalculateSymbolContext(&sc); + if (sc.function) { + m_opaque_ptr->DumpAddressRanges( + &strm, + sc.function->GetAddressRange().GetBaseAddress().GetFileAddress()); + } + } else + strm.PutCString("No value"); + + return true; } -uint32_t -SBBlock::GetNumRanges () -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetNumRanges(); - return 0; +uint32_t SBBlock::GetNumRanges() { + if (m_opaque_ptr) + return m_opaque_ptr->GetNumRanges(); + return 0; } -lldb::SBAddress -SBBlock::GetRangeStartAddress (uint32_t idx) -{ - lldb::SBAddress sb_addr; - if (m_opaque_ptr) - { - AddressRange range; - if (m_opaque_ptr->GetRangeAtIndex(idx, range)) - { - sb_addr.ref() = range.GetBaseAddress(); - } +lldb::SBAddress SBBlock::GetRangeStartAddress(uint32_t idx) { + lldb::SBAddress sb_addr; + if (m_opaque_ptr) { + AddressRange range; + if (m_opaque_ptr->GetRangeAtIndex(idx, range)) { + sb_addr.ref() = range.GetBaseAddress(); } - return sb_addr; + } + return sb_addr; } -lldb::SBAddress -SBBlock::GetRangeEndAddress (uint32_t idx) -{ - lldb::SBAddress sb_addr; - if (m_opaque_ptr) - { - AddressRange range; - if (m_opaque_ptr->GetRangeAtIndex(idx, range)) - { - sb_addr.ref() = range.GetBaseAddress(); - sb_addr.ref().Slide(range.GetByteSize()); - } +lldb::SBAddress SBBlock::GetRangeEndAddress(uint32_t idx) { + lldb::SBAddress sb_addr; + if (m_opaque_ptr) { + AddressRange range; + if (m_opaque_ptr->GetRangeAtIndex(idx, range)) { + sb_addr.ref() = range.GetBaseAddress(); + sb_addr.ref().Slide(range.GetByteSize()); } - return sb_addr; + } + return sb_addr; } -uint32_t -SBBlock::GetRangeIndexForBlockAddress (lldb::SBAddress block_addr) -{ - if (m_opaque_ptr && block_addr.IsValid()) - { - return m_opaque_ptr->GetRangeIndexContainingAddress (block_addr.ref()); - } +uint32_t SBBlock::GetRangeIndexForBlockAddress(lldb::SBAddress block_addr) { + if (m_opaque_ptr && block_addr.IsValid()) { + return m_opaque_ptr->GetRangeIndexContainingAddress(block_addr.ref()); + } - return UINT32_MAX; + return UINT32_MAX; } - -lldb::SBValueList -SBBlock::GetVariables (lldb::SBFrame& frame, - bool arguments, - bool locals, - bool statics, - lldb::DynamicValueType use_dynamic) -{ - Block *block = GetPtr(); - SBValueList value_list; - if (block) - { - StackFrameSP frame_sp(frame.GetFrameSP()); - VariableListSP variable_list_sp (block->GetBlockVariableList (true)); - - if (variable_list_sp) - { - const size_t num_variables = variable_list_sp->GetSize(); - if (num_variables) - { - for (size_t i = 0; i < num_variables; ++i) - { - VariableSP variable_sp (variable_list_sp->GetVariableAtIndex(i)); - if (variable_sp) - { - bool add_variable = false; - switch (variable_sp->GetScope()) - { - case eValueTypeVariableGlobal: - case eValueTypeVariableStatic: - case eValueTypeVariableThreadLocal: - add_variable = statics; - break; - - case eValueTypeVariableArgument: - add_variable = arguments; - break; - - case eValueTypeVariableLocal: - add_variable = locals; - break; - - default: - break; - } - if (add_variable) - { - if (frame_sp) - { - lldb::ValueObjectSP valobj_sp(frame_sp->GetValueObjectForFrameVariable (variable_sp,eNoDynamicValues)); - SBValue value_sb; - value_sb.SetSP(valobj_sp, use_dynamic); - value_list.Append (value_sb); - } - } - } - } +lldb::SBValueList SBBlock::GetVariables(lldb::SBFrame &frame, bool arguments, + bool locals, bool statics, + lldb::DynamicValueType use_dynamic) { + Block *block = GetPtr(); + SBValueList value_list; + if (block) { + StackFrameSP frame_sp(frame.GetFrameSP()); + VariableListSP variable_list_sp(block->GetBlockVariableList(true)); + + if (variable_list_sp) { + const size_t num_variables = variable_list_sp->GetSize(); + if (num_variables) { + for (size_t i = 0; i < num_variables; ++i) { + VariableSP variable_sp(variable_list_sp->GetVariableAtIndex(i)); + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; + } + if (add_variable) { + if (frame_sp) { + lldb::ValueObjectSP valobj_sp( + frame_sp->GetValueObjectForFrameVariable(variable_sp, + eNoDynamicValues)); + SBValue value_sb; + value_sb.SetSP(valobj_sp, use_dynamic); + value_list.Append(value_sb); + } } - } + } + } + } } - return value_list; + } + return value_list; } -lldb::SBValueList -SBBlock::GetVariables (lldb::SBTarget& target, - bool arguments, - bool locals, - bool statics) -{ - Block *block = GetPtr(); - - SBValueList value_list; - if (block) - { - TargetSP target_sp(target.GetSP()); - - VariableListSP variable_list_sp (block->GetBlockVariableList (true)); - - if (variable_list_sp) - { - const size_t num_variables = variable_list_sp->GetSize(); - if (num_variables) - { - for (size_t i = 0; i < num_variables; ++i) - { - VariableSP variable_sp (variable_list_sp->GetVariableAtIndex(i)); - if (variable_sp) - { - bool add_variable = false; - switch (variable_sp->GetScope()) - { - case eValueTypeVariableGlobal: - case eValueTypeVariableStatic: - case eValueTypeVariableThreadLocal: - add_variable = statics; - break; - - case eValueTypeVariableArgument: - add_variable = arguments; - break; - - case eValueTypeVariableLocal: - add_variable = locals; - break; - - default: - break; - } - if (add_variable) - { - if (target_sp) - value_list.Append (ValueObjectVariable::Create (target_sp.get(), variable_sp)); - } - } - } +lldb::SBValueList SBBlock::GetVariables(lldb::SBTarget &target, bool arguments, + bool locals, bool statics) { + Block *block = GetPtr(); + + SBValueList value_list; + if (block) { + TargetSP target_sp(target.GetSP()); + + VariableListSP variable_list_sp(block->GetBlockVariableList(true)); + + if (variable_list_sp) { + const size_t num_variables = variable_list_sp->GetSize(); + if (num_variables) { + for (size_t i = 0; i < num_variables; ++i) { + VariableSP variable_sp(variable_list_sp->GetVariableAtIndex(i)); + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; } + if (add_variable) { + if (target_sp) + value_list.Append( + ValueObjectVariable::Create(target_sp.get(), variable_sp)); + } + } } - } - return value_list; + } + } + } + return value_list; } - diff --git a/lldb/source/API/SBBreakpoint.cpp b/lldb/source/API/SBBreakpoint.cpp index ec3a3de4a78..1887ad12ef1 100644 --- a/lldb/source/API/SBBreakpoint.cpp +++ b/lldb/source/API/SBBreakpoint.cpp @@ -41,750 +41,648 @@ using namespace lldb; using namespace lldb_private; -struct CallbackData -{ - SBBreakpoint::BreakpointHitCallback callback; - void *callback_baton; +struct CallbackData { + SBBreakpoint::BreakpointHitCallback callback; + void *callback_baton; }; -class SBBreakpointCallbackBaton : public Baton -{ +class SBBreakpointCallbackBaton : public Baton { public: - SBBreakpointCallbackBaton (SBBreakpoint::BreakpointHitCallback callback, void *baton) : - Baton (new CallbackData) - { - CallbackData *data = (CallbackData *)m_data; - data->callback = callback; - data->callback_baton = baton; - } - - ~SBBreakpointCallbackBaton() override - { - CallbackData *data = (CallbackData *)m_data; - - if (data) - { - delete data; - m_data = nullptr; - } - } + SBBreakpointCallbackBaton(SBBreakpoint::BreakpointHitCallback callback, + void *baton) + : Baton(new CallbackData) { + CallbackData *data = (CallbackData *)m_data; + data->callback = callback; + data->callback_baton = baton; + } + + ~SBBreakpointCallbackBaton() override { + CallbackData *data = (CallbackData *)m_data; + + if (data) { + delete data; + m_data = nullptr; + } + } }; -SBBreakpoint::SBBreakpoint () : - m_opaque_sp () -{ -} +SBBreakpoint::SBBreakpoint() : m_opaque_sp() {} -SBBreakpoint::SBBreakpoint (const SBBreakpoint& rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBBreakpoint::SBBreakpoint(const SBBreakpoint &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBBreakpoint::SBBreakpoint (const lldb::BreakpointSP &bp_sp) : - m_opaque_sp (bp_sp) -{ -} +SBBreakpoint::SBBreakpoint(const lldb::BreakpointSP &bp_sp) + : m_opaque_sp(bp_sp) {} SBBreakpoint::~SBBreakpoint() = default; -const SBBreakpoint & -SBBreakpoint::operator = (const SBBreakpoint& rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBBreakpoint &SBBreakpoint::operator=(const SBBreakpoint &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -bool -SBBreakpoint::operator == (const lldb::SBBreakpoint& rhs) -{ - if (m_opaque_sp && rhs.m_opaque_sp) - return m_opaque_sp.get() == rhs.m_opaque_sp.get(); - return false; +bool SBBreakpoint::operator==(const lldb::SBBreakpoint &rhs) { + if (m_opaque_sp && rhs.m_opaque_sp) + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); + return false; } -bool -SBBreakpoint::operator != (const lldb::SBBreakpoint& rhs) -{ - if (m_opaque_sp && rhs.m_opaque_sp) - return m_opaque_sp.get() != rhs.m_opaque_sp.get(); - return (m_opaque_sp && !rhs.m_opaque_sp) || (rhs.m_opaque_sp && !m_opaque_sp); +bool SBBreakpoint::operator!=(const lldb::SBBreakpoint &rhs) { + if (m_opaque_sp && rhs.m_opaque_sp) + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); + return (m_opaque_sp && !rhs.m_opaque_sp) || (rhs.m_opaque_sp && !m_opaque_sp); } -break_id_t -SBBreakpoint::GetID () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +break_id_t SBBreakpoint::GetID() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - break_id_t break_id = LLDB_INVALID_BREAK_ID; - if (m_opaque_sp) - break_id = m_opaque_sp->GetID(); + break_id_t break_id = LLDB_INVALID_BREAK_ID; + if (m_opaque_sp) + break_id = m_opaque_sp->GetID(); - if (log) - { - if (break_id == LLDB_INVALID_BREAK_ID) - log->Printf ("SBBreakpoint(%p)::GetID () => LLDB_INVALID_BREAK_ID", - static_cast(m_opaque_sp.get())); - else - log->Printf ("SBBreakpoint(%p)::GetID () => %u", - static_cast(m_opaque_sp.get()), break_id); - } - - return break_id; -} - -bool -SBBreakpoint::IsValid() const -{ - if (!m_opaque_sp) - return false; - else if (m_opaque_sp->GetTarget().GetBreakpointByID(m_opaque_sp->GetID())) - return true; + if (log) { + if (break_id == LLDB_INVALID_BREAK_ID) + log->Printf("SBBreakpoint(%p)::GetID () => LLDB_INVALID_BREAK_ID", + static_cast(m_opaque_sp.get())); else - return false; -} + log->Printf("SBBreakpoint(%p)::GetID () => %u", + static_cast(m_opaque_sp.get()), break_id); + } -void -SBBreakpoint::ClearAllBreakpointSites () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->ClearAllBreakpointSites (); - } + return break_id; } -SBBreakpointLocation -SBBreakpoint::FindLocationByAddress (addr_t vm_addr) -{ - SBBreakpointLocation sb_bp_location; - - if (m_opaque_sp) - { - if (vm_addr != LLDB_INVALID_ADDRESS) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - Address address; - Target &target = m_opaque_sp->GetTarget(); - if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) - { - address.SetRawAddress (vm_addr); - } - sb_bp_location.SetLocation (m_opaque_sp->FindLocationByAddress (address)); - } - } - return sb_bp_location; -} - -break_id_t -SBBreakpoint::FindLocationIDByAddress (addr_t vm_addr) -{ - break_id_t break_id = LLDB_INVALID_BREAK_ID; - - if (m_opaque_sp && vm_addr != LLDB_INVALID_ADDRESS) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - Address address; - Target &target = m_opaque_sp->GetTarget(); - if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) - { - address.SetRawAddress (vm_addr); - } - break_id = m_opaque_sp->FindLocationIDByAddress (address); - } - - return break_id; +bool SBBreakpoint::IsValid() const { + if (!m_opaque_sp) + return false; + else if (m_opaque_sp->GetTarget().GetBreakpointByID(m_opaque_sp->GetID())) + return true; + else + return false; } -SBBreakpointLocation -SBBreakpoint::FindLocationByID (break_id_t bp_loc_id) -{ - SBBreakpointLocation sb_bp_location; - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - sb_bp_location.SetLocation (m_opaque_sp->FindLocationByID (bp_loc_id)); - } - - return sb_bp_location; +void SBBreakpoint::ClearAllBreakpointSites() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->ClearAllBreakpointSites(); + } } -SBBreakpointLocation -SBBreakpoint::GetLocationAtIndex (uint32_t index) -{ - SBBreakpointLocation sb_bp_location; - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - sb_bp_location.SetLocation (m_opaque_sp->GetLocationAtIndex (index)); - } +SBBreakpointLocation SBBreakpoint::FindLocationByAddress(addr_t vm_addr) { + SBBreakpointLocation sb_bp_location; - return sb_bp_location; -} - -void -SBBreakpoint::SetEnabled (bool enable) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpoint(%p)::SetEnabled (enabled=%i)", - static_cast(m_opaque_sp.get()), enable); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetEnabled (enable); + if (m_opaque_sp) { + if (vm_addr != LLDB_INVALID_ADDRESS) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + Address address; + Target &target = m_opaque_sp->GetTarget(); + if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) { + address.SetRawAddress(vm_addr); + } + sb_bp_location.SetLocation(m_opaque_sp->FindLocationByAddress(address)); } + } + return sb_bp_location; } -bool -SBBreakpoint::IsEnabled () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->IsEnabled(); - } - else - return false; -} - -void -SBBreakpoint::SetOneShot (bool one_shot) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpoint(%p)::SetOneShot (one_shot=%i)", - static_cast(m_opaque_sp.get()), one_shot); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetOneShot (one_shot); - } -} +break_id_t SBBreakpoint::FindLocationIDByAddress(addr_t vm_addr) { + break_id_t break_id = LLDB_INVALID_BREAK_ID; -bool -SBBreakpoint::IsOneShot () const -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->IsOneShot(); + if (m_opaque_sp && vm_addr != LLDB_INVALID_ADDRESS) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + Address address; + Target &target = m_opaque_sp->GetTarget(); + if (!target.GetSectionLoadList().ResolveLoadAddress(vm_addr, address)) { + address.SetRawAddress(vm_addr); } - else - return false; -} + break_id = m_opaque_sp->FindLocationIDByAddress(address); + } -bool -SBBreakpoint::IsInternal () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->IsInternal(); - } - else - return false; + return break_id; } -void -SBBreakpoint::SetIgnoreCount (uint32_t count) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBBreakpointLocation SBBreakpoint::FindLocationByID(break_id_t bp_loc_id) { + SBBreakpointLocation sb_bp_location; - if (log) - log->Printf ("SBBreakpoint(%p)::SetIgnoreCount (count=%u)", - static_cast(m_opaque_sp.get()), count); + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + sb_bp_location.SetLocation(m_opaque_sp->FindLocationByID(bp_loc_id)); + } - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetIgnoreCount (count); - } + return sb_bp_location; } -void -SBBreakpoint::SetCondition (const char *condition) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetCondition (condition); - } -} +SBBreakpointLocation SBBreakpoint::GetLocationAtIndex(uint32_t index) { + SBBreakpointLocation sb_bp_location; -const char * -SBBreakpoint::GetCondition () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetConditionText (); - } - return nullptr; -} + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + sb_bp_location.SetLocation(m_opaque_sp->GetLocationAtIndex(index)); + } -uint32_t -SBBreakpoint::GetHitCount () const -{ - uint32_t count = 0; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - count = m_opaque_sp->GetHitCount(); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetHitCount () => %u", - static_cast(m_opaque_sp.get()), count); - - return count; + return sb_bp_location; } -uint32_t -SBBreakpoint::GetIgnoreCount () const -{ - uint32_t count = 0; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - count = m_opaque_sp->GetIgnoreCount(); - } +void SBBreakpoint::SetEnabled(bool enable) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetIgnoreCount () => %u", - static_cast(m_opaque_sp.get()), count); + if (log) + log->Printf("SBBreakpoint(%p)::SetEnabled (enabled=%i)", + static_cast(m_opaque_sp.get()), enable); - return count; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetEnabled(enable); + } } -void -SBBreakpoint::SetThreadID (tid_t tid) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetThreadID (tid); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::SetThreadID (tid=0x%4.4" PRIx64 ")", - static_cast(m_opaque_sp.get()), tid); -} - -tid_t -SBBreakpoint::GetThreadID () -{ - tid_t tid = LLDB_INVALID_THREAD_ID; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - tid = m_opaque_sp->GetThreadID(); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetThreadID () => 0x%4.4" PRIx64, - static_cast(m_opaque_sp.get()), tid); - return tid; -} - -void -SBBreakpoint::SetThreadIndex (uint32_t index) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::SetThreadIndex (%u)", - static_cast(m_opaque_sp.get()), index); - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->GetOptions()->GetThreadSpec()->SetIndex (index); - } +bool SBBreakpoint::IsEnabled() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->IsEnabled(); + } else + return false; } -uint32_t -SBBreakpoint::GetThreadIndex() const -{ - uint32_t thread_idx = UINT32_MAX; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - const ThreadSpec *thread_spec = m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); - if (thread_spec != nullptr) - thread_idx = thread_spec->GetIndex(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetThreadIndex () => %u", - static_cast(m_opaque_sp.get()), thread_idx); - - return thread_idx; -} - -void -SBBreakpoint::SetThreadName (const char *thread_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::SetThreadName (%s)", - static_cast(m_opaque_sp.get()), thread_name); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->GetOptions()->GetThreadSpec()->SetName (thread_name); - } -} +void SBBreakpoint::SetOneShot(bool one_shot) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -const char * -SBBreakpoint::GetThreadName () const -{ - const char *name = nullptr; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - const ThreadSpec *thread_spec = m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); - if (thread_spec != nullptr) - name = thread_spec->GetName(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetThreadName () => %s", - static_cast(m_opaque_sp.get()), name); - - return name; -} - -void -SBBreakpoint::SetQueueName (const char *queue_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::SetQueueName (%s)", - static_cast(m_opaque_sp.get()), queue_name); - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->GetOptions()->GetThreadSpec()->SetQueueName (queue_name); - } -} + if (log) + log->Printf("SBBreakpoint(%p)::SetOneShot (one_shot=%i)", + static_cast(m_opaque_sp.get()), one_shot); -const char * -SBBreakpoint::GetQueueName () const -{ - const char *name = nullptr; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - const ThreadSpec *thread_spec = m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); - if (thread_spec) - name = thread_spec->GetQueueName(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetQueueName () => %s", - static_cast(m_opaque_sp.get()), name); - - return name; -} - -size_t -SBBreakpoint::GetNumResolvedLocations() const -{ - size_t num_resolved = 0; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - num_resolved = m_opaque_sp->GetNumResolvedLocations(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetNumResolvedLocations () => %" PRIu64, - static_cast(m_opaque_sp.get()), - static_cast(num_resolved)); - return num_resolved; -} - -size_t -SBBreakpoint::GetNumLocations() const -{ - size_t num_locs = 0; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - num_locs = m_opaque_sp->GetNumLocations(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::GetNumLocations () => %" PRIu64, - static_cast(m_opaque_sp.get()), - static_cast(num_locs)); - return num_locs; -} - -bool -SBBreakpoint::GetDescription (SBStream &s) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - s.Printf("SBBreakpoint: id = %i, ", m_opaque_sp->GetID()); - m_opaque_sp->GetResolverDescription (s.get()); - m_opaque_sp->GetFilterDescription (s.get()); - const size_t num_locations = m_opaque_sp->GetNumLocations (); - s.Printf(", locations = %" PRIu64, (uint64_t)num_locations); - return true; - } - s.Printf ("No value"); - return false; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetOneShot(one_shot); + } } -bool -SBBreakpoint::PrivateBreakpointHitCallback(void *baton, - StoppointCallbackContext *ctx, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id) -{ - ExecutionContext exe_ctx (ctx->exe_ctx_ref); - BreakpointSP bp_sp(exe_ctx.GetTargetRef().GetBreakpointList().FindBreakpointByID(break_id)); - if (baton && bp_sp) - { - CallbackData *data = (CallbackData *)baton; - lldb_private::Breakpoint *bp = bp_sp.get(); - if (bp && data->callback) - { - Process *process = exe_ctx.GetProcessPtr(); - if (process) - { - SBProcess sb_process (process->shared_from_this()); - SBThread sb_thread; - SBBreakpointLocation sb_location; - assert (bp_sp); - sb_location.SetLocation (bp_sp->FindLocationByID (break_loc_id)); - Thread *thread = exe_ctx.GetThreadPtr(); - if (thread) - sb_thread.SetThread(thread->shared_from_this()); - - return data->callback (data->callback_baton, - sb_process, - sb_thread, - sb_location); - } - } - } - return true; // Return true if we should stop at this breakpoint +bool SBBreakpoint::IsOneShot() const { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->IsOneShot(); + } else + return false; } -void -SBBreakpoint::SetCallback (BreakpointHitCallback callback, void *baton) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - { - void *pointer = &callback; - log->Printf ("SBBreakpoint(%p)::SetCallback (callback=%p, baton=%p)", - static_cast(m_opaque_sp.get()), - *static_cast(&pointer), static_cast(baton)); - } - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - BatonSP baton_sp(new SBBreakpointCallbackBaton (callback, baton)); - m_opaque_sp->SetCallback (SBBreakpoint::PrivateBreakpointHitCallback, baton_sp, false); - } +bool SBBreakpoint::IsInternal() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->IsInternal(); + } else + return false; } -void -SBBreakpoint::SetScriptCallbackFunction (const char *callback_function_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpoint(%p)::SetScriptCallbackFunction (callback=%s)", - static_cast(m_opaque_sp.get()), - callback_function_name); +void SBBreakpoint::SetIgnoreCount(uint32_t count) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBBreakpoint(%p)::SetIgnoreCount (count=%u)", + static_cast(m_opaque_sp.get()), count); + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetIgnoreCount(count); + } +} + +void SBBreakpoint::SetCondition(const char *condition) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetCondition(condition); + } +} + +const char *SBBreakpoint::GetCondition() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetConditionText(); + } + return nullptr; +} + +uint32_t SBBreakpoint::GetHitCount() const { + uint32_t count = 0; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + count = m_opaque_sp->GetHitCount(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetHitCount () => %u", + static_cast(m_opaque_sp.get()), count); + + return count; +} + +uint32_t SBBreakpoint::GetIgnoreCount() const { + uint32_t count = 0; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + count = m_opaque_sp->GetIgnoreCount(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetIgnoreCount () => %u", + static_cast(m_opaque_sp.get()), count); + + return count; +} + +void SBBreakpoint::SetThreadID(tid_t tid) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetThreadID(tid); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::SetThreadID (tid=0x%4.4" PRIx64 ")", + static_cast(m_opaque_sp.get()), tid); +} + +tid_t SBBreakpoint::GetThreadID() { + tid_t tid = LLDB_INVALID_THREAD_ID; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + tid = m_opaque_sp->GetThreadID(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetThreadID () => 0x%4.4" PRIx64, + static_cast(m_opaque_sp.get()), tid); + return tid; +} + +void SBBreakpoint::SetThreadIndex(uint32_t index) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::SetThreadIndex (%u)", + static_cast(m_opaque_sp.get()), index); + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->GetOptions()->GetThreadSpec()->SetIndex(index); + } +} + +uint32_t SBBreakpoint::GetThreadIndex() const { + uint32_t thread_idx = UINT32_MAX; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + const ThreadSpec *thread_spec = + m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); + if (thread_spec != nullptr) + thread_idx = thread_spec->GetIndex(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetThreadIndex () => %u", + static_cast(m_opaque_sp.get()), thread_idx); + + return thread_idx; +} + +void SBBreakpoint::SetThreadName(const char *thread_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::SetThreadName (%s)", + static_cast(m_opaque_sp.get()), thread_name); + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->GetOptions()->GetThreadSpec()->SetName(thread_name); + } +} + +const char *SBBreakpoint::GetThreadName() const { + const char *name = nullptr; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + const ThreadSpec *thread_spec = + m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); + if (thread_spec != nullptr) + name = thread_spec->GetName(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetThreadName () => %s", + static_cast(m_opaque_sp.get()), name); + + return name; +} + +void SBBreakpoint::SetQueueName(const char *queue_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::SetQueueName (%s)", + static_cast(m_opaque_sp.get()), queue_name); + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->GetOptions()->GetThreadSpec()->SetQueueName(queue_name); + } +} + +const char *SBBreakpoint::GetQueueName() const { + const char *name = nullptr; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + const ThreadSpec *thread_spec = + m_opaque_sp->GetOptions()->GetThreadSpecNoCreate(); + if (thread_spec) + name = thread_spec->GetQueueName(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetQueueName () => %s", + static_cast(m_opaque_sp.get()), name); + + return name; +} + +size_t SBBreakpoint::GetNumResolvedLocations() const { + size_t num_resolved = 0; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + num_resolved = m_opaque_sp->GetNumResolvedLocations(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetNumResolvedLocations () => %" PRIu64, + static_cast(m_opaque_sp.get()), + static_cast(num_resolved)); + return num_resolved; +} + +size_t SBBreakpoint::GetNumLocations() const { + size_t num_locs = 0; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + num_locs = m_opaque_sp->GetNumLocations(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBreakpoint(%p)::GetNumLocations () => %" PRIu64, + static_cast(m_opaque_sp.get()), + static_cast(num_locs)); + return num_locs; +} + +bool SBBreakpoint::GetDescription(SBStream &s) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + s.Printf("SBBreakpoint: id = %i, ", m_opaque_sp->GetID()); + m_opaque_sp->GetResolverDescription(s.get()); + m_opaque_sp->GetFilterDescription(s.get()); + const size_t num_locations = m_opaque_sp->GetNumLocations(); + s.Printf(", locations = %" PRIu64, (uint64_t)num_locations); + return true; + } + s.Printf("No value"); + return false; +} + +bool SBBreakpoint::PrivateBreakpointHitCallback(void *baton, + StoppointCallbackContext *ctx, + lldb::user_id_t break_id, + lldb::user_id_t break_loc_id) { + ExecutionContext exe_ctx(ctx->exe_ctx_ref); + BreakpointSP bp_sp( + exe_ctx.GetTargetRef().GetBreakpointList().FindBreakpointByID(break_id)); + if (baton && bp_sp) { + CallbackData *data = (CallbackData *)baton; + lldb_private::Breakpoint *bp = bp_sp.get(); + if (bp && data->callback) { + Process *process = exe_ctx.GetProcessPtr(); + if (process) { + SBProcess sb_process(process->shared_from_this()); + SBThread sb_thread; + SBBreakpointLocation sb_location; + assert(bp_sp); + sb_location.SetLocation(bp_sp->FindLocationByID(break_loc_id)); + Thread *thread = exe_ctx.GetThreadPtr(); + if (thread) + sb_thread.SetThread(thread->shared_from_this()); + + return data->callback(data->callback_baton, sb_process, sb_thread, + sb_location); + } + } + } + return true; // Return true if we should stop at this breakpoint +} + +void SBBreakpoint::SetCallback(BreakpointHitCallback callback, void *baton) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) { + void *pointer = &callback; + log->Printf("SBBreakpoint(%p)::SetCallback (callback=%p, baton=%p)", + static_cast(m_opaque_sp.get()), + *static_cast(&pointer), static_cast(baton)); + } + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + BatonSP baton_sp(new SBBreakpointCallbackBaton(callback, baton)); + m_opaque_sp->SetCallback(SBBreakpoint::PrivateBreakpointHitCallback, + baton_sp, false); + } +} + +void SBBreakpoint::SetScriptCallbackFunction( + const char *callback_function_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBBreakpoint(%p)::SetScriptCallbackFunction (callback=%s)", + static_cast(m_opaque_sp.get()), callback_function_name); + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + BreakpointOptions *bp_options = m_opaque_sp->GetOptions(); + m_opaque_sp->GetTarget() + .GetDebugger() + .GetCommandInterpreter() + .GetScriptInterpreter() + ->SetBreakpointCommandCallbackFunction(bp_options, + callback_function_name); + } +} + +SBError SBBreakpoint::SetScriptCallbackBody(const char *callback_body_text) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBBreakpoint(%p)::SetScriptCallbackBody: callback body:\n%s)", + static_cast(m_opaque_sp.get()), callback_body_text); + + SBError sb_error; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + BreakpointOptions *bp_options = m_opaque_sp->GetOptions(); + Error error = + m_opaque_sp->GetTarget() + .GetDebugger() + .GetCommandInterpreter() + .GetScriptInterpreter() + ->SetBreakpointCommandCallback(bp_options, callback_body_text); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - BreakpointOptions *bp_options = m_opaque_sp->GetOptions(); - m_opaque_sp->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter()->SetBreakpointCommandCallbackFunction (bp_options, - callback_function_name); - } + return sb_error; } -SBError -SBBreakpoint::SetScriptCallbackBody (const char *callback_body_text) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBBreakpoint::AddName(const char *new_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::SetScriptCallbackBody: callback body:\n%s)", - static_cast(m_opaque_sp.get()), callback_body_text); + if (log) + log->Printf("SBBreakpoint(%p)::AddName (name=%s)", + static_cast(m_opaque_sp.get()), new_name); - SBError sb_error; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - BreakpointOptions *bp_options = m_opaque_sp->GetOptions(); - Error error = m_opaque_sp->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter()->SetBreakpointCommandCallback (bp_options, - callback_body_text); - sb_error.SetError(error); - } - else - sb_error.SetErrorString("invalid breakpoint"); + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + Error error; // Think I'm just going to swallow the error here, it's + // probably more annoying to have to provide it. + return m_opaque_sp->AddName(new_name, error); + } - return sb_error; + return false; } -bool -SBBreakpoint::AddName (const char *new_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBBreakpoint::RemoveName(const char *name_to_remove) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::AddName (name=%s)", - static_cast(m_opaque_sp.get()), - new_name); + if (log) + log->Printf("SBBreakpoint(%p)::RemoveName (name=%s)", + static_cast(m_opaque_sp.get()), name_to_remove); - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - Error error; // Think I'm just going to swallow the error here, it's probably more annoying to have to provide it. - return m_opaque_sp->AddName(new_name, error); - } - - return false; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->RemoveName(name_to_remove); + } } -void -SBBreakpoint::RemoveName (const char *name_to_remove) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBBreakpoint::MatchesName(const char *name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBreakpoint(%p)::RemoveName (name=%s)", - static_cast(m_opaque_sp.get()), - name_to_remove); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->RemoveName(name_to_remove); - } -} + if (log) + log->Printf("SBBreakpoint(%p)::MatchesName (name=%s)", + static_cast(m_opaque_sp.get()), name); -bool -SBBreakpoint::MatchesName (const char *name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->MatchesName(name); + } - if (log) - log->Printf ("SBBreakpoint(%p)::MatchesName (name=%s)", - static_cast(m_opaque_sp.get()), - name); + return false; +} - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->MatchesName(name); - } +void SBBreakpoint::GetNames(SBStringList &names) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - return false; -} + if (log) + log->Printf("SBBreakpoint(%p)::GetNames ()", + static_cast(m_opaque_sp.get())); -void -SBBreakpoint::GetNames (SBStringList &names) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpoint(%p)::GetNames ()", - static_cast(m_opaque_sp.get())); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - std::vector names_vec; - m_opaque_sp->GetNames(names_vec); - for (std::string name : names_vec) - { - names.AppendString (name.c_str()); - } + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + std::vector names_vec; + m_opaque_sp->GetNames(names_vec); + for (std::string name : names_vec) { + names.AppendString(name.c_str()); } + } } -lldb_private::Breakpoint * -SBBreakpoint::operator->() const -{ - return m_opaque_sp.get(); +lldb_private::Breakpoint *SBBreakpoint::operator->() const { + return m_opaque_sp.get(); } -lldb_private::Breakpoint * -SBBreakpoint::get() const -{ - return m_opaque_sp.get(); +lldb_private::Breakpoint *SBBreakpoint::get() const { + return m_opaque_sp.get(); } -lldb::BreakpointSP & -SBBreakpoint::operator *() -{ - return m_opaque_sp; -} +lldb::BreakpointSP &SBBreakpoint::operator*() { return m_opaque_sp; } -const lldb::BreakpointSP & -SBBreakpoint::operator *() const -{ - return m_opaque_sp; +const lldb::BreakpointSP &SBBreakpoint::operator*() const { + return m_opaque_sp; } -bool -SBBreakpoint::EventIsBreakpointEvent (const lldb::SBEvent &event) -{ - return Breakpoint::BreakpointEventData::GetEventDataFromEvent(event.get()) != nullptr; +bool SBBreakpoint::EventIsBreakpointEvent(const lldb::SBEvent &event) { + return Breakpoint::BreakpointEventData::GetEventDataFromEvent(event.get()) != + nullptr; } BreakpointEventType -SBBreakpoint::GetBreakpointEventTypeFromEvent (const SBEvent& event) -{ - if (event.IsValid()) - return Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event.GetSP()); - return eBreakpointEventTypeInvalidType; +SBBreakpoint::GetBreakpointEventTypeFromEvent(const SBEvent &event) { + if (event.IsValid()) + return Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( + event.GetSP()); + return eBreakpointEventTypeInvalidType; } -SBBreakpoint -SBBreakpoint::GetBreakpointFromEvent (const lldb::SBEvent& event) -{ - SBBreakpoint sb_breakpoint; - if (event.IsValid()) - sb_breakpoint.m_opaque_sp = Breakpoint::BreakpointEventData::GetBreakpointFromEvent (event.GetSP()); - return sb_breakpoint; +SBBreakpoint SBBreakpoint::GetBreakpointFromEvent(const lldb::SBEvent &event) { + SBBreakpoint sb_breakpoint; + if (event.IsValid()) + sb_breakpoint.m_opaque_sp = + Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event.GetSP()); + return sb_breakpoint; } SBBreakpointLocation -SBBreakpoint::GetBreakpointLocationAtIndexFromEvent (const lldb::SBEvent& event, uint32_t loc_idx) -{ - SBBreakpointLocation sb_breakpoint_loc; - if (event.IsValid()) - sb_breakpoint_loc.SetLocation (Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent (event.GetSP(), loc_idx)); - return sb_breakpoint_loc; +SBBreakpoint::GetBreakpointLocationAtIndexFromEvent(const lldb::SBEvent &event, + uint32_t loc_idx) { + SBBreakpointLocation sb_breakpoint_loc; + if (event.IsValid()) + sb_breakpoint_loc.SetLocation( + Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent( + event.GetSP(), loc_idx)); + return sb_breakpoint_loc; } uint32_t -SBBreakpoint::GetNumBreakpointLocationsFromEvent (const lldb::SBEvent &event) -{ - uint32_t num_locations = 0; - if (event.IsValid()) - num_locations = (Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent (event.GetSP())); - return num_locations; +SBBreakpoint::GetNumBreakpointLocationsFromEvent(const lldb::SBEvent &event) { + uint32_t num_locations = 0; + if (event.IsValid()) + num_locations = + (Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( + event.GetSP())); + return num_locations; } diff --git a/lldb/source/API/SBBreakpointLocation.cpp b/lldb/source/API/SBBreakpointLocation.cpp index 631a32bc9dd..c7fac7688f8 100644 --- a/lldb/source/API/SBBreakpointLocation.cpp +++ b/lldb/source/API/SBBreakpointLocation.cpp @@ -8,13 +8,11 @@ //===----------------------------------------------------------------------===// #include "lldb/API/SBBreakpointLocation.h" -#include "lldb/API/SBDefines.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" +#include "lldb/API/SBDefines.h" #include "lldb/API/SBStream.h" -#include "lldb/lldb-types.h" -#include "lldb/lldb-defines.h" #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Debugger.h" @@ -23,347 +21,296 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/ScriptInterpreter.h" -#include "lldb/Target/ThreadSpec.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" +#include "lldb/Target/ThreadSpec.h" +#include "lldb/lldb-defines.h" +#include "lldb/lldb-types.h" using namespace lldb; using namespace lldb_private; - -SBBreakpointLocation::SBBreakpointLocation () : - m_opaque_sp () -{ +SBBreakpointLocation::SBBreakpointLocation() : m_opaque_sp() {} + +SBBreakpointLocation::SBBreakpointLocation( + const lldb::BreakpointLocationSP &break_loc_sp) + : m_opaque_sp(break_loc_sp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) { + SBStream sstr; + GetDescription(sstr, lldb::eDescriptionLevelBrief); + log->Printf("SBBreakpointLocation::SBBreakpointLocaiton (const " + "lldb::BreakpointLocationsSP &break_loc_sp" + "=%p) => this.sp = %p (%s)", + static_cast(break_loc_sp.get()), + static_cast(m_opaque_sp.get()), sstr.GetData()); + } } -SBBreakpointLocation::SBBreakpointLocation (const lldb::BreakpointLocationSP &break_loc_sp) : - m_opaque_sp (break_loc_sp) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - { - SBStream sstr; - GetDescription (sstr, lldb::eDescriptionLevelBrief); - log->Printf ("SBBreakpointLocation::SBBreakpointLocaiton (const lldb::BreakpointLocationsSP &break_loc_sp" - "=%p) => this.sp = %p (%s)", - static_cast(break_loc_sp.get()), - static_cast(m_opaque_sp.get()), sstr.GetData()); - } -} +SBBreakpointLocation::SBBreakpointLocation(const SBBreakpointLocation &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBBreakpointLocation::SBBreakpointLocation(const SBBreakpointLocation &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ +const SBBreakpointLocation &SBBreakpointLocation:: +operator=(const SBBreakpointLocation &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -const SBBreakpointLocation & -SBBreakpointLocation::operator = (const SBBreakpointLocation &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; -} +SBBreakpointLocation::~SBBreakpointLocation() {} +bool SBBreakpointLocation::IsValid() const { return m_opaque_sp.get() != NULL; } -SBBreakpointLocation::~SBBreakpointLocation () -{ +SBAddress SBBreakpointLocation::GetAddress() { + if (m_opaque_sp) + return SBAddress(&m_opaque_sp->GetAddress()); + else + return SBAddress(); } -bool -SBBreakpointLocation::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} - -SBAddress -SBBreakpointLocation::GetAddress () -{ - if (m_opaque_sp) - return SBAddress(&m_opaque_sp->GetAddress()); - else - return SBAddress(); -} +addr_t SBBreakpointLocation::GetLoadAddress() { + addr_t ret_addr = LLDB_INVALID_ADDRESS; -addr_t -SBBreakpointLocation::GetLoadAddress () -{ - addr_t ret_addr = LLDB_INVALID_ADDRESS; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + ret_addr = m_opaque_sp->GetLoadAddress(); + } - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - ret_addr = m_opaque_sp->GetLoadAddress(); - } - - return ret_addr; + return ret_addr; } -void -SBBreakpointLocation::SetEnabled (bool enabled) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetEnabled (enabled); - } +void SBBreakpointLocation::SetEnabled(bool enabled) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetEnabled(enabled); + } } -bool -SBBreakpointLocation::IsEnabled () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->IsEnabled(); - } - else - return false; +bool SBBreakpointLocation::IsEnabled() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->IsEnabled(); + } else + return false; } -uint32_t -SBBreakpointLocation::GetIgnoreCount () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetIgnoreCount(); - } - else - return 0; +uint32_t SBBreakpointLocation::GetIgnoreCount() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetIgnoreCount(); + } else + return 0; } -void -SBBreakpointLocation::SetIgnoreCount (uint32_t n) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetIgnoreCount (n); - } +void SBBreakpointLocation::SetIgnoreCount(uint32_t n) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetIgnoreCount(n); + } } -void -SBBreakpointLocation::SetCondition (const char *condition) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetCondition (condition); - } +void SBBreakpointLocation::SetCondition(const char *condition) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetCondition(condition); + } } -const char * -SBBreakpointLocation::GetCondition () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetConditionText (); - } - return NULL; +const char *SBBreakpointLocation::GetCondition() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetConditionText(); + } + return NULL; } -void -SBBreakpointLocation::SetScriptCallbackFunction (const char *callback_function_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpointLocation(%p)::SetScriptCallbackFunction (callback=%s)", - static_cast(m_opaque_sp.get()), - callback_function_name); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - BreakpointOptions *bp_options = m_opaque_sp->GetLocationOptions(); - m_opaque_sp->GetBreakpoint().GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter()->SetBreakpointCommandCallbackFunction (bp_options, - callback_function_name); - } +void SBBreakpointLocation::SetScriptCallbackFunction( + const char *callback_function_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf( + "SBBreakpointLocation(%p)::SetScriptCallbackFunction (callback=%s)", + static_cast(m_opaque_sp.get()), callback_function_name); + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + BreakpointOptions *bp_options = m_opaque_sp->GetLocationOptions(); + m_opaque_sp->GetBreakpoint() + .GetTarget() + .GetDebugger() + .GetCommandInterpreter() + .GetScriptInterpreter() + ->SetBreakpointCommandCallbackFunction(bp_options, + callback_function_name); + } } SBError -SBBreakpointLocation::SetScriptCallbackBody (const char *callback_body_text) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBBreakpoint(%p)::SetScriptCallbackBody: callback body:\n%s)", - static_cast(m_opaque_sp.get()), callback_body_text); - - SBError sb_error; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - BreakpointOptions *bp_options = m_opaque_sp->GetLocationOptions(); - Error error = m_opaque_sp->GetBreakpoint().GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter()->SetBreakpointCommandCallback (bp_options, - callback_body_text); - sb_error.SetError(error); - } - else - sb_error.SetErrorString("invalid breakpoint"); - - return sb_error; +SBBreakpointLocation::SetScriptCallbackBody(const char *callback_body_text) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBBreakpoint(%p)::SetScriptCallbackBody: callback body:\n%s)", + static_cast(m_opaque_sp.get()), callback_body_text); + + SBError sb_error; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + BreakpointOptions *bp_options = m_opaque_sp->GetLocationOptions(); + Error error = + m_opaque_sp->GetBreakpoint() + .GetTarget() + .GetDebugger() + .GetCommandInterpreter() + .GetScriptInterpreter() + ->SetBreakpointCommandCallback(bp_options, callback_body_text); + sb_error.SetError(error); + } else + sb_error.SetErrorString("invalid breakpoint"); + + return sb_error; } -void -SBBreakpointLocation::SetThreadID (tid_t thread_id) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetThreadID (thread_id); - } +void SBBreakpointLocation::SetThreadID(tid_t thread_id) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetThreadID(thread_id); + } } -tid_t -SBBreakpointLocation::GetThreadID () -{ - tid_t tid = LLDB_INVALID_THREAD_ID; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetThreadID(); - } - return tid; +tid_t SBBreakpointLocation::GetThreadID() { + tid_t tid = LLDB_INVALID_THREAD_ID; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetThreadID(); + } + return tid; } -void -SBBreakpointLocation::SetThreadIndex (uint32_t index) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetThreadIndex (index); - } +void SBBreakpointLocation::SetThreadIndex(uint32_t index) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetThreadIndex(index); + } } -uint32_t -SBBreakpointLocation::GetThreadIndex() const -{ - uint32_t thread_idx = UINT32_MAX; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetThreadIndex(); - } - return thread_idx; -} - - -void -SBBreakpointLocation::SetThreadName (const char *thread_name) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetThreadName (thread_name); - } +uint32_t SBBreakpointLocation::GetThreadIndex() const { + uint32_t thread_idx = UINT32_MAX; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetThreadIndex(); + } + return thread_idx; } -const char * -SBBreakpointLocation::GetThreadName () const -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetThreadName(); - } - return NULL; +void SBBreakpointLocation::SetThreadName(const char *thread_name) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetThreadName(thread_name); + } } -void -SBBreakpointLocation::SetQueueName (const char *queue_name) -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->SetQueueName (queue_name); - } +const char *SBBreakpointLocation::GetThreadName() const { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetThreadName(); + } + return NULL; } -const char * -SBBreakpointLocation::GetQueueName () const -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->GetQueueName (); - } - return NULL; +void SBBreakpointLocation::SetQueueName(const char *queue_name) { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->SetQueueName(queue_name); + } } -bool -SBBreakpointLocation::IsResolved () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->IsResolved(); - } - return false; +const char *SBBreakpointLocation::GetQueueName() const { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->GetQueueName(); + } + return NULL; } -void -SBBreakpointLocation::SetLocation (const lldb::BreakpointLocationSP &break_loc_sp) -{ - // Uninstall the callbacks? - m_opaque_sp = break_loc_sp; +bool SBBreakpointLocation::IsResolved() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->IsResolved(); + } + return false; } -bool -SBBreakpointLocation::GetDescription (SBStream &description, DescriptionLevel level) -{ - Stream &strm = description.ref(); - - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - m_opaque_sp->GetDescription (&strm, level); - strm.EOL(); - } - else - strm.PutCString ("No value"); - - return true; +void SBBreakpointLocation::SetLocation( + const lldb::BreakpointLocationSP &break_loc_sp) { + // Uninstall the callbacks? + m_opaque_sp = break_loc_sp; } -break_id_t -SBBreakpointLocation::GetID () -{ - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - return m_opaque_sp->GetID (); - } - else - return LLDB_INVALID_BREAK_ID; +bool SBBreakpointLocation::GetDescription(SBStream &description, + DescriptionLevel level) { + Stream &strm = description.ref(); + + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + m_opaque_sp->GetDescription(&strm, level); + strm.EOL(); + } else + strm.PutCString("No value"); + + return true; } -SBBreakpoint -SBBreakpointLocation::GetBreakpoint () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - //if (log) - // log->Printf ("SBBreakpointLocation::GetBreakpoint ()"); - - SBBreakpoint sb_bp; - if (m_opaque_sp) - { - std::lock_guard guard(m_opaque_sp->GetTarget().GetAPIMutex()); - *sb_bp = m_opaque_sp->GetBreakpoint ().shared_from_this(); - } - - if (log) - { - SBStream sstr; - sb_bp.GetDescription (sstr); - log->Printf ("SBBreakpointLocation(%p)::GetBreakpoint () => SBBreakpoint(%p) %s", - static_cast(m_opaque_sp.get()), - static_cast(sb_bp.get()), sstr.GetData()); - } - return sb_bp; +break_id_t SBBreakpointLocation::GetID() { + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + return m_opaque_sp->GetID(); + } else + return LLDB_INVALID_BREAK_ID; } +SBBreakpoint SBBreakpointLocation::GetBreakpoint() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + // if (log) + // log->Printf ("SBBreakpointLocation::GetBreakpoint ()"); + + SBBreakpoint sb_bp; + if (m_opaque_sp) { + std::lock_guard guard( + m_opaque_sp->GetTarget().GetAPIMutex()); + *sb_bp = m_opaque_sp->GetBreakpoint().shared_from_this(); + } + + if (log) { + SBStream sstr; + sb_bp.GetDescription(sstr); + log->Printf( + "SBBreakpointLocation(%p)::GetBreakpoint () => SBBreakpoint(%p) %s", + static_cast(m_opaque_sp.get()), + static_cast(sb_bp.get()), sstr.GetData()); + } + return sb_bp; +} diff --git a/lldb/source/API/SBBroadcaster.cpp b/lldb/source/API/SBBroadcaster.cpp index 4b751adc295..5189dd7bb27 100644 --- a/lldb/source/API/SBBroadcaster.cpp +++ b/lldb/source/API/SBBroadcaster.cpp @@ -11,192 +11,151 @@ #include "lldb/Core/Log.h" #include "lldb/API/SBBroadcaster.h" -#include "lldb/API/SBListener.h" #include "lldb/API/SBEvent.h" +#include "lldb/API/SBListener.h" using namespace lldb; using namespace lldb_private; +SBBroadcaster::SBBroadcaster() : m_opaque_sp(), m_opaque_ptr(NULL) {} -SBBroadcaster::SBBroadcaster () : - m_opaque_sp (), - m_opaque_ptr (NULL) -{ -} - -SBBroadcaster::SBBroadcaster (const char *name) : - m_opaque_sp (new Broadcaster (NULL, name)), - m_opaque_ptr (NULL) -{ - m_opaque_ptr = m_opaque_sp.get(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API | LIBLLDB_LOG_VERBOSE)); +SBBroadcaster::SBBroadcaster(const char *name) + : m_opaque_sp(new Broadcaster(NULL, name)), m_opaque_ptr(NULL) { + m_opaque_ptr = m_opaque_sp.get(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API | + LIBLLDB_LOG_VERBOSE)); - if (log) - log->Printf ("SBBroadcaster::SBBroadcaster (name=\"%s\") => SBBroadcaster(%p)", - name, static_cast(m_opaque_ptr)); + if (log) + log->Printf( + "SBBroadcaster::SBBroadcaster (name=\"%s\") => SBBroadcaster(%p)", name, + static_cast(m_opaque_ptr)); } -SBBroadcaster::SBBroadcaster (lldb_private::Broadcaster *broadcaster, bool owns) : - m_opaque_sp (owns ? broadcaster : NULL), - m_opaque_ptr (broadcaster) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API | LIBLLDB_LOG_VERBOSE)); +SBBroadcaster::SBBroadcaster(lldb_private::Broadcaster *broadcaster, bool owns) + : m_opaque_sp(owns ? broadcaster : NULL), m_opaque_ptr(broadcaster) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API | + LIBLLDB_LOG_VERBOSE)); - if (log) - log->Printf ("SBBroadcaster::SBBroadcaster (broadcaster=%p, bool owns=%i) => SBBroadcaster(%p)", - static_cast(broadcaster), owns, - static_cast(m_opaque_ptr)); + if (log) + log->Printf("SBBroadcaster::SBBroadcaster (broadcaster=%p, bool owns=%i) " + "=> SBBroadcaster(%p)", + static_cast(broadcaster), owns, + static_cast(m_opaque_ptr)); } -SBBroadcaster::SBBroadcaster (const SBBroadcaster &rhs) : - m_opaque_sp (rhs.m_opaque_sp), - m_opaque_ptr (rhs.m_opaque_ptr) -{ -} +SBBroadcaster::SBBroadcaster(const SBBroadcaster &rhs) + : m_opaque_sp(rhs.m_opaque_sp), m_opaque_ptr(rhs.m_opaque_ptr) {} -const SBBroadcaster & -SBBroadcaster::operator = (const SBBroadcaster &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - m_opaque_ptr = rhs.m_opaque_ptr; - } - return *this; +const SBBroadcaster &SBBroadcaster::operator=(const SBBroadcaster &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + m_opaque_ptr = rhs.m_opaque_ptr; + } + return *this; } -SBBroadcaster::~SBBroadcaster() -{ - reset (NULL, false); -} +SBBroadcaster::~SBBroadcaster() { reset(NULL, false); } -void -SBBroadcaster::BroadcastEventByType (uint32_t event_type, bool unique) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBBroadcaster::BroadcastEventByType(uint32_t event_type, bool unique) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBroadcaster(%p)::BroadcastEventByType (event_type=0x%8.8x, unique=%i)", - static_cast(m_opaque_ptr), event_type, unique); + if (log) + log->Printf("SBBroadcaster(%p)::BroadcastEventByType (event_type=0x%8.8x, " + "unique=%i)", + static_cast(m_opaque_ptr), event_type, unique); - if (m_opaque_ptr == NULL) - return; + if (m_opaque_ptr == NULL) + return; - if (unique) - m_opaque_ptr->BroadcastEventIfUnique (event_type); - else - m_opaque_ptr->BroadcastEvent (event_type); + if (unique) + m_opaque_ptr->BroadcastEventIfUnique(event_type); + else + m_opaque_ptr->BroadcastEvent(event_type); } -void -SBBroadcaster::BroadcastEvent (const SBEvent &event, bool unique) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBBroadcaster::BroadcastEvent(const SBEvent &event, bool unique) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBroadcaster(%p)::BroadcastEventByType (SBEvent(%p), unique=%i)", - static_cast(m_opaque_ptr), - static_cast(event.get()), unique); + if (log) + log->Printf( + "SBBroadcaster(%p)::BroadcastEventByType (SBEvent(%p), unique=%i)", + static_cast(m_opaque_ptr), static_cast(event.get()), + unique); - if (m_opaque_ptr == NULL) - return; + if (m_opaque_ptr == NULL) + return; - EventSP event_sp = event.GetSP (); - if (unique) - m_opaque_ptr->BroadcastEventIfUnique (event_sp); - else - m_opaque_ptr->BroadcastEvent (event_sp); + EventSP event_sp = event.GetSP(); + if (unique) + m_opaque_ptr->BroadcastEventIfUnique(event_sp); + else + m_opaque_ptr->BroadcastEvent(event_sp); } -void -SBBroadcaster::AddInitialEventsToListener (const SBListener &listener, uint32_t requested_events) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBBroadcaster(%p)::AddInitialEventsToListener (SBListener(%p), event_mask=0x%8.8x)", - static_cast(m_opaque_ptr), - static_cast(listener.get()), requested_events); - if (m_opaque_ptr) - m_opaque_ptr->AddInitialEventsToListener (listener.m_opaque_sp, requested_events); +void SBBroadcaster::AddInitialEventsToListener(const SBListener &listener, + uint32_t requested_events) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBBroadcaster(%p)::AddInitialEventsToListener " + "(SBListener(%p), event_mask=0x%8.8x)", + static_cast(m_opaque_ptr), + static_cast(listener.get()), requested_events); + if (m_opaque_ptr) + m_opaque_ptr->AddInitialEventsToListener(listener.m_opaque_sp, + requested_events); } -uint32_t -SBBroadcaster::AddListener (const SBListener &listener, uint32_t event_mask) -{ - if (m_opaque_ptr) - return m_opaque_ptr->AddListener (listener.m_opaque_sp, event_mask); - return 0; +uint32_t SBBroadcaster::AddListener(const SBListener &listener, + uint32_t event_mask) { + if (m_opaque_ptr) + return m_opaque_ptr->AddListener(listener.m_opaque_sp, event_mask); + return 0; } -const char * -SBBroadcaster::GetName () const -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetBroadcasterName().GetCString(); - return NULL; +const char *SBBroadcaster::GetName() const { + if (m_opaque_ptr) + return m_opaque_ptr->GetBroadcasterName().GetCString(); + return NULL; } -bool -SBBroadcaster::EventTypeHasListeners (uint32_t event_type) -{ - if (m_opaque_ptr) - return m_opaque_ptr->EventTypeHasListeners (event_type); - return false; +bool SBBroadcaster::EventTypeHasListeners(uint32_t event_type) { + if (m_opaque_ptr) + return m_opaque_ptr->EventTypeHasListeners(event_type); + return false; } -bool -SBBroadcaster::RemoveListener (const SBListener &listener, uint32_t event_mask) -{ - if (m_opaque_ptr) - return m_opaque_ptr->RemoveListener (listener.m_opaque_sp, event_mask); - return false; +bool SBBroadcaster::RemoveListener(const SBListener &listener, + uint32_t event_mask) { + if (m_opaque_ptr) + return m_opaque_ptr->RemoveListener(listener.m_opaque_sp, event_mask); + return false; } -Broadcaster * -SBBroadcaster::get () const -{ - return m_opaque_ptr; -} +Broadcaster *SBBroadcaster::get() const { return m_opaque_ptr; } -void -SBBroadcaster::reset (Broadcaster *broadcaster, bool owns) -{ - if (owns) - m_opaque_sp.reset (broadcaster); - else - m_opaque_sp.reset (); - m_opaque_ptr = broadcaster; +void SBBroadcaster::reset(Broadcaster *broadcaster, bool owns) { + if (owns) + m_opaque_sp.reset(broadcaster); + else + m_opaque_sp.reset(); + m_opaque_ptr = broadcaster; } +bool SBBroadcaster::IsValid() const { return m_opaque_ptr != NULL; } -bool -SBBroadcaster::IsValid () const -{ - return m_opaque_ptr != NULL; -} - -void -SBBroadcaster::Clear () -{ - m_opaque_sp.reset(); - m_opaque_ptr = NULL; +void SBBroadcaster::Clear() { + m_opaque_sp.reset(); + m_opaque_ptr = NULL; } -bool -SBBroadcaster::operator == (const SBBroadcaster &rhs) const -{ - return m_opaque_ptr == rhs.m_opaque_ptr; - +bool SBBroadcaster::operator==(const SBBroadcaster &rhs) const { + return m_opaque_ptr == rhs.m_opaque_ptr; } -bool -SBBroadcaster::operator != (const SBBroadcaster &rhs) const -{ - return m_opaque_ptr != rhs.m_opaque_ptr; +bool SBBroadcaster::operator!=(const SBBroadcaster &rhs) const { + return m_opaque_ptr != rhs.m_opaque_ptr; } -bool -SBBroadcaster::operator < (const SBBroadcaster &rhs) const -{ - return m_opaque_ptr < rhs.m_opaque_ptr; +bool SBBroadcaster::operator<(const SBBroadcaster &rhs) const { + return m_opaque_ptr < rhs.m_opaque_ptr; } diff --git a/lldb/source/API/SBCommandInterpreter.cpp b/lldb/source/API/SBCommandInterpreter.cpp index c93db506c5a..95164c13e5e 100644 --- a/lldb/source/API/SBCommandInterpreter.cpp +++ b/lldb/source/API/SBCommandInterpreter.cpp @@ -20,698 +20,595 @@ #include "lldb/Target/Target.h" #include "lldb/API/SBBroadcaster.h" -#include "lldb/API/SBCommandReturnObject.h" #include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandReturnObject.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBExecutionContext.h" -#include "lldb/API/SBProcess.h" -#include "lldb/API/SBTarget.h" #include "lldb/API/SBListener.h" +#include "lldb/API/SBProcess.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBStringList.h" +#include "lldb/API/SBTarget.h" using namespace lldb; using namespace lldb_private; -SBCommandInterpreterRunOptions::SBCommandInterpreterRunOptions() -{ - m_opaque_up.reset(new CommandInterpreterRunOptions()); +SBCommandInterpreterRunOptions::SBCommandInterpreterRunOptions() { + m_opaque_up.reset(new CommandInterpreterRunOptions()); } SBCommandInterpreterRunOptions::~SBCommandInterpreterRunOptions() = default; -bool -SBCommandInterpreterRunOptions::GetStopOnContinue () const -{ - return m_opaque_up->GetStopOnContinue(); +bool SBCommandInterpreterRunOptions::GetStopOnContinue() const { + return m_opaque_up->GetStopOnContinue(); } -void -SBCommandInterpreterRunOptions::SetStopOnContinue (bool stop_on_continue) -{ - m_opaque_up->SetStopOnContinue(stop_on_continue); +void SBCommandInterpreterRunOptions::SetStopOnContinue(bool stop_on_continue) { + m_opaque_up->SetStopOnContinue(stop_on_continue); } -bool -SBCommandInterpreterRunOptions::GetStopOnError () const -{ - return m_opaque_up->GetStopOnError(); +bool SBCommandInterpreterRunOptions::GetStopOnError() const { + return m_opaque_up->GetStopOnError(); } -void -SBCommandInterpreterRunOptions::SetStopOnError (bool stop_on_error) -{ - m_opaque_up->SetStopOnError(stop_on_error); +void SBCommandInterpreterRunOptions::SetStopOnError(bool stop_on_error) { + m_opaque_up->SetStopOnError(stop_on_error); } -bool -SBCommandInterpreterRunOptions::GetStopOnCrash () const -{ - return m_opaque_up->GetStopOnCrash(); +bool SBCommandInterpreterRunOptions::GetStopOnCrash() const { + return m_opaque_up->GetStopOnCrash(); } -void -SBCommandInterpreterRunOptions::SetStopOnCrash (bool stop_on_crash) -{ - m_opaque_up->SetStopOnCrash(stop_on_crash); +void SBCommandInterpreterRunOptions::SetStopOnCrash(bool stop_on_crash) { + m_opaque_up->SetStopOnCrash(stop_on_crash); } -bool -SBCommandInterpreterRunOptions::GetEchoCommands () const -{ - return m_opaque_up->GetEchoCommands(); +bool SBCommandInterpreterRunOptions::GetEchoCommands() const { + return m_opaque_up->GetEchoCommands(); } -void -SBCommandInterpreterRunOptions::SetEchoCommands (bool echo_commands) -{ - m_opaque_up->SetEchoCommands(echo_commands); +void SBCommandInterpreterRunOptions::SetEchoCommands(bool echo_commands) { + m_opaque_up->SetEchoCommands(echo_commands); } -bool -SBCommandInterpreterRunOptions::GetPrintResults () const -{ - return m_opaque_up->GetPrintResults(); +bool SBCommandInterpreterRunOptions::GetPrintResults() const { + return m_opaque_up->GetPrintResults(); } -void -SBCommandInterpreterRunOptions::SetPrintResults (bool print_results) -{ - m_opaque_up->SetPrintResults(print_results); +void SBCommandInterpreterRunOptions::SetPrintResults(bool print_results) { + m_opaque_up->SetPrintResults(print_results); } -bool -SBCommandInterpreterRunOptions::GetAddToHistory () const -{ - return m_opaque_up->GetAddToHistory(); +bool SBCommandInterpreterRunOptions::GetAddToHistory() const { + return m_opaque_up->GetAddToHistory(); } -void -SBCommandInterpreterRunOptions::SetAddToHistory (bool add_to_history) -{ - m_opaque_up->SetAddToHistory(add_to_history); +void SBCommandInterpreterRunOptions::SetAddToHistory(bool add_to_history) { + m_opaque_up->SetAddToHistory(add_to_history); } lldb_private::CommandInterpreterRunOptions * -SBCommandInterpreterRunOptions::get () const -{ - return m_opaque_up.get(); +SBCommandInterpreterRunOptions::get() const { + return m_opaque_up.get(); } lldb_private::CommandInterpreterRunOptions & -SBCommandInterpreterRunOptions::ref () const -{ - return *m_opaque_up.get(); +SBCommandInterpreterRunOptions::ref() const { + return *m_opaque_up.get(); } -class CommandPluginInterfaceImplementation : public CommandObjectParsed -{ +class CommandPluginInterfaceImplementation : public CommandObjectParsed { public: - CommandPluginInterfaceImplementation(CommandInterpreter &interpreter, - const char *name, - lldb::SBCommandPluginInterface* backend, - const char *help = nullptr, - const char *syntax = nullptr, - uint32_t flags = 0) : - CommandObjectParsed (interpreter, name, help, syntax, flags), - m_backend(backend) {} - - bool - IsRemovable() const override - { - return true; - } - + CommandPluginInterfaceImplementation(CommandInterpreter &interpreter, + const char *name, + lldb::SBCommandPluginInterface *backend, + const char *help = nullptr, + const char *syntax = nullptr, + uint32_t flags = 0) + : CommandObjectParsed(interpreter, name, help, syntax, flags), + m_backend(backend) {} + + bool IsRemovable() const override { return true; } + protected: - bool - DoExecute(Args& command, CommandReturnObject &result) override - { - SBCommandReturnObject sb_return(&result); - SBCommandInterpreter sb_interpreter(&m_interpreter); - SBDebugger debugger_sb(m_interpreter.GetDebugger().shared_from_this()); - bool ret = m_backend->DoExecute (debugger_sb,(char**)command.GetArgumentVector(), sb_return); - sb_return.Release(); - return ret; - } - std::shared_ptr m_backend; + bool DoExecute(Args &command, CommandReturnObject &result) override { + SBCommandReturnObject sb_return(&result); + SBCommandInterpreter sb_interpreter(&m_interpreter); + SBDebugger debugger_sb(m_interpreter.GetDebugger().shared_from_this()); + bool ret = m_backend->DoExecute( + debugger_sb, (char **)command.GetArgumentVector(), sb_return); + sb_return.Release(); + return ret; + } + std::shared_ptr m_backend; }; -SBCommandInterpreter::SBCommandInterpreter (CommandInterpreter *interpreter) : - m_opaque_ptr (interpreter) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBCommandInterpreter::SBCommandInterpreter(CommandInterpreter *interpreter) + : m_opaque_ptr(interpreter) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommandInterpreter::SBCommandInterpreter (interpreter=%p)" - " => SBCommandInterpreter(%p)", - static_cast(interpreter), - static_cast(m_opaque_ptr)); + if (log) + log->Printf("SBCommandInterpreter::SBCommandInterpreter (interpreter=%p)" + " => SBCommandInterpreter(%p)", + static_cast(interpreter), + static_cast(m_opaque_ptr)); } -SBCommandInterpreter::SBCommandInterpreter(const SBCommandInterpreter &rhs) : - m_opaque_ptr (rhs.m_opaque_ptr) -{ -} +SBCommandInterpreter::SBCommandInterpreter(const SBCommandInterpreter &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) {} SBCommandInterpreter::~SBCommandInterpreter() = default; -const SBCommandInterpreter & -SBCommandInterpreter::operator = (const SBCommandInterpreter &rhs) -{ - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; +const SBCommandInterpreter &SBCommandInterpreter:: +operator=(const SBCommandInterpreter &rhs) { + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; } -bool -SBCommandInterpreter::IsValid() const -{ - return m_opaque_ptr != nullptr; -} +bool SBCommandInterpreter::IsValid() const { return m_opaque_ptr != nullptr; } -bool -SBCommandInterpreter::CommandExists(const char *cmd) -{ - return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->CommandExists(cmd) : false); +bool SBCommandInterpreter::CommandExists(const char *cmd) { + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->CommandExists(cmd) + : false); } -bool -SBCommandInterpreter::AliasExists (const char *cmd) -{ - return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->AliasExists(cmd) : false); +bool SBCommandInterpreter::AliasExists(const char *cmd) { + return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->AliasExists(cmd) + : false); } -bool -SBCommandInterpreter::IsActive() -{ - return (IsValid() ? m_opaque_ptr->IsActive() : false); +bool SBCommandInterpreter::IsActive() { + return (IsValid() ? m_opaque_ptr->IsActive() : false); } -const char * -SBCommandInterpreter::GetIOHandlerControlSequence(char ch) -{ - return (IsValid() ? m_opaque_ptr->GetDebugger().GetTopIOHandlerControlSequence(ch).GetCString() : nullptr); -} - -lldb::ReturnStatus -SBCommandInterpreter::HandleCommand (const char *command_line, SBCommandReturnObject &result, bool add_to_history) -{ - SBExecutionContext sb_exe_ctx; - return HandleCommand (command_line, sb_exe_ctx, result, add_to_history); +const char *SBCommandInterpreter::GetIOHandlerControlSequence(char ch) { + return (IsValid() + ? m_opaque_ptr->GetDebugger() + .GetTopIOHandlerControlSequence(ch) + .GetCString() + : nullptr); } lldb::ReturnStatus -SBCommandInterpreter::HandleCommand (const char *command_line, SBExecutionContext &override_context, SBCommandReturnObject &result, bool add_to_history) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", SBCommandReturnObject(%p), add_to_history=%i)", - static_cast(m_opaque_ptr), command_line, - static_cast(result.get()), add_to_history); - - ExecutionContext ctx, *ctx_ptr; - if (override_context.get()) - { - ctx = override_context.get()->Lock(true); - ctx_ptr = &ctx; +SBCommandInterpreter::HandleCommand(const char *command_line, + SBCommandReturnObject &result, + bool add_to_history) { + SBExecutionContext sb_exe_ctx; + return HandleCommand(command_line, sb_exe_ctx, result, add_to_history); +} + +lldb::ReturnStatus SBCommandInterpreter::HandleCommand( + const char *command_line, SBExecutionContext &override_context, + SBCommandReturnObject &result, bool add_to_history) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", " + "SBCommandReturnObject(%p), add_to_history=%i)", + static_cast(m_opaque_ptr), command_line, + static_cast(result.get()), add_to_history); + + ExecutionContext ctx, *ctx_ptr; + if (override_context.get()) { + ctx = override_context.get()->Lock(true); + ctx_ptr = &ctx; + } else + ctx_ptr = nullptr; + + result.Clear(); + if (command_line && IsValid()) { + result.ref().SetInteractive(false); + m_opaque_ptr->HandleCommand(command_line, + add_to_history ? eLazyBoolYes : eLazyBoolNo, + result.ref(), ctx_ptr); + } else { + result->AppendError( + "SBCommandInterpreter or the command line is not valid"); + result->SetStatus(eReturnStatusFailed); + } + + // We need to get the value again, in case the command disabled the log! + log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); + if (log) { + SBStream sstr; + result.GetDescription(sstr); + log->Printf("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", " + "SBCommandReturnObject(%p): %s, add_to_history=%i) => %i", + static_cast(m_opaque_ptr), command_line, + static_cast(result.get()), sstr.GetData(), + add_to_history, result.GetStatus()); + } + + return result.GetStatus(); +} + +void SBCommandInterpreter::HandleCommandsFromFile( + lldb::SBFileSpec &file, lldb::SBExecutionContext &override_context, + lldb::SBCommandInterpreterRunOptions &options, + lldb::SBCommandReturnObject result) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) { + SBStream s; + file.GetDescription(s); + log->Printf("SBCommandInterpreter(%p)::HandleCommandsFromFile " + "(file=\"%s\", SBCommandReturnObject(%p))", + static_cast(m_opaque_ptr), s.GetData(), + static_cast(result.get())); + } + + if (!IsValid()) { + result->AppendError("SBCommandInterpreter is not valid."); + result->SetStatus(eReturnStatusFailed); + return; + } + + if (!file.IsValid()) { + SBStream s; + file.GetDescription(s); + result->AppendErrorWithFormat("File is not valid: %s.", s.GetData()); + result->SetStatus(eReturnStatusFailed); + } + + FileSpec tmp_spec = file.ref(); + ExecutionContext ctx, *ctx_ptr; + if (override_context.get()) { + ctx = override_context.get()->Lock(true); + ctx_ptr = &ctx; + } else + ctx_ptr = nullptr; + + m_opaque_ptr->HandleCommandsFromFile(tmp_spec, ctx_ptr, options.ref(), + result.ref()); +} + +int SBCommandInterpreter::HandleCompletion( + const char *current_line, const char *cursor, const char *last_char, + int match_start_point, int max_return_elements, SBStringList &matches) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + int num_completions = 0; + + // Sanity check the arguments that are passed in: + // cursor & last_char have to be within the current_line. + if (current_line == nullptr || cursor == nullptr || last_char == nullptr) + return 0; + + if (cursor < current_line || last_char < current_line) + return 0; + + size_t current_line_size = strlen(current_line); + if (cursor - current_line > static_cast(current_line_size) || + last_char - current_line > static_cast(current_line_size)) + return 0; + + if (log) + log->Printf("SBCommandInterpreter(%p)::HandleCompletion " + "(current_line=\"%s\", cursor at: %" PRId64 + ", last char at: %" PRId64 + ", match_start_point: %d, max_return_elements: %d)", + static_cast(m_opaque_ptr), current_line, + static_cast(cursor - current_line), + static_cast(last_char - current_line), + match_start_point, max_return_elements); + + if (IsValid()) { + lldb_private::StringList lldb_matches; + num_completions = m_opaque_ptr->HandleCompletion( + current_line, cursor, last_char, match_start_point, max_return_elements, + lldb_matches); + + SBStringList temp_list(&lldb_matches); + matches.AppendList(temp_list); + } + if (log) + log->Printf( + "SBCommandInterpreter(%p)::HandleCompletion - Found %d completions.", + static_cast(m_opaque_ptr), num_completions); + + return num_completions; +} + +int SBCommandInterpreter::HandleCompletion(const char *current_line, + uint32_t cursor_pos, + int match_start_point, + int max_return_elements, + lldb::SBStringList &matches) { + const char *cursor = current_line + cursor_pos; + const char *last_char = current_line + strlen(current_line); + return HandleCompletion(current_line, cursor, last_char, match_start_point, + max_return_elements, matches); +} + +bool SBCommandInterpreter::HasCommands() { + return (IsValid() ? m_opaque_ptr->HasCommands() : false); +} + +bool SBCommandInterpreter::HasAliases() { + return (IsValid() ? m_opaque_ptr->HasAliases() : false); +} + +bool SBCommandInterpreter::HasAliasOptions() { + return (IsValid() ? m_opaque_ptr->HasAliasOptions() : false); +} + +SBProcess SBCommandInterpreter::GetProcess() { + SBProcess sb_process; + ProcessSP process_sp; + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + process_sp = target_sp->GetProcessSP(); + sb_process.SetSP(process_sp); } - else - ctx_ptr = nullptr; + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBCommandInterpreter(%p)::GetProcess () => SBProcess(%p)", + static_cast(m_opaque_ptr), + static_cast(process_sp.get())); - result.Clear(); - if (command_line && IsValid()) - { - result.ref().SetInteractive(false); - m_opaque_ptr->HandleCommand (command_line, add_to_history ? eLazyBoolYes : eLazyBoolNo, result.ref(), ctx_ptr); - } - else - { - result->AppendError ("SBCommandInterpreter or the command line is not valid"); - result->SetStatus (eReturnStatusFailed); - } - - // We need to get the value again, in case the command disabled the log! - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API); - if (log) - { - SBStream sstr; - result.GetDescription (sstr); - log->Printf ("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", SBCommandReturnObject(%p): %s, add_to_history=%i) => %i", - static_cast(m_opaque_ptr), command_line, - static_cast(result.get()), sstr.GetData(), - add_to_history, result.GetStatus()); - } - - return result.GetStatus(); + return sb_process; } -void -SBCommandInterpreter::HandleCommandsFromFile (lldb::SBFileSpec &file, - lldb::SBExecutionContext &override_context, - lldb::SBCommandInterpreterRunOptions &options, - lldb::SBCommandReturnObject result) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - { - SBStream s; - file.GetDescription (s); - log->Printf ("SBCommandInterpreter(%p)::HandleCommandsFromFile (file=\"%s\", SBCommandReturnObject(%p))", - static_cast(m_opaque_ptr), s.GetData(), - static_cast(result.get())); - } - - if (!IsValid()) - { - result->AppendError ("SBCommandInterpreter is not valid."); - result->SetStatus (eReturnStatusFailed); - return; - } - - if (!file.IsValid()) - { - SBStream s; - file.GetDescription (s); - result->AppendErrorWithFormat ("File is not valid: %s.", s.GetData()); - result->SetStatus (eReturnStatusFailed); - } - - FileSpec tmp_spec = file.ref(); - ExecutionContext ctx, *ctx_ptr; - if (override_context.get()) - { - ctx = override_context.get()->Lock(true); - ctx_ptr = &ctx; - } - else - ctx_ptr = nullptr; - - m_opaque_ptr->HandleCommandsFromFile (tmp_spec, ctx_ptr, options.ref(), result.ref()); -} - -int -SBCommandInterpreter::HandleCompletion (const char *current_line, - const char *cursor, - const char *last_char, - int match_start_point, - int max_return_elements, - SBStringList &matches) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - int num_completions = 0; - - // Sanity check the arguments that are passed in: - // cursor & last_char have to be within the current_line. - if (current_line == nullptr || cursor == nullptr || last_char == nullptr) - return 0; - - if (cursor < current_line || last_char < current_line) - return 0; - - size_t current_line_size = strlen (current_line); - if (cursor - current_line > static_cast(current_line_size) || - last_char - current_line > static_cast(current_line_size)) - return 0; - - if (log) - log->Printf ("SBCommandInterpreter(%p)::HandleCompletion (current_line=\"%s\", cursor at: %" PRId64 ", last char at: %" PRId64 ", match_start_point: %d, max_return_elements: %d)", - static_cast(m_opaque_ptr), current_line, - static_cast(cursor - current_line), - static_cast(last_char - current_line), - match_start_point, max_return_elements); - - if (IsValid()) - { - lldb_private::StringList lldb_matches; - num_completions = m_opaque_ptr->HandleCompletion(current_line, cursor, last_char, match_start_point, - max_return_elements, lldb_matches); - - SBStringList temp_list (&lldb_matches); - matches.AppendList (temp_list); - } - if (log) - log->Printf ("SBCommandInterpreter(%p)::HandleCompletion - Found %d completions.", - static_cast(m_opaque_ptr), num_completions); - - return num_completions; -} - -int -SBCommandInterpreter::HandleCompletion (const char *current_line, - uint32_t cursor_pos, - int match_start_point, - int max_return_elements, - lldb::SBStringList &matches) -{ - const char *cursor = current_line + cursor_pos; - const char *last_char = current_line + strlen (current_line); - return HandleCompletion (current_line, cursor, last_char, match_start_point, max_return_elements, matches); -} - -bool -SBCommandInterpreter::HasCommands() -{ - return (IsValid() ? m_opaque_ptr->HasCommands() : false); -} - -bool -SBCommandInterpreter::HasAliases() -{ - return (IsValid() ? m_opaque_ptr->HasAliases() : false); -} - -bool -SBCommandInterpreter::HasAliasOptions() -{ - return (IsValid() ? m_opaque_ptr->HasAliasOptions() : false); -} - -SBProcess -SBCommandInterpreter::GetProcess () -{ - SBProcess sb_process; - ProcessSP process_sp; - if (IsValid()) - { - TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - process_sp = target_sp->GetProcessSP(); - sb_process.SetSP(process_sp); - } - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBDebugger SBCommandInterpreter::GetDebugger() { + SBDebugger sb_debugger; + if (IsValid()) + sb_debugger.reset(m_opaque_ptr->GetDebugger().shared_from_this()); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommandInterpreter(%p)::GetProcess () => SBProcess(%p)", - static_cast(m_opaque_ptr), - static_cast(process_sp.get())); + if (log) + log->Printf("SBCommandInterpreter(%p)::GetDebugger () => SBDebugger(%p)", + static_cast(m_opaque_ptr), + static_cast(sb_debugger.get())); - return sb_process; + return sb_debugger; } -SBDebugger -SBCommandInterpreter::GetDebugger () -{ - SBDebugger sb_debugger; - if (IsValid()) - sb_debugger.reset(m_opaque_ptr->GetDebugger().shared_from_this()); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBCommandInterpreter(%p)::GetDebugger () => SBDebugger(%p)", - static_cast(m_opaque_ptr), - static_cast(sb_debugger.get())); - - return sb_debugger; +bool SBCommandInterpreter::GetPromptOnQuit() { + return (IsValid() ? m_opaque_ptr->GetPromptOnQuit() : false); } -bool -SBCommandInterpreter::GetPromptOnQuit() -{ - return (IsValid() ? m_opaque_ptr->GetPromptOnQuit() : false); +void SBCommandInterpreter::SetPromptOnQuit(bool b) { + if (IsValid()) + m_opaque_ptr->SetPromptOnQuit(b); } -void -SBCommandInterpreter::SetPromptOnQuit (bool b) -{ - if (IsValid()) - m_opaque_ptr->SetPromptOnQuit(b); +void SBCommandInterpreter::ResolveCommand(const char *command_line, + SBCommandReturnObject &result) { + result.Clear(); + if (command_line && IsValid()) { + m_opaque_ptr->ResolveCommand(command_line, result.ref()); + } else { + result->AppendError( + "SBCommandInterpreter or the command line is not valid"); + result->SetStatus(eReturnStatusFailed); + } } -void -SBCommandInterpreter::ResolveCommand(const char *command_line, SBCommandReturnObject &result) -{ - result.Clear(); - if (command_line && IsValid()) - { - m_opaque_ptr->ResolveCommand(command_line, result.ref()); - } - else - { - result->AppendError("SBCommandInterpreter or the command line is not valid"); - result->SetStatus(eReturnStatusFailed); - } -} +CommandInterpreter *SBCommandInterpreter::get() { return m_opaque_ptr; } -CommandInterpreter * -SBCommandInterpreter::get () -{ - return m_opaque_ptr; +CommandInterpreter &SBCommandInterpreter::ref() { + assert(m_opaque_ptr); + return *m_opaque_ptr; } -CommandInterpreter & -SBCommandInterpreter::ref () -{ - assert (m_opaque_ptr); - return *m_opaque_ptr; +void SBCommandInterpreter::reset( + lldb_private::CommandInterpreter *interpreter) { + m_opaque_ptr = interpreter; } -void -SBCommandInterpreter::reset (lldb_private::CommandInterpreter *interpreter) -{ - m_opaque_ptr = interpreter; +void SBCommandInterpreter::SourceInitFileInHomeDirectory( + SBCommandReturnObject &result) { + result.Clear(); + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + std::unique_lock lock; + if (target_sp) + lock = std::unique_lock(target_sp->GetAPIMutex()); + m_opaque_ptr->SourceInitFile(false, result.ref()); + } else { + result->AppendError("SBCommandInterpreter is not valid"); + result->SetStatus(eReturnStatusFailed); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBCommandInterpreter(%p)::SourceInitFileInHomeDirectory " + "(&SBCommandReturnObject(%p))", + static_cast(m_opaque_ptr), + static_cast(result.get())); } -void -SBCommandInterpreter::SourceInitFileInHomeDirectory (SBCommandReturnObject &result) -{ - result.Clear(); - if (IsValid()) - { - TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); - std::unique_lock lock; - if (target_sp) - lock = std::unique_lock(target_sp->GetAPIMutex()); - m_opaque_ptr->SourceInitFile (false, result.ref()); - } - else - { - result->AppendError ("SBCommandInterpreter is not valid"); - result->SetStatus (eReturnStatusFailed); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBCommandInterpreter(%p)::SourceInitFileInHomeDirectory (&SBCommandReturnObject(%p))", - static_cast(m_opaque_ptr), - static_cast(result.get())); -} - -void -SBCommandInterpreter::SourceInitFileInCurrentWorkingDirectory (SBCommandReturnObject &result) -{ - result.Clear(); - if (IsValid()) - { - TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); - std::unique_lock lock; - if (target_sp) - lock = std::unique_lock(target_sp->GetAPIMutex()); - m_opaque_ptr->SourceInitFile (true, result.ref()); - } - else - { - result->AppendError ("SBCommandInterpreter is not valid"); - result->SetStatus (eReturnStatusFailed); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBCommandInterpreter::SourceInitFileInCurrentWorkingDirectory( + SBCommandReturnObject &result) { + result.Clear(); + if (IsValid()) { + TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget()); + std::unique_lock lock; + if (target_sp) + lock = std::unique_lock(target_sp->GetAPIMutex()); + m_opaque_ptr->SourceInitFile(true, result.ref()); + } else { + result->AppendError("SBCommandInterpreter is not valid"); + result->SetStatus(eReturnStatusFailed); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommandInterpreter(%p)::SourceInitFileInCurrentWorkingDirectory (&SBCommandReturnObject(%p))", - static_cast(m_opaque_ptr), - static_cast(result.get())); + if (log) + log->Printf( + "SBCommandInterpreter(%p)::SourceInitFileInCurrentWorkingDirectory " + "(&SBCommandReturnObject(%p))", + static_cast(m_opaque_ptr), static_cast(result.get())); } -SBBroadcaster -SBCommandInterpreter::GetBroadcaster () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBBroadcaster SBCommandInterpreter::GetBroadcaster() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBBroadcaster broadcaster (m_opaque_ptr, false); + SBBroadcaster broadcaster(m_opaque_ptr, false); - if (log) - log->Printf ("SBCommandInterpreter(%p)::GetBroadcaster() => SBBroadcaster(%p)", - static_cast(m_opaque_ptr), static_cast(broadcaster.get())); - - return broadcaster; -} + if (log) + log->Printf( + "SBCommandInterpreter(%p)::GetBroadcaster() => SBBroadcaster(%p)", + static_cast(m_opaque_ptr), + static_cast(broadcaster.get())); -const char * -SBCommandInterpreter::GetBroadcasterClass () -{ - return CommandInterpreter::GetStaticBroadcasterClass().AsCString(); + return broadcaster; } -const char * -SBCommandInterpreter::GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type) -{ - return CommandObject::GetArgumentTypeAsCString (arg_type); +const char *SBCommandInterpreter::GetBroadcasterClass() { + return CommandInterpreter::GetStaticBroadcasterClass().AsCString(); } -const char * -SBCommandInterpreter::GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type) -{ - return CommandObject::GetArgumentDescriptionAsCString (arg_type); +const char *SBCommandInterpreter::GetArgumentTypeAsCString( + const lldb::CommandArgumentType arg_type) { + return CommandObject::GetArgumentTypeAsCString(arg_type); } -bool -SBCommandInterpreter::EventIsCommandInterpreterEvent (const lldb::SBEvent &event) -{ - return event.GetBroadcasterClass() == SBCommandInterpreter::GetBroadcasterClass(); +const char *SBCommandInterpreter::GetArgumentDescriptionAsCString( + const lldb::CommandArgumentType arg_type) { + return CommandObject::GetArgumentDescriptionAsCString(arg_type); } - -bool -SBCommandInterpreter::SetCommandOverrideCallback (const char *command_name, - lldb::CommandOverrideCallback callback, - void *baton) -{ - if (command_name && command_name[0] && IsValid()) - { - std::string command_name_str (command_name); - CommandObject *cmd_obj = m_opaque_ptr->GetCommandObjectForCommand(command_name_str); - if (cmd_obj) - { - assert(command_name_str.empty()); - cmd_obj->SetOverrideCallback (callback, baton); - return true; - } + +bool SBCommandInterpreter::EventIsCommandInterpreterEvent( + const lldb::SBEvent &event) { + return event.GetBroadcasterClass() == + SBCommandInterpreter::GetBroadcasterClass(); +} + +bool SBCommandInterpreter::SetCommandOverrideCallback( + const char *command_name, lldb::CommandOverrideCallback callback, + void *baton) { + if (command_name && command_name[0] && IsValid()) { + std::string command_name_str(command_name); + CommandObject *cmd_obj = + m_opaque_ptr->GetCommandObjectForCommand(command_name_str); + if (cmd_obj) { + assert(command_name_str.empty()); + cmd_obj->SetOverrideCallback(callback, baton); + return true; } - return false; + } + return false; } -lldb::SBCommand -SBCommandInterpreter::AddMultiwordCommand (const char* name, const char* help) -{ - CommandObjectMultiword *new_command = new CommandObjectMultiword(*m_opaque_ptr, name, help); - new_command->SetRemovable (true); - lldb::CommandObjectSP new_command_sp(new_command); - if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); +lldb::SBCommand SBCommandInterpreter::AddMultiwordCommand(const char *name, + const char *help) { + CommandObjectMultiword *new_command = + new CommandObjectMultiword(*m_opaque_ptr, name, help); + new_command->SetRemovable(true); + lldb::CommandObjectSP new_command_sp(new_command); + if (new_command_sp && + m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); } -lldb::SBCommand -SBCommandInterpreter::AddCommand (const char* name, lldb::SBCommandPluginInterface* impl, const char* help) -{ - lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation(*m_opaque_ptr,name, impl, help)); +lldb::SBCommand SBCommandInterpreter::AddCommand( + const char *name, lldb::SBCommandPluginInterface *impl, const char *help) { + lldb::CommandObjectSP new_command_sp; + new_command_sp.reset(new CommandPluginInterfaceImplementation( + *m_opaque_ptr, name, impl, help)); - if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + if (new_command_sp && + m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); } lldb::SBCommand -SBCommandInterpreter::AddCommand (const char* name, lldb::SBCommandPluginInterface* impl, const char* help, const char* syntax) -{ - lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation(*m_opaque_ptr,name, impl, help, syntax)); +SBCommandInterpreter::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help, const char *syntax) { + lldb::CommandObjectSP new_command_sp; + new_command_sp.reset(new CommandPluginInterfaceImplementation( + *m_opaque_ptr, name, impl, help, syntax)); - if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) - return lldb::SBCommand(new_command_sp); - return lldb::SBCommand(); + if (new_command_sp && + m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); } SBCommand::SBCommand() = default; -SBCommand::SBCommand (lldb::CommandObjectSP cmd_sp) : m_opaque_sp (cmd_sp) -{} +SBCommand::SBCommand(lldb::CommandObjectSP cmd_sp) : m_opaque_sp(cmd_sp) {} -bool -SBCommand::IsValid() -{ - return m_opaque_sp.get() != nullptr; -} +bool SBCommand::IsValid() { return m_opaque_sp.get() != nullptr; } -const char* -SBCommand::GetName() -{ - return (IsValid() ? m_opaque_sp->GetCommandName() : nullptr); +const char *SBCommand::GetName() { + return (IsValid() ? m_opaque_sp->GetCommandName() : nullptr); } -const char* -SBCommand::GetHelp() -{ - return (IsValid() ? m_opaque_sp->GetHelp() : nullptr); +const char *SBCommand::GetHelp() { + return (IsValid() ? m_opaque_sp->GetHelp() : nullptr); } -const char* -SBCommand::GetHelpLong() -{ - return (IsValid() ? m_opaque_sp->GetHelpLong() : nullptr); +const char *SBCommand::GetHelpLong() { + return (IsValid() ? m_opaque_sp->GetHelpLong() : nullptr); } -void -SBCommand::SetHelp (const char* help) -{ - if (IsValid()) - m_opaque_sp->SetHelp(help); +void SBCommand::SetHelp(const char *help) { + if (IsValid()) + m_opaque_sp->SetHelp(help); } -void -SBCommand::SetHelpLong (const char* help) -{ - if (IsValid()) - m_opaque_sp->SetHelpLong(help); +void SBCommand::SetHelpLong(const char *help) { + if (IsValid()) + m_opaque_sp->SetHelpLong(help); } -lldb::SBCommand -SBCommand::AddMultiwordCommand (const char* name, const char* help) -{ - if (!IsValid ()) - return lldb::SBCommand(); - if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); - CommandObjectMultiword *new_command = new CommandObjectMultiword(m_opaque_sp->GetCommandInterpreter(),name,help); - new_command->SetRemovable (true); - lldb::CommandObjectSP new_command_sp(new_command); - if (new_command_sp && m_opaque_sp->LoadSubCommand(name,new_command_sp)) - return lldb::SBCommand(new_command_sp); +lldb::SBCommand SBCommand::AddMultiwordCommand(const char *name, + const char *help) { + if (!IsValid()) return lldb::SBCommand(); -} - -lldb::SBCommand -SBCommand::AddCommand (const char* name, lldb::SBCommandPluginInterface *impl, const char* help) -{ - if (!IsValid ()) - return lldb::SBCommand(); - if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); - lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation(m_opaque_sp->GetCommandInterpreter(),name,impl,help)); - if (new_command_sp && m_opaque_sp->LoadSubCommand(name,new_command_sp)) - return lldb::SBCommand(new_command_sp); + if (!m_opaque_sp->IsMultiwordObject()) return lldb::SBCommand(); -} - -lldb::SBCommand -SBCommand::AddCommand (const char* name, lldb::SBCommandPluginInterface *impl, const char* help, const char* syntax) -{ - if (!IsValid ()) - return lldb::SBCommand(); - if (!m_opaque_sp->IsMultiwordObject()) - return lldb::SBCommand(); - lldb::CommandObjectSP new_command_sp; - new_command_sp.reset(new CommandPluginInterfaceImplementation(m_opaque_sp->GetCommandInterpreter(),name,impl,help, syntax)); - if (new_command_sp && m_opaque_sp->LoadSubCommand(name,new_command_sp)) - return lldb::SBCommand(new_command_sp); + CommandObjectMultiword *new_command = new CommandObjectMultiword( + m_opaque_sp->GetCommandInterpreter(), name, help); + new_command->SetRemovable(true); + lldb::CommandObjectSP new_command_sp(new_command); + if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +lldb::SBCommand SBCommand::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help) { + if (!IsValid()) + return lldb::SBCommand(); + if (!m_opaque_sp->IsMultiwordObject()) return lldb::SBCommand(); + lldb::CommandObjectSP new_command_sp; + new_command_sp.reset(new CommandPluginInterfaceImplementation( + m_opaque_sp->GetCommandInterpreter(), name, impl, help)); + if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); +} + +lldb::SBCommand SBCommand::AddCommand(const char *name, + lldb::SBCommandPluginInterface *impl, + const char *help, const char *syntax) { + if (!IsValid()) + return lldb::SBCommand(); + if (!m_opaque_sp->IsMultiwordObject()) + return lldb::SBCommand(); + lldb::CommandObjectSP new_command_sp; + new_command_sp.reset(new CommandPluginInterfaceImplementation( + m_opaque_sp->GetCommandInterpreter(), name, impl, help, syntax)); + if (new_command_sp && m_opaque_sp->LoadSubCommand(name, new_command_sp)) + return lldb::SBCommand(new_command_sp); + return lldb::SBCommand(); } - -uint32_t -SBCommand::GetFlags () -{ - return (IsValid() ? m_opaque_sp->GetFlags().Get() : 0); +uint32_t SBCommand::GetFlags() { + return (IsValid() ? m_opaque_sp->GetFlags().Get() : 0); } -void -SBCommand::SetFlags (uint32_t flags) -{ - if (IsValid()) - m_opaque_sp->GetFlags().Set(flags); +void SBCommand::SetFlags(uint32_t flags) { + if (IsValid()) + m_opaque_sp->GetFlags().Set(flags); } diff --git a/lldb/source/API/SBCommandReturnObject.cpp b/lldb/source/API/SBCommandReturnObject.cpp index a7bc31da8a8..51e6781ffb5 100644 --- a/lldb/source/API/SBCommandReturnObject.cpp +++ b/lldb/source/API/SBCommandReturnObject.cpp @@ -22,333 +22,256 @@ using namespace lldb; using namespace lldb_private; -SBCommandReturnObject::SBCommandReturnObject () : - m_opaque_ap (new CommandReturnObject ()) -{ -} +SBCommandReturnObject::SBCommandReturnObject() + : m_opaque_ap(new CommandReturnObject()) {} -SBCommandReturnObject::SBCommandReturnObject (const SBCommandReturnObject &rhs): - m_opaque_ap () -{ - if (rhs.m_opaque_ap) - m_opaque_ap.reset (new CommandReturnObject (*rhs.m_opaque_ap)); +SBCommandReturnObject::SBCommandReturnObject(const SBCommandReturnObject &rhs) + : m_opaque_ap() { + if (rhs.m_opaque_ap) + m_opaque_ap.reset(new CommandReturnObject(*rhs.m_opaque_ap)); } -SBCommandReturnObject::SBCommandReturnObject (CommandReturnObject *ptr) : - m_opaque_ap (ptr) -{ -} +SBCommandReturnObject::SBCommandReturnObject(CommandReturnObject *ptr) + : m_opaque_ap(ptr) {} SBCommandReturnObject::~SBCommandReturnObject() = default; -CommandReturnObject * -SBCommandReturnObject::Release () -{ - return m_opaque_ap.release(); +CommandReturnObject *SBCommandReturnObject::Release() { + return m_opaque_ap.release(); } -const SBCommandReturnObject & -SBCommandReturnObject::operator = (const SBCommandReturnObject &rhs) -{ - if (this != &rhs) - { - if (rhs.m_opaque_ap) - m_opaque_ap.reset (new CommandReturnObject (*rhs.m_opaque_ap)); - else - m_opaque_ap.reset(); - } - return *this; +const SBCommandReturnObject &SBCommandReturnObject:: +operator=(const SBCommandReturnObject &rhs) { + if (this != &rhs) { + if (rhs.m_opaque_ap) + m_opaque_ap.reset(new CommandReturnObject(*rhs.m_opaque_ap)); + else + m_opaque_ap.reset(); + } + return *this; } -bool -SBCommandReturnObject::IsValid() const -{ - return m_opaque_ap.get() != nullptr; +bool SBCommandReturnObject::IsValid() const { + return m_opaque_ap.get() != nullptr; } -const char * -SBCommandReturnObject::GetOutput () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +const char *SBCommandReturnObject::GetOutput() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (m_opaque_ap) - { - if (log) - log->Printf ("SBCommandReturnObject(%p)::GetOutput () => \"%s\"", - static_cast(m_opaque_ap.get()), - m_opaque_ap->GetOutputData()); + if (m_opaque_ap) { + if (log) + log->Printf("SBCommandReturnObject(%p)::GetOutput () => \"%s\"", + static_cast(m_opaque_ap.get()), + m_opaque_ap->GetOutputData()); - return m_opaque_ap->GetOutputData(); - } + return m_opaque_ap->GetOutputData(); + } - if (log) - log->Printf ("SBCommandReturnObject(%p)::GetOutput () => nullptr", - static_cast(m_opaque_ap.get())); + if (log) + log->Printf("SBCommandReturnObject(%p)::GetOutput () => nullptr", + static_cast(m_opaque_ap.get())); - return nullptr; + return nullptr; } -const char * -SBCommandReturnObject::GetError () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +const char *SBCommandReturnObject::GetError() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (m_opaque_ap) - { - if (log) - log->Printf ("SBCommandReturnObject(%p)::GetError () => \"%s\"", - static_cast(m_opaque_ap.get()), - m_opaque_ap->GetErrorData()); + if (m_opaque_ap) { + if (log) + log->Printf("SBCommandReturnObject(%p)::GetError () => \"%s\"", + static_cast(m_opaque_ap.get()), + m_opaque_ap->GetErrorData()); - return m_opaque_ap->GetErrorData(); - } + return m_opaque_ap->GetErrorData(); + } - if (log) - log->Printf ("SBCommandReturnObject(%p)::GetError () => nullptr", - static_cast(m_opaque_ap.get())); + if (log) + log->Printf("SBCommandReturnObject(%p)::GetError () => nullptr", + static_cast(m_opaque_ap.get())); - return nullptr; + return nullptr; } -size_t -SBCommandReturnObject::GetOutputSize() -{ - return (m_opaque_ap ? strlen(m_opaque_ap->GetOutputData()) : 0); +size_t SBCommandReturnObject::GetOutputSize() { + return (m_opaque_ap ? strlen(m_opaque_ap->GetOutputData()) : 0); } -size_t -SBCommandReturnObject::GetErrorSize() -{ - return (m_opaque_ap ? strlen(m_opaque_ap->GetErrorData()) : 0); +size_t SBCommandReturnObject::GetErrorSize() { + return (m_opaque_ap ? strlen(m_opaque_ap->GetErrorData()) : 0); } -size_t -SBCommandReturnObject::PutOutput (FILE *fh) -{ - if (fh) - { - size_t num_bytes = GetOutputSize (); - if (num_bytes) - return ::fprintf (fh, "%s", GetOutput()); - } - return 0; +size_t SBCommandReturnObject::PutOutput(FILE *fh) { + if (fh) { + size_t num_bytes = GetOutputSize(); + if (num_bytes) + return ::fprintf(fh, "%s", GetOutput()); + } + return 0; } -size_t -SBCommandReturnObject::PutError (FILE *fh) -{ - if (fh) - { - size_t num_bytes = GetErrorSize (); - if (num_bytes) - return ::fprintf (fh, "%s", GetError()); - } - return 0; +size_t SBCommandReturnObject::PutError(FILE *fh) { + if (fh) { + size_t num_bytes = GetErrorSize(); + if (num_bytes) + return ::fprintf(fh, "%s", GetError()); + } + return 0; } -void -SBCommandReturnObject::Clear() -{ - if (m_opaque_ap) - m_opaque_ap->Clear(); +void SBCommandReturnObject::Clear() { + if (m_opaque_ap) + m_opaque_ap->Clear(); } -lldb::ReturnStatus -SBCommandReturnObject::GetStatus() -{ - return (m_opaque_ap ? m_opaque_ap->GetStatus() : lldb::eReturnStatusInvalid); +lldb::ReturnStatus SBCommandReturnObject::GetStatus() { + return (m_opaque_ap ? m_opaque_ap->GetStatus() : lldb::eReturnStatusInvalid); } -void -SBCommandReturnObject::SetStatus(lldb::ReturnStatus status) -{ - if (m_opaque_ap) - m_opaque_ap->SetStatus(status); +void SBCommandReturnObject::SetStatus(lldb::ReturnStatus status) { + if (m_opaque_ap) + m_opaque_ap->SetStatus(status); } -bool -SBCommandReturnObject::Succeeded() -{ - return (m_opaque_ap ? m_opaque_ap->Succeeded() : false); +bool SBCommandReturnObject::Succeeded() { + return (m_opaque_ap ? m_opaque_ap->Succeeded() : false); } -bool -SBCommandReturnObject::HasResult() -{ - return (m_opaque_ap ? m_opaque_ap->HasResult() : false); +bool SBCommandReturnObject::HasResult() { + return (m_opaque_ap ? m_opaque_ap->HasResult() : false); } -void -SBCommandReturnObject::AppendMessage (const char *message) -{ - if (m_opaque_ap) - m_opaque_ap->AppendMessage (message); +void SBCommandReturnObject::AppendMessage(const char *message) { + if (m_opaque_ap) + m_opaque_ap->AppendMessage(message); } -void -SBCommandReturnObject::AppendWarning (const char *message) -{ - if (m_opaque_ap) - m_opaque_ap->AppendWarning (message); +void SBCommandReturnObject::AppendWarning(const char *message) { + if (m_opaque_ap) + m_opaque_ap->AppendWarning(message); } -CommandReturnObject * -SBCommandReturnObject::operator ->() const -{ - return m_opaque_ap.get(); +CommandReturnObject *SBCommandReturnObject::operator->() const { + return m_opaque_ap.get(); } -CommandReturnObject * -SBCommandReturnObject::get() const -{ - return m_opaque_ap.get(); +CommandReturnObject *SBCommandReturnObject::get() const { + return m_opaque_ap.get(); } -CommandReturnObject & -SBCommandReturnObject::operator *() const -{ - assert(m_opaque_ap.get()); - return *(m_opaque_ap.get()); +CommandReturnObject &SBCommandReturnObject::operator*() const { + assert(m_opaque_ap.get()); + return *(m_opaque_ap.get()); } -CommandReturnObject & -SBCommandReturnObject::ref() const -{ - assert(m_opaque_ap.get()); - return *(m_opaque_ap.get()); +CommandReturnObject &SBCommandReturnObject::ref() const { + assert(m_opaque_ap.get()); + return *(m_opaque_ap.get()); } -void -SBCommandReturnObject::SetLLDBObjectPtr (CommandReturnObject *ptr) -{ - if (m_opaque_ap) - m_opaque_ap.reset (ptr); +void SBCommandReturnObject::SetLLDBObjectPtr(CommandReturnObject *ptr) { + if (m_opaque_ap) + m_opaque_ap.reset(ptr); } -bool -SBCommandReturnObject::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBCommandReturnObject::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - if (m_opaque_ap) - { - description.Printf ("Status: "); - lldb::ReturnStatus status = m_opaque_ap->GetStatus(); - if (status == lldb::eReturnStatusStarted) - strm.PutCString ("Started"); - else if (status == lldb::eReturnStatusInvalid) - strm.PutCString ("Invalid"); - else if (m_opaque_ap->Succeeded()) - strm.PutCString ("Success"); - else - strm.PutCString ("Fail"); + if (m_opaque_ap) { + description.Printf("Status: "); + lldb::ReturnStatus status = m_opaque_ap->GetStatus(); + if (status == lldb::eReturnStatusStarted) + strm.PutCString("Started"); + else if (status == lldb::eReturnStatusInvalid) + strm.PutCString("Invalid"); + else if (m_opaque_ap->Succeeded()) + strm.PutCString("Success"); + else + strm.PutCString("Fail"); - if (GetOutputSize() > 0) - strm.Printf ("\nOutput Message:\n%s", GetOutput()); + if (GetOutputSize() > 0) + strm.Printf("\nOutput Message:\n%s", GetOutput()); - if (GetErrorSize() > 0) - strm.Printf ("\nError Message:\n%s", GetError()); - } - else - strm.PutCString ("No value"); - - return true; -} - -void -SBCommandReturnObject::SetImmediateOutputFile(FILE *fh) -{ - SetImmediateOutputFile(fh, false); -} - -void -SBCommandReturnObject::SetImmediateErrorFile(FILE *fh) -{ - SetImmediateErrorFile(fh, false); -} - -void -SBCommandReturnObject::SetImmediateOutputFile(FILE *fh, bool transfer_ownership) -{ - if (m_opaque_ap) - m_opaque_ap->SetImmediateOutputFile(fh, transfer_ownership); -} - -void -SBCommandReturnObject::SetImmediateErrorFile(FILE *fh, bool transfer_ownership) -{ - if (m_opaque_ap) - m_opaque_ap->SetImmediateErrorFile(fh, transfer_ownership); -} - -void -SBCommandReturnObject::PutCString(const char* string, int len) -{ - if (m_opaque_ap) - { - if (len == 0 || string == nullptr || *string == 0) - { - return; - } - else if (len > 0) - { - std::string buffer(string, len); - m_opaque_ap->AppendMessage(buffer.c_str()); - } - else - m_opaque_ap->AppendMessage(string); - } -} - -const char * -SBCommandReturnObject::GetOutput (bool only_if_no_immediate) -{ - if (!m_opaque_ap) - return nullptr; - if (!only_if_no_immediate || m_opaque_ap->GetImmediateOutputStream().get() == nullptr) - return GetOutput(); - return nullptr; + if (GetErrorSize() > 0) + strm.Printf("\nError Message:\n%s", GetError()); + } else + strm.PutCString("No value"); + + return true; +} + +void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh) { + SetImmediateOutputFile(fh, false); } -const char * -SBCommandReturnObject::GetError (bool only_if_no_immediate) -{ - if (!m_opaque_ap) - return nullptr; - if (!only_if_no_immediate || m_opaque_ap->GetImmediateErrorStream().get() == nullptr) - return GetError(); +void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh) { + SetImmediateErrorFile(fh, false); +} + +void SBCommandReturnObject::SetImmediateOutputFile(FILE *fh, + bool transfer_ownership) { + if (m_opaque_ap) + m_opaque_ap->SetImmediateOutputFile(fh, transfer_ownership); +} + +void SBCommandReturnObject::SetImmediateErrorFile(FILE *fh, + bool transfer_ownership) { + if (m_opaque_ap) + m_opaque_ap->SetImmediateErrorFile(fh, transfer_ownership); +} + +void SBCommandReturnObject::PutCString(const char *string, int len) { + if (m_opaque_ap) { + if (len == 0 || string == nullptr || *string == 0) { + return; + } else if (len > 0) { + std::string buffer(string, len); + m_opaque_ap->AppendMessage(buffer.c_str()); + } else + m_opaque_ap->AppendMessage(string); + } +} + +const char *SBCommandReturnObject::GetOutput(bool only_if_no_immediate) { + if (!m_opaque_ap) return nullptr; + if (!only_if_no_immediate || + m_opaque_ap->GetImmediateOutputStream().get() == nullptr) + return GetOutput(); + return nullptr; } -size_t -SBCommandReturnObject::Printf(const char* format, ...) -{ - if (m_opaque_ap) - { - va_list args; - va_start (args, format); - size_t result = m_opaque_ap->GetOutputStream().PrintfVarArg(format, args); - va_end (args); - return result; - } - return 0; -} - -void -SBCommandReturnObject::SetError (lldb::SBError &error, const char *fallback_error_cstr) -{ - if (m_opaque_ap) - { - if (error.IsValid()) - m_opaque_ap->SetError(error.ref(), fallback_error_cstr); - else if (fallback_error_cstr) - m_opaque_ap->SetError(Error(), fallback_error_cstr); - } -} - -void -SBCommandReturnObject::SetError (const char *error_cstr) -{ - if (m_opaque_ap && error_cstr) - m_opaque_ap->SetError(error_cstr); +const char *SBCommandReturnObject::GetError(bool only_if_no_immediate) { + if (!m_opaque_ap) + return nullptr; + if (!only_if_no_immediate || + m_opaque_ap->GetImmediateErrorStream().get() == nullptr) + return GetError(); + return nullptr; +} + +size_t SBCommandReturnObject::Printf(const char *format, ...) { + if (m_opaque_ap) { + va_list args; + va_start(args, format); + size_t result = m_opaque_ap->GetOutputStream().PrintfVarArg(format, args); + va_end(args); + return result; + } + return 0; +} + +void SBCommandReturnObject::SetError(lldb::SBError &error, + const char *fallback_error_cstr) { + if (m_opaque_ap) { + if (error.IsValid()) + m_opaque_ap->SetError(error.ref(), fallback_error_cstr); + else if (fallback_error_cstr) + m_opaque_ap->SetError(Error(), fallback_error_cstr); + } +} + +void SBCommandReturnObject::SetError(const char *error_cstr) { + if (m_opaque_ap && error_cstr) + m_opaque_ap->SetError(error_cstr); } diff --git a/lldb/source/API/SBCommunication.cpp b/lldb/source/API/SBCommunication.cpp index 956b6cfcdd3..f80b114e222 100644 --- a/lldb/source/API/SBCommunication.cpp +++ b/lldb/source/API/SBCommunication.cpp @@ -16,270 +16,226 @@ using namespace lldb; using namespace lldb_private; +SBCommunication::SBCommunication() : m_opaque(NULL), m_opaque_owned(false) {} +SBCommunication::SBCommunication(const char *broadcaster_name) + : m_opaque(new Communication(broadcaster_name)), m_opaque_owned(true) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBCommunication::SBCommunication() : - m_opaque (NULL), - m_opaque_owned (false) -{ + if (log) + log->Printf("SBCommunication::SBCommunication (broadcaster_name=\"%s\") => " + "SBCommunication(%p)", + broadcaster_name, static_cast(m_opaque)); } -SBCommunication::SBCommunication(const char * broadcaster_name) : - m_opaque (new Communication (broadcaster_name)), - m_opaque_owned (true) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBCommunication::SBCommunication (broadcaster_name=\"%s\") => " - "SBCommunication(%p)", broadcaster_name, - static_cast(m_opaque)); +SBCommunication::~SBCommunication() { + if (m_opaque && m_opaque_owned) + delete m_opaque; + m_opaque = NULL; + m_opaque_owned = false; } -SBCommunication::~SBCommunication() -{ - if (m_opaque && m_opaque_owned) - delete m_opaque; - m_opaque = NULL; - m_opaque_owned = false; -} +bool SBCommunication::IsValid() const { return m_opaque != NULL; } -bool -SBCommunication::IsValid () const -{ - return m_opaque != NULL; +bool SBCommunication::GetCloseOnEOF() { + if (m_opaque) + return m_opaque->GetCloseOnEOF(); + return false; } -bool -SBCommunication::GetCloseOnEOF () -{ - if (m_opaque) - return m_opaque->GetCloseOnEOF (); - return false; +void SBCommunication::SetCloseOnEOF(bool b) { + if (m_opaque) + m_opaque->SetCloseOnEOF(b); } -void -SBCommunication::SetCloseOnEOF (bool b) -{ - if (m_opaque) - m_opaque->SetCloseOnEOF (b); +ConnectionStatus SBCommunication::Connect(const char *url) { + if (m_opaque) { + if (!m_opaque->HasConnection()) + m_opaque->SetConnection(Connection::CreateDefaultConnection(url)); + return m_opaque->Connect(url, NULL); + } + return eConnectionStatusNoConnection; } -ConnectionStatus -SBCommunication::Connect (const char *url) -{ - if (m_opaque) - { - if (!m_opaque->HasConnection ()) - m_opaque->SetConnection(Connection::CreateDefaultConnection(url)); - return m_opaque->Connect (url, NULL); - } - return eConnectionStatusNoConnection; -} +ConnectionStatus SBCommunication::AdoptFileDesriptor(int fd, bool owns_fd) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -ConnectionStatus -SBCommunication::AdoptFileDesriptor (int fd, bool owns_fd) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - ConnectionStatus status = eConnectionStatusNoConnection; - if (m_opaque) - { - if (m_opaque->HasConnection ()) - { - if (m_opaque->IsConnected()) - m_opaque->Disconnect(); - } - m_opaque->SetConnection (new ConnectionFileDescriptor (fd, owns_fd)); - if (m_opaque->IsConnected()) - status = eConnectionStatusSuccess; - else - status = eConnectionStatusLostConnection; + ConnectionStatus status = eConnectionStatusNoConnection; + if (m_opaque) { + if (m_opaque->HasConnection()) { + if (m_opaque->IsConnected()) + m_opaque->Disconnect(); } + m_opaque->SetConnection(new ConnectionFileDescriptor(fd, owns_fd)); + if (m_opaque->IsConnected()) + status = eConnectionStatusSuccess; + else + status = eConnectionStatusLostConnection; + } - if (log) - log->Printf ("SBCommunication(%p)::AdoptFileDescriptor (fd=%d, ownd_fd=%i) => %s", - static_cast(m_opaque), fd, owns_fd, - Communication::ConnectionStatusAsCString (status)); + if (log) + log->Printf( + "SBCommunication(%p)::AdoptFileDescriptor (fd=%d, ownd_fd=%i) => %s", + static_cast(m_opaque), fd, owns_fd, + Communication::ConnectionStatusAsCString(status)); - return status; + return status; } +ConnectionStatus SBCommunication::Disconnect() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -ConnectionStatus -SBCommunication::Disconnect () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - ConnectionStatus status= eConnectionStatusNoConnection; - if (m_opaque) - status = m_opaque->Disconnect (); - - if (log) - log->Printf ("SBCommunication(%p)::Disconnect () => %s", - static_cast(m_opaque), - Communication::ConnectionStatusAsCString (status)); + ConnectionStatus status = eConnectionStatusNoConnection; + if (m_opaque) + status = m_opaque->Disconnect(); - return status; + if (log) + log->Printf("SBCommunication(%p)::Disconnect () => %s", + static_cast(m_opaque), + Communication::ConnectionStatusAsCString(status)); + + return status; } -bool -SBCommunication::IsConnected () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool result = false; - if (m_opaque) - result = m_opaque->IsConnected (); +bool SBCommunication::IsConnected() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool result = false; + if (m_opaque) + result = m_opaque->IsConnected(); - if (log) - log->Printf ("SBCommunication(%p)::IsConnected () => %i", - static_cast(m_opaque), result); + if (log) + log->Printf("SBCommunication(%p)::IsConnected () => %i", + static_cast(m_opaque), result); - return false; + return false; } -size_t -SBCommunication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 ", timeout_usec=%u, &status)...", - static_cast(m_opaque), static_cast(dst), - static_cast(dst_len), timeout_usec); - size_t bytes_read = 0; - if (m_opaque) - bytes_read = m_opaque->Read (dst, dst_len, timeout_usec, status, NULL); - else - status = eConnectionStatusNoConnection; - - if (log) - log->Printf ("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 ", timeout_usec=%u, &status=%s) => %" PRIu64, - static_cast(m_opaque), static_cast(dst), - static_cast(dst_len), timeout_usec, - Communication::ConnectionStatusAsCString (status), - static_cast(bytes_read)); - return bytes_read; +size_t SBCommunication::Read(void *dst, size_t dst_len, uint32_t timeout_usec, + ConnectionStatus &status) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 + ", timeout_usec=%u, &status)...", + static_cast(m_opaque), static_cast(dst), + static_cast(dst_len), timeout_usec); + size_t bytes_read = 0; + if (m_opaque) + bytes_read = m_opaque->Read(dst, dst_len, timeout_usec, status, NULL); + else + status = eConnectionStatusNoConnection; + + if (log) + log->Printf("SBCommunication(%p)::Read (dst=%p, dst_len=%" PRIu64 + ", timeout_usec=%u, &status=%s) => %" PRIu64, + static_cast(m_opaque), static_cast(dst), + static_cast(dst_len), timeout_usec, + Communication::ConnectionStatusAsCString(status), + static_cast(bytes_read)); + return bytes_read; } +size_t SBCommunication::Write(const void *src, size_t src_len, + ConnectionStatus &status) { + size_t bytes_written = 0; + if (m_opaque) + bytes_written = m_opaque->Write(src, src_len, status, NULL); + else + status = eConnectionStatusNoConnection; -size_t -SBCommunication::Write (const void *src, size_t src_len, ConnectionStatus &status) -{ - size_t bytes_written = 0; - if (m_opaque) - bytes_written = m_opaque->Write (src, src_len, status, NULL); - else - status = eConnectionStatusNoConnection; - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommunication(%p)::Write (src=%p, src_len=%" PRIu64 ", &status=%s) => %" PRIu64, - static_cast(m_opaque), static_cast(src), - static_cast(src_len), - Communication::ConnectionStatusAsCString (status), - static_cast(bytes_written)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBCommunication(%p)::Write (src=%p, src_len=%" PRIu64 + ", &status=%s) => %" PRIu64, + static_cast(m_opaque), static_cast(src), + static_cast(src_len), + Communication::ConnectionStatusAsCString(status), + static_cast(bytes_written)); - return 0; + return 0; } -bool -SBCommunication::ReadThreadStart () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBCommunication::ReadThreadStart() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool success = false; - if (m_opaque) - success = m_opaque->StartReadThread (); + bool success = false; + if (m_opaque) + success = m_opaque->StartReadThread(); - if (log) - log->Printf ("SBCommunication(%p)::ReadThreadStart () => %i", - static_cast(m_opaque), success); + if (log) + log->Printf("SBCommunication(%p)::ReadThreadStart () => %i", + static_cast(m_opaque), success); - return success; + return success; } +bool SBCommunication::ReadThreadStop() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBCommunication(%p)::ReadThreadStop ()...", + static_cast(m_opaque)); -bool -SBCommunication::ReadThreadStop () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommunication(%p)::ReadThreadStop ()...", - static_cast(m_opaque)); + bool success = false; + if (m_opaque) + success = m_opaque->StopReadThread(); - bool success = false; - if (m_opaque) - success = m_opaque->StopReadThread (); + if (log) + log->Printf("SBCommunication(%p)::ReadThreadStop () => %i", + static_cast(m_opaque), success); - if (log) - log->Printf ("SBCommunication(%p)::ReadThreadStop () => %i", - static_cast(m_opaque), success); - - return success; + return success; } -bool -SBCommunication::ReadThreadIsRunning () -{ - bool result = false; - if (m_opaque) - result = m_opaque->ReadThreadIsRunning (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommunication(%p)::ReadThreadIsRunning () => %i", - static_cast(m_opaque), result); - return result; +bool SBCommunication::ReadThreadIsRunning() { + bool result = false; + if (m_opaque) + result = m_opaque->ReadThreadIsRunning(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBCommunication(%p)::ReadThreadIsRunning () => %i", + static_cast(m_opaque), result); + return result; } -bool -SBCommunication::SetReadThreadBytesReceivedCallback -( - ReadThreadBytesReceived callback, - void *callback_baton -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - bool result = false; - if (m_opaque) - { - m_opaque->SetReadThreadBytesReceivedCallback (callback, callback_baton); - result = true; - } +bool SBCommunication::SetReadThreadBytesReceivedCallback( + ReadThreadBytesReceived callback, void *callback_baton) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + bool result = false; + if (m_opaque) { + m_opaque->SetReadThreadBytesReceivedCallback(callback, callback_baton); + result = true; + } - if (log) - log->Printf ("SBCommunication(%p)::SetReadThreadBytesReceivedCallback (callback=%p, baton=%p) => %i", - static_cast(m_opaque), - reinterpret_cast(reinterpret_cast(callback)), - static_cast(callback_baton), result); + if (log) + log->Printf("SBCommunication(%p)::SetReadThreadBytesReceivedCallback " + "(callback=%p, baton=%p) => %i", + static_cast(m_opaque), + reinterpret_cast(reinterpret_cast(callback)), + static_cast(callback_baton), result); - return result; + return result; } -SBBroadcaster -SBCommunication::GetBroadcaster () -{ - SBBroadcaster broadcaster (m_opaque, false); +SBBroadcaster SBCommunication::GetBroadcaster() { + SBBroadcaster broadcaster(m_opaque, false); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBCommunication(%p)::GetBroadcaster () => SBBroadcaster (%p)", - static_cast(m_opaque), - static_cast(broadcaster.get())); + if (log) + log->Printf("SBCommunication(%p)::GetBroadcaster () => SBBroadcaster (%p)", + static_cast(m_opaque), + static_cast(broadcaster.get())); - return broadcaster; + return broadcaster; } -const char * -SBCommunication::GetBroadcasterClass () -{ - return Communication::GetStaticBroadcasterClass().AsCString(); +const char *SBCommunication::GetBroadcasterClass() { + return Communication::GetStaticBroadcasterClass().AsCString(); } // -//void -//SBCommunication::CreateIfNeeded () +// void +// SBCommunication::CreateIfNeeded () //{ // if (m_opaque == NULL) // { diff --git a/lldb/source/API/SBCompileUnit.cpp b/lldb/source/API/SBCompileUnit.cpp index 5d904ce5630..12aed5911de 100644 --- a/lldb/source/API/SBCompileUnit.cpp +++ b/lldb/source/API/SBCompileUnit.cpp @@ -21,275 +21,203 @@ using namespace lldb; using namespace lldb_private; +SBCompileUnit::SBCompileUnit() : m_opaque_ptr(NULL) {} -SBCompileUnit::SBCompileUnit () : - m_opaque_ptr (NULL) -{ -} - -SBCompileUnit::SBCompileUnit (lldb_private::CompileUnit *lldb_object_ptr) : - m_opaque_ptr (lldb_object_ptr) -{ -} +SBCompileUnit::SBCompileUnit(lldb_private::CompileUnit *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} -SBCompileUnit::SBCompileUnit(const SBCompileUnit &rhs) : - m_opaque_ptr (rhs.m_opaque_ptr) -{ -} +SBCompileUnit::SBCompileUnit(const SBCompileUnit &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) {} -const SBCompileUnit & -SBCompileUnit::operator = (const SBCompileUnit &rhs) -{ - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; +const SBCompileUnit &SBCompileUnit::operator=(const SBCompileUnit &rhs) { + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; } +SBCompileUnit::~SBCompileUnit() { m_opaque_ptr = NULL; } -SBCompileUnit::~SBCompileUnit () -{ - m_opaque_ptr = NULL; +SBFileSpec SBCompileUnit::GetFileSpec() const { + SBFileSpec file_spec; + if (m_opaque_ptr) + file_spec.SetFileSpec(*m_opaque_ptr); + return file_spec; } -SBFileSpec -SBCompileUnit::GetFileSpec () const -{ - SBFileSpec file_spec; - if (m_opaque_ptr) - file_spec.SetFileSpec(*m_opaque_ptr); - return file_spec; +uint32_t SBCompileUnit::GetNumLineEntries() const { + if (m_opaque_ptr) { + LineTable *line_table = m_opaque_ptr->GetLineTable(); + if (line_table) + return line_table->GetSize(); + } + return 0; } -uint32_t -SBCompileUnit::GetNumLineEntries () const -{ - if (m_opaque_ptr) - { - LineTable *line_table = m_opaque_ptr->GetLineTable (); - if (line_table) - return line_table->GetSize(); - } - return 0; -} +SBLineEntry SBCompileUnit::GetLineEntryAtIndex(uint32_t idx) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBLineEntry -SBCompileUnit::GetLineEntryAtIndex (uint32_t idx) const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBLineEntry sb_line_entry; - if (m_opaque_ptr) - { - LineTable *line_table = m_opaque_ptr->GetLineTable (); - if (line_table) - { - LineEntry line_entry; - if (line_table->GetLineEntryAtIndex(idx, line_entry)) - sb_line_entry.SetLineEntry(line_entry); - } + SBLineEntry sb_line_entry; + if (m_opaque_ptr) { + LineTable *line_table = m_opaque_ptr->GetLineTable(); + if (line_table) { + LineEntry line_entry; + if (line_table->GetLineEntryAtIndex(idx, line_entry)) + sb_line_entry.SetLineEntry(line_entry); } + } - if (log) - { - SBStream sstr; - sb_line_entry.GetDescription (sstr); - log->Printf ("SBCompileUnit(%p)::GetLineEntryAtIndex (idx=%u) => SBLineEntry(%p): '%s'", - static_cast(m_opaque_ptr), idx, - static_cast(sb_line_entry.get()), sstr.GetData()); - } + if (log) { + SBStream sstr; + sb_line_entry.GetDescription(sstr); + log->Printf("SBCompileUnit(%p)::GetLineEntryAtIndex (idx=%u) => " + "SBLineEntry(%p): '%s'", + static_cast(m_opaque_ptr), idx, + static_cast(sb_line_entry.get()), sstr.GetData()); + } - return sb_line_entry; + return sb_line_entry; } -uint32_t -SBCompileUnit::FindLineEntryIndex (uint32_t start_idx, uint32_t line, SBFileSpec *inline_file_spec) const -{ - const bool exact = true; - return FindLineEntryIndex (start_idx, line, inline_file_spec, exact); +uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, + SBFileSpec *inline_file_spec) const { + const bool exact = true; + return FindLineEntryIndex(start_idx, line, inline_file_spec, exact); } -uint32_t -SBCompileUnit::FindLineEntryIndex (uint32_t start_idx, uint32_t line, SBFileSpec *inline_file_spec, bool exact) const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t index = UINT32_MAX; - if (m_opaque_ptr) - { - FileSpec file_spec; - if (inline_file_spec && inline_file_spec->IsValid()) - file_spec = inline_file_spec->ref(); - else - file_spec = *m_opaque_ptr; - - index = m_opaque_ptr->FindLineEntry (start_idx, - line, - inline_file_spec ? inline_file_spec->get() : NULL, - exact, - NULL); - } +uint32_t SBCompileUnit::FindLineEntryIndex(uint32_t start_idx, uint32_t line, + SBFileSpec *inline_file_spec, + bool exact) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - if (index == UINT32_MAX) - { - log->Printf ("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, line=%u, SBFileSpec(%p)) => NOT FOUND", - static_cast(m_opaque_ptr), start_idx, line, - inline_file_spec - ? static_cast(inline_file_spec->get()) - : NULL); - } - else - { - log->Printf ("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, line=%u, SBFileSpec(%p)) => %u", - static_cast(m_opaque_ptr), start_idx, line, - inline_file_spec - ? static_cast(inline_file_spec->get()) - : NULL, - index); - } + uint32_t index = UINT32_MAX; + if (m_opaque_ptr) { + FileSpec file_spec; + if (inline_file_spec && inline_file_spec->IsValid()) + file_spec = inline_file_spec->ref(); + else + file_spec = *m_opaque_ptr; + + index = m_opaque_ptr->FindLineEntry( + start_idx, line, inline_file_spec ? inline_file_spec->get() : NULL, + exact, NULL); + } + + if (log) { + SBStream sstr; + if (index == UINT32_MAX) { + log->Printf("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, " + "line=%u, SBFileSpec(%p)) => NOT FOUND", + static_cast(m_opaque_ptr), start_idx, line, + inline_file_spec + ? static_cast(inline_file_spec->get()) + : NULL); + } else { + log->Printf("SBCompileUnit(%p)::FindLineEntryIndex (start_idx=%u, " + "line=%u, SBFileSpec(%p)) => %u", + static_cast(m_opaque_ptr), start_idx, line, + inline_file_spec + ? static_cast(inline_file_spec->get()) + : NULL, + index); } + } - return index; + return index; } -uint32_t -SBCompileUnit::GetNumSupportFiles () const -{ - if (m_opaque_ptr) - { - FileSpecList& support_files = m_opaque_ptr->GetSupportFiles (); - return support_files.GetSize(); - } - return 0; +uint32_t SBCompileUnit::GetNumSupportFiles() const { + if (m_opaque_ptr) { + FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); + return support_files.GetSize(); + } + return 0; } +lldb::SBTypeList SBCompileUnit::GetTypes(uint32_t type_mask) { + SBTypeList sb_type_list; - -lldb::SBTypeList -SBCompileUnit::GetTypes (uint32_t type_mask) -{ - SBTypeList sb_type_list; - - if (m_opaque_ptr) - { - ModuleSP module_sp (m_opaque_ptr->GetModule()); - if (module_sp) - { - SymbolVendor* vendor = module_sp->GetSymbolVendor(); - if (vendor) - { - TypeList type_list; - vendor->GetTypes (m_opaque_ptr, type_mask, type_list); - sb_type_list.m_opaque_ap->Append(type_list); - } - } + if (m_opaque_ptr) { + ModuleSP module_sp(m_opaque_ptr->GetModule()); + if (module_sp) { + SymbolVendor *vendor = module_sp->GetSymbolVendor(); + if (vendor) { + TypeList type_list; + vendor->GetTypes(m_opaque_ptr, type_mask, type_list); + sb_type_list.m_opaque_ap->Append(type_list); + } } - return sb_type_list; + } + return sb_type_list; } +SBFileSpec SBCompileUnit::GetSupportFileAtIndex(uint32_t idx) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBFileSpec sb_file_spec; + if (m_opaque_ptr) { + FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); + FileSpec file_spec = support_files.GetFileSpecAtIndex(idx); + sb_file_spec.SetFileSpec(file_spec); + } + if (log) { + SBStream sstr; + sb_file_spec.GetDescription(sstr); + log->Printf("SBCompileUnit(%p)::GetGetFileSpecAtIndex (idx=%u) => " + "SBFileSpec(%p): '%s'", + static_cast(m_opaque_ptr), idx, + static_cast(sb_file_spec.get()), sstr.GetData()); + } -SBFileSpec -SBCompileUnit::GetSupportFileAtIndex (uint32_t idx) const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBFileSpec sb_file_spec; - if (m_opaque_ptr) - { - FileSpecList &support_files = m_opaque_ptr->GetSupportFiles (); - FileSpec file_spec = support_files.GetFileSpecAtIndex(idx); - sb_file_spec.SetFileSpec(file_spec); - } - - if (log) - { - SBStream sstr; - sb_file_spec.GetDescription (sstr); - log->Printf ("SBCompileUnit(%p)::GetGetFileSpecAtIndex (idx=%u) => SBFileSpec(%p): '%s'", - static_cast(m_opaque_ptr), idx, - static_cast(sb_file_spec.get()), - sstr.GetData()); - } - - return sb_file_spec; + return sb_file_spec; } -uint32_t -SBCompileUnit::FindSupportFileIndex (uint32_t start_idx, const SBFileSpec &sb_file, bool full) -{ - if (m_opaque_ptr) - { - FileSpecList &support_files = m_opaque_ptr->GetSupportFiles (); - return support_files.FindFileIndex(start_idx, sb_file.ref(), full); - } - return 0; +uint32_t SBCompileUnit::FindSupportFileIndex(uint32_t start_idx, + const SBFileSpec &sb_file, + bool full) { + if (m_opaque_ptr) { + FileSpecList &support_files = m_opaque_ptr->GetSupportFiles(); + return support_files.FindFileIndex(start_idx, sb_file.ref(), full); + } + return 0; } -lldb::LanguageType -SBCompileUnit::GetLanguage () -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetLanguage(); - return lldb::eLanguageTypeUnknown; +lldb::LanguageType SBCompileUnit::GetLanguage() { + if (m_opaque_ptr) + return m_opaque_ptr->GetLanguage(); + return lldb::eLanguageTypeUnknown; } -bool -SBCompileUnit::IsValid () const -{ - return m_opaque_ptr != NULL; -} +bool SBCompileUnit::IsValid() const { return m_opaque_ptr != NULL; } -bool -SBCompileUnit::operator == (const SBCompileUnit &rhs) const -{ - return m_opaque_ptr == rhs.m_opaque_ptr; +bool SBCompileUnit::operator==(const SBCompileUnit &rhs) const { + return m_opaque_ptr == rhs.m_opaque_ptr; } -bool -SBCompileUnit::operator != (const SBCompileUnit &rhs) const -{ - return m_opaque_ptr != rhs.m_opaque_ptr; +bool SBCompileUnit::operator!=(const SBCompileUnit &rhs) const { + return m_opaque_ptr != rhs.m_opaque_ptr; } -const lldb_private::CompileUnit * -SBCompileUnit::operator->() const -{ - return m_opaque_ptr; +const lldb_private::CompileUnit *SBCompileUnit::operator->() const { + return m_opaque_ptr; } -const lldb_private::CompileUnit & -SBCompileUnit::operator*() const -{ - return *m_opaque_ptr; +const lldb_private::CompileUnit &SBCompileUnit::operator*() const { + return *m_opaque_ptr; } -lldb_private::CompileUnit * -SBCompileUnit::get () -{ - return m_opaque_ptr; -} +lldb_private::CompileUnit *SBCompileUnit::get() { return m_opaque_ptr; } -void -SBCompileUnit::reset (lldb_private::CompileUnit *lldb_object_ptr) -{ - m_opaque_ptr = lldb_object_ptr; +void SBCompileUnit::reset(lldb_private::CompileUnit *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; } - -bool -SBCompileUnit::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBCompileUnit::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - if (m_opaque_ptr) - { - m_opaque_ptr->Dump (&strm, false); - } - else - strm.PutCString ("No value"); - - return true; + if (m_opaque_ptr) { + m_opaque_ptr->Dump(&strm, false); + } else + strm.PutCString("No value"); + + return true; } diff --git a/lldb/source/API/SBData.cpp b/lldb/source/API/SBData.cpp index a58585295a2..d905d3f272f 100644 --- a/lldb/source/API/SBData.cpp +++ b/lldb/source/API/SBData.cpp @@ -18,788 +18,682 @@ #include "lldb/Core/Log.h" #include "lldb/Core/Stream.h" - using namespace lldb; using namespace lldb_private; -SBData::SBData () : - m_opaque_sp(new DataExtractor()) -{ -} +SBData::SBData() : m_opaque_sp(new DataExtractor()) {} -SBData::SBData (const lldb::DataExtractorSP& data_sp) : - m_opaque_sp (data_sp) -{ -} +SBData::SBData(const lldb::DataExtractorSP &data_sp) : m_opaque_sp(data_sp) {} -SBData::SBData(const SBData &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBData::SBData(const SBData &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} -const SBData & -SBData::operator = (const SBData &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBData &SBData::operator=(const SBData &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -SBData::~SBData () -{ -} +SBData::~SBData() {} -void -SBData::SetOpaque (const lldb::DataExtractorSP &data_sp) -{ - m_opaque_sp = data_sp; +void SBData::SetOpaque(const lldb::DataExtractorSP &data_sp) { + m_opaque_sp = data_sp; } -lldb_private::DataExtractor * -SBData::get() const -{ - return m_opaque_sp.get(); +lldb_private::DataExtractor *SBData::get() const { return m_opaque_sp.get(); } + +lldb_private::DataExtractor *SBData::operator->() const { + return m_opaque_sp.operator->(); } -lldb_private::DataExtractor * -SBData::operator->() const -{ - return m_opaque_sp.operator->(); -} +lldb::DataExtractorSP &SBData::operator*() { return m_opaque_sp; } -lldb::DataExtractorSP & -SBData::operator*() -{ - return m_opaque_sp; -} +const lldb::DataExtractorSP &SBData::operator*() const { return m_opaque_sp; } + +bool SBData::IsValid() { return m_opaque_sp.get() != NULL; } + +uint8_t SBData::GetAddressByteSize() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + uint8_t value = 0; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetAddressByteSize(); + if (log) + log->Printf("SBData::GetAddressByteSize () => " + "(%i)", + value); + return value; +} + +void SBData::SetAddressByteSize(uint8_t addr_byte_size) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_opaque_sp.get()) + m_opaque_sp->SetAddressByteSize(addr_byte_size); + if (log) + log->Printf("SBData::SetAddressByteSize (%i)", addr_byte_size); +} + +void SBData::Clear() { + if (m_opaque_sp.get()) + m_opaque_sp->Clear(); +} + +size_t SBData::GetByteSize() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + size_t value = 0; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetByteSize(); + if (log) + log->Printf("SBData::GetByteSize () => " + "( %" PRIu64 " )", + (uint64_t)value); + return value; +} + +lldb::ByteOrder SBData::GetByteOrder() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::ByteOrder value = eByteOrderInvalid; + if (m_opaque_sp.get()) + value = m_opaque_sp->GetByteOrder(); + if (log) + log->Printf("SBData::GetByteOrder () => " + "(%i)", + value); + return value; +} + +void SBData::SetByteOrder(lldb::ByteOrder endian) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_opaque_sp.get()) + m_opaque_sp->SetByteOrder(endian); + if (log) + log->Printf("SBData::GetByteOrder (%i)", endian); +} + +float SBData::GetFloat(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + float value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetFloat(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetFloat (error=%p,offset=%" PRIu64 ") => (%f)", + static_cast(error.get()), offset, value); + return value; +} + +double SBData::GetDouble(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + double value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetDouble(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetDouble (error=%p,offset=%" PRIu64 ") => " + "(%f)", + static_cast(error.get()), offset, value); + return value; +} + +long double SBData::GetLongDouble(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + long double value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetLongDouble(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetLongDouble (error=%p,offset=%" PRIu64 ") => " + "(%Lf)", + static_cast(error.get()), offset, value); + return value; +} + +lldb::addr_t SBData::GetAddress(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::addr_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetAddress(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetAddress (error=%p,offset=%" PRIu64 ") => " + "(%p)", + static_cast(error.get()), offset, + reinterpret_cast(value)); + return value; +} + +uint8_t SBData::GetUnsignedInt8(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + uint8_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU8(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetUnsignedInt8 (error=%p,offset=%" PRIu64 ") => " + "(%c)", + static_cast(error.get()), offset, value); + return value; +} + +uint16_t SBData::GetUnsignedInt16(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + uint16_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU16(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetUnsignedInt16 (error=%p,offset=%" PRIu64 ") => " + "(%hd)", + static_cast(error.get()), offset, value); + return value; +} + +uint32_t SBData::GetUnsignedInt32(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + uint32_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU32(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetUnsignedInt32 (error=%p,offset=%" PRIu64 ") => " + "(%d)", + static_cast(error.get()), offset, value); + return value; +} + +uint64_t SBData::GetUnsignedInt64(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + uint64_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetU64(&offset); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetUnsignedInt64 (error=%p,offset=%" PRIu64 ") => " + "(%" PRId64 ")", + static_cast(error.get()), offset, value); + return value; +} + +int8_t SBData::GetSignedInt8(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + int8_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int8_t)m_opaque_sp->GetMaxS64(&offset, 1); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetSignedInt8 (error=%p,offset=%" PRIu64 ") => " + "(%c)", + static_cast(error.get()), offset, value); + return value; +} + +int16_t SBData::GetSignedInt16(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + int16_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int16_t)m_opaque_sp->GetMaxS64(&offset, 2); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetSignedInt16 (error=%p,offset=%" PRIu64 ") => " + "(%hd)", + static_cast(error.get()), offset, value); + return value; +} + +int32_t SBData::GetSignedInt32(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + int32_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int32_t)m_opaque_sp->GetMaxS64(&offset, 4); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetSignedInt32 (error=%p,offset=%" PRIu64 ") => " + "(%d)", + static_cast(error.get()), offset, value); + return value; +} + +int64_t SBData::GetSignedInt64(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + int64_t value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = (int64_t)m_opaque_sp->GetMaxS64(&offset, 8); + if (offset == old_offset) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetSignedInt64 (error=%p,offset=%" PRIu64 ") => " + "(%" PRId64 ")", + static_cast(error.get()), offset, value); + return value; +} + +const char *SBData::GetString(lldb::SBError &error, lldb::offset_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *value = 0; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + value = m_opaque_sp->GetCStr(&offset); + if (offset == old_offset || (value == NULL)) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::GetString (error=%p,offset=%" PRIu64 ") => (%p)", + static_cast(error.get()), offset, + static_cast(value)); + return value; +} + +bool SBData::GetDescription(lldb::SBStream &description, + lldb::addr_t base_addr) { + Stream &strm = description.ref(); + + if (m_opaque_sp) { + m_opaque_sp->Dump(&strm, 0, lldb::eFormatBytesWithASCII, 1, + m_opaque_sp->GetByteSize(), 16, base_addr, 0, 0); + } else + strm.PutCString("No value"); + + return true; +} + +size_t SBData::ReadRawData(lldb::SBError &error, lldb::offset_t offset, + void *buf, size_t size) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + void *ok = NULL; + if (!m_opaque_sp.get()) { + error.SetErrorString("no value to read from"); + } else { + uint32_t old_offset = offset; + ok = m_opaque_sp->GetU8(&offset, buf, size); + if ((offset == old_offset) || (ok == NULL)) + error.SetErrorString("unable to read data"); + } + if (log) + log->Printf("SBData::ReadRawData (error=%p,offset=%" PRIu64 + ",buf=%p,size=%" PRIu64 ") => " + "(%p)", + static_cast(error.get()), offset, + static_cast(buf), static_cast(size), + static_cast(ok)); + return ok ? size : 0; +} + +void SBData::SetData(lldb::SBError &error, const void *buf, size_t size, + lldb::ByteOrder endian, uint8_t addr_size) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!m_opaque_sp.get()) + m_opaque_sp.reset(new DataExtractor(buf, size, endian, addr_size)); + else + m_opaque_sp->SetData(buf, size, endian); + if (log) + log->Printf("SBData::SetData (error=%p,buf=%p,size=%" PRIu64 + ",endian=%d,addr_size=%c) => " + "(%p)", + static_cast(error.get()), + static_cast(buf), static_cast(size), + endian, addr_size, static_cast(m_opaque_sp.get())); +} + +bool SBData::Append(const SBData &rhs) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool value = false; + if (m_opaque_sp.get() && rhs.m_opaque_sp.get()) + value = m_opaque_sp.get()->Append(*rhs.m_opaque_sp); + if (log) + log->Printf("SBData::Append (rhs=%p) => (%s)", + static_cast(rhs.get()), value ? "true" : "false"); + return value; +} + +lldb::SBData SBData::CreateDataFromCString(lldb::ByteOrder endian, + uint32_t addr_byte_size, + const char *data) { + if (!data || !data[0]) + return SBData(); + + uint32_t data_len = strlen(data); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); -const lldb::DataExtractorSP & -SBData::operator*() const -{ - return m_opaque_sp; + SBData ret(data_sp); + + return ret; } -bool -SBData::IsValid() -{ - return m_opaque_sp.get() != NULL; +lldb::SBData SBData::CreateDataFromUInt64Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + uint64_t *array, + size_t array_len) { + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(uint64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; } -uint8_t -SBData::GetAddressByteSize () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - uint8_t value = 0; - if (m_opaque_sp.get()) - value = m_opaque_sp->GetAddressByteSize(); - if (log) - log->Printf ("SBData::GetAddressByteSize () => " - "(%i)", value); - return value; +lldb::SBData SBData::CreateDataFromUInt32Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + uint32_t *array, + size_t array_len) { + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(uint32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; } -void -SBData::SetAddressByteSize (uint8_t addr_byte_size) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_opaque_sp.get()) - m_opaque_sp->SetAddressByteSize(addr_byte_size); - if (log) - log->Printf ("SBData::SetAddressByteSize (%i)", addr_byte_size); +lldb::SBData SBData::CreateDataFromSInt64Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + int64_t *array, + size_t array_len) { + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(int64_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; } -void -SBData::Clear () -{ - if (m_opaque_sp.get()) - m_opaque_sp->Clear(); +lldb::SBData SBData::CreateDataFromSInt32Array(lldb::ByteOrder endian, + uint32_t addr_byte_size, + int32_t *array, + size_t array_len) { + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(int32_t); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; } -size_t -SBData::GetByteSize () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - size_t value = 0; - if (m_opaque_sp.get()) - value = m_opaque_sp->GetByteSize(); - if (log) - log->Printf ("SBData::GetByteSize () => " - "( %" PRIu64 " )", (uint64_t)value); - return value; -} - -lldb::ByteOrder -SBData::GetByteOrder () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::ByteOrder value = eByteOrderInvalid; - if (m_opaque_sp.get()) - value = m_opaque_sp->GetByteOrder(); - if (log) - log->Printf ("SBData::GetByteOrder () => " - "(%i)", value); - return value; +lldb::SBData SBData::CreateDataFromDoubleArray(lldb::ByteOrder endian, + uint32_t addr_byte_size, + double *array, + size_t array_len) { + if (!array || array_len == 0) + return SBData(); + + size_t data_len = array_len * sizeof(double); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + lldb::DataExtractorSP data_sp( + new DataExtractor(buffer_sp, endian, addr_byte_size)); + + SBData ret(data_sp); + + return ret; } -void -SBData::SetByteOrder (lldb::ByteOrder endian) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_opaque_sp.get()) - m_opaque_sp->SetByteOrder(endian); - if (log) - log->Printf ("SBData::GetByteOrder (%i)", endian); -} - - -float -SBData::GetFloat (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - float value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetFloat(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetFloat (error=%p,offset=%" PRIu64 ") => (%f)", - static_cast(error.get()), offset, value); - return value; -} - -double -SBData::GetDouble (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - double value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetDouble(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetDouble (error=%p,offset=%" PRIu64 ") => " - "(%f)", static_cast(error.get()), offset, value); - return value; -} - -long double -SBData::GetLongDouble (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - long double value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetLongDouble(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetLongDouble (error=%p,offset=%" PRIu64 ") => " - "(%Lf)", static_cast(error.get()), offset, value); - return value; -} - -lldb::addr_t -SBData::GetAddress (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::addr_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetAddress(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetAddress (error=%p,offset=%" PRIu64 ") => " - "(%p)", static_cast(error.get()), offset, - reinterpret_cast(value)); - return value; -} - -uint8_t -SBData::GetUnsignedInt8 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - uint8_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetU8(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetUnsignedInt8 (error=%p,offset=%" PRIu64 ") => " - "(%c)", static_cast(error.get()), offset, value); - return value; -} - -uint16_t -SBData::GetUnsignedInt16 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - uint16_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetU16(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetUnsignedInt16 (error=%p,offset=%" PRIu64 ") => " - "(%hd)", static_cast(error.get()), offset, value); - return value; -} - -uint32_t -SBData::GetUnsignedInt32 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - uint32_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetU32(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetUnsignedInt32 (error=%p,offset=%" PRIu64 ") => " - "(%d)", static_cast(error.get()), offset, value); - return value; -} - -uint64_t -SBData::GetUnsignedInt64 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - uint64_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetU64(&offset); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetUnsignedInt64 (error=%p,offset=%" PRIu64 ") => " - "(%" PRId64 ")", static_cast(error.get()), offset, - value); - return value; -} - -int8_t -SBData::GetSignedInt8 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - int8_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = (int8_t)m_opaque_sp->GetMaxS64(&offset, 1); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetSignedInt8 (error=%p,offset=%" PRIu64 ") => " - "(%c)", static_cast(error.get()), offset, value); - return value; -} - -int16_t -SBData::GetSignedInt16 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - int16_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = (int16_t)m_opaque_sp->GetMaxS64(&offset, 2); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetSignedInt16 (error=%p,offset=%" PRIu64 ") => " - "(%hd)", static_cast(error.get()), offset, value); - return value; -} - -int32_t -SBData::GetSignedInt32 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - int32_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = (int32_t)m_opaque_sp->GetMaxS64(&offset, 4); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetSignedInt32 (error=%p,offset=%" PRIu64 ") => " - "(%d)", static_cast(error.get()), offset, value); - return value; -} - -int64_t -SBData::GetSignedInt64 (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - int64_t value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = (int64_t)m_opaque_sp->GetMaxS64(&offset, 8); - if (offset == old_offset) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetSignedInt64 (error=%p,offset=%" PRIu64 ") => " - "(%" PRId64 ")", static_cast(error.get()), offset, - value); - return value; -} - -const char* -SBData::GetString (lldb::SBError& error, lldb::offset_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char* value = 0; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - value = m_opaque_sp->GetCStr(&offset); - if (offset == old_offset || (value == NULL)) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf ("SBData::GetString (error=%p,offset=%" PRIu64 ") => (%p)", - static_cast(error.get()), offset, - static_cast(value)); - return value; -} - -bool -SBData::GetDescription (lldb::SBStream &description, lldb::addr_t base_addr) -{ - Stream &strm = description.ref(); - - if (m_opaque_sp) - { - m_opaque_sp->Dump (&strm, - 0, - lldb::eFormatBytesWithASCII, - 1, - m_opaque_sp->GetByteSize(), - 16, - base_addr, - 0, - 0); - } - else - strm.PutCString ("No value"); - - return true; -} - -size_t -SBData::ReadRawData (lldb::SBError& error, - lldb::offset_t offset, - void *buf, - size_t size) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - void* ok = NULL; - if (!m_opaque_sp.get()) - { - error.SetErrorString("no value to read from"); - } - else - { - uint32_t old_offset = offset; - ok = m_opaque_sp->GetU8(&offset, buf, size); - if ((offset == old_offset) || (ok == NULL)) - error.SetErrorString("unable to read data"); - } - if (log) - log->Printf("SBData::ReadRawData (error=%p,offset=%" PRIu64 ",buf=%p,size=%" PRIu64 ") => " - "(%p)", static_cast(error.get()), offset, - static_cast(buf), static_cast(size), - static_cast(ok)); - return ok ? size : 0; -} - -void -SBData::SetData (lldb::SBError& error, - const void *buf, - size_t size, - lldb::ByteOrder endian, - uint8_t addr_size) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buf, size, endian, addr_size)); - else - m_opaque_sp->SetData(buf, size, endian); - if (log) - log->Printf("SBData::SetData (error=%p,buf=%p,size=%" PRIu64 ",endian=%d,addr_size=%c) => " - "(%p)", static_cast(error.get()), - static_cast(buf), static_cast(size), - endian, addr_size, static_cast(m_opaque_sp.get())); -} - -bool -SBData::Append (const SBData& rhs) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool value = false; - if (m_opaque_sp.get() && rhs.m_opaque_sp.get()) - value = m_opaque_sp.get()->Append(*rhs.m_opaque_sp); - if (log) - log->Printf ("SBData::Append (rhs=%p) => (%s)", - static_cast(rhs.get()), value ? "true" : "false"); - return value; -} - -lldb::SBData -SBData::CreateDataFromCString (lldb::ByteOrder endian, uint32_t addr_byte_size, const char* data) -{ - if (!data || !data[0]) - return SBData(); - - uint32_t data_len = strlen(data); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -lldb::SBData -SBData::CreateDataFromUInt64Array (lldb::ByteOrder endian, uint32_t addr_byte_size, uint64_t* array, size_t array_len) -{ - if (!array || array_len == 0) - return SBData(); - - size_t data_len = array_len * sizeof(uint64_t); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -lldb::SBData -SBData::CreateDataFromUInt32Array (lldb::ByteOrder endian, uint32_t addr_byte_size, uint32_t* array, size_t array_len) -{ - if (!array || array_len == 0) - return SBData(); - - size_t data_len = array_len * sizeof(uint32_t); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -lldb::SBData -SBData::CreateDataFromSInt64Array (lldb::ByteOrder endian, uint32_t addr_byte_size, int64_t* array, size_t array_len) -{ - if (!array || array_len == 0) - return SBData(); - - size_t data_len = array_len * sizeof(int64_t); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -lldb::SBData -SBData::CreateDataFromSInt32Array (lldb::ByteOrder endian, uint32_t addr_byte_size, int32_t* array, size_t array_len) -{ - if (!array || array_len == 0) - return SBData(); - - size_t data_len = array_len * sizeof(int32_t); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -lldb::SBData -SBData::CreateDataFromDoubleArray (lldb::ByteOrder endian, uint32_t addr_byte_size, double* array, size_t array_len) -{ - if (!array || array_len == 0) - return SBData(); - - size_t data_len = array_len * sizeof(double); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - lldb::DataExtractorSP data_sp(new DataExtractor(buffer_sp, endian, addr_byte_size)); - - SBData ret(data_sp); - - return ret; -} - -bool -SBData::SetDataFromCString (const char* data) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (!data) - { - if (log) - log->Printf ("SBData::SetDataFromCString (data=%p) => false", - static_cast(data)); - return false; - } - - size_t data_len = strlen(data); - - lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); - - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromCString(const char *data) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!data) { if (log) - log->Printf ("SBData::SetDataFromCString (data=%p) => true", - static_cast(data)); + log->Printf("SBData::SetDataFromCString (data=%p) => false", + static_cast(data)); + return false; + } - return true; -} + size_t data_len = strlen(data); -bool -SBData::SetDataFromUInt64Array (uint64_t* array, size_t array_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + lldb::DataBufferSP buffer_sp(new DataBufferHeap(data, data_len)); - if (!array || array_len == 0) - { - if (log) - log->Printf("SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 ") => " - "false", static_cast(array), - static_cast(array_len)); - return false; - } + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); - size_t data_len = array_len * sizeof(uint64_t); + if (log) + log->Printf("SBData::SetDataFromCString (data=%p) => true", + static_cast(data)); - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + return true; +} - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromUInt64Array(uint64_t *array, size_t array_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!array || array_len == 0) { if (log) - log->Printf("SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 ") => " - "true", static_cast(array), - static_cast(array_len)); + log->Printf( + "SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 + ") => " + "false", + static_cast(array), static_cast(array_len)); + return false; + } - return true; -} + size_t data_len = array_len * sizeof(uint64_t); -bool -SBData::SetDataFromUInt32Array (uint32_t* array, size_t array_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - if (!array || array_len == 0) - { - if (log) - log->Printf("SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 ") => " - "false", static_cast(array), - static_cast(array_len)); - return false; - } + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); - size_t data_len = array_len * sizeof(uint32_t); + if (log) + log->Printf("SBData::SetDataFromUInt64Array (array=%p, array_len = %" PRIu64 + ") => " + "true", + static_cast(array), static_cast(array_len)); - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + return true; +} - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromUInt32Array(uint32_t *array, size_t array_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!array || array_len == 0) { if (log) - log->Printf("SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 ") => " - "true", static_cast(array), - static_cast(array_len)); + log->Printf( + "SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 + ") => " + "false", + static_cast(array), static_cast(array_len)); + return false; + } - return true; -} + size_t data_len = array_len * sizeof(uint32_t); -bool -SBData::SetDataFromSInt64Array (int64_t* array, size_t array_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - if (!array || array_len == 0) - { - if (log) - log->Printf("SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 ") => " - "false", static_cast(array), - static_cast(array_len)); - return false; - } + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); - size_t data_len = array_len * sizeof(int64_t); + if (log) + log->Printf("SBData::SetDataFromUInt32Array (array=%p, array_len = %" PRIu64 + ") => " + "true", + static_cast(array), static_cast(array_len)); - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + return true; +} - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromSInt64Array(int64_t *array, size_t array_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!array || array_len == 0) { if (log) - log->Printf("SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 ") => " - "true", static_cast(array), - static_cast(array_len)); + log->Printf( + "SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 + ") => " + "false", + static_cast(array), static_cast(array_len)); + return false; + } - return true; -} + size_t data_len = array_len * sizeof(int64_t); -bool -SBData::SetDataFromSInt32Array (int32_t* array, size_t array_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - if (!array || array_len == 0) - { - if (log) - log->Printf("SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 ") => " - "false", static_cast(array), - static_cast(array_len)); - return false; - } + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); - size_t data_len = array_len * sizeof(int32_t); + if (log) + log->Printf("SBData::SetDataFromSInt64Array (array=%p, array_len = %" PRIu64 + ") => " + "true", + static_cast(array), static_cast(array_len)); - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + return true; +} - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromSInt32Array(int32_t *array, size_t array_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!array || array_len == 0) { if (log) - log->Printf("SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 ") => " - "true", static_cast(array), - static_cast(array_len)); + log->Printf( + "SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 + ") => " + "false", + static_cast(array), static_cast(array_len)); + return false; + } - return true; -} + size_t data_len = array_len * sizeof(int32_t); -bool -SBData::SetDataFromDoubleArray (double* array, size_t array_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); - if (!array || array_len == 0) - { - if (log) - log->Printf("SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 ") => " - "false", static_cast(array), - static_cast(array_len)); - return false; - } + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); - size_t data_len = array_len * sizeof(double); + if (log) + log->Printf("SBData::SetDataFromSInt32Array (array=%p, array_len = %" PRIu64 + ") => " + "true", + static_cast(array), static_cast(array_len)); - lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + return true; +} - if (!m_opaque_sp.get()) - m_opaque_sp.reset(new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); - else - m_opaque_sp->SetData(buffer_sp); +bool SBData::SetDataFromDoubleArray(double *array, size_t array_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!array || array_len == 0) { if (log) - log->Printf("SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 ") => " - "true", static_cast(array), - static_cast(array_len)); - - return true; + log->Printf( + "SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 + ") => " + "false", + static_cast(array), static_cast(array_len)); + return false; + } + + size_t data_len = array_len * sizeof(double); + + lldb::DataBufferSP buffer_sp(new DataBufferHeap(array, data_len)); + + if (!m_opaque_sp.get()) + m_opaque_sp.reset( + new DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize())); + else + m_opaque_sp->SetData(buffer_sp); + + if (log) + log->Printf("SBData::SetDataFromDoubleArray (array=%p, array_len = %" PRIu64 + ") => " + "true", + static_cast(array), static_cast(array_len)); + + return true; } diff --git a/lldb/source/API/SBDebugger.cpp b/lldb/source/API/SBDebugger.cpp index 9a047085260..f7811f2e7b5 100644 --- a/lldb/source/API/SBDebugger.cpp +++ b/lldb/source/API/SBDebugger.cpp @@ -15,14 +15,13 @@ #include "lldb/lldb-private.h" -#include "lldb/API/SystemInitializerFull.h" -#include "lldb/API/SBListener.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBCommandInterpreter.h" #include "lldb/API/SBCommandReturnObject.h" #include "lldb/API/SBError.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBFrame.h" +#include "lldb/API/SBListener.h" #include "lldb/API/SBProcess.h" #include "lldb/API/SBSourceManager.h" #include "lldb/API/SBStream.h" @@ -30,11 +29,12 @@ #include "lldb/API/SBTarget.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBTypeCategory.h" -#include "lldb/API/SBTypeFormat.h" #include "lldb/API/SBTypeFilter.h" +#include "lldb/API/SBTypeFormat.h" #include "lldb/API/SBTypeNameSpecifier.h" #include "lldb/API/SBTypeSummary.h" #include "lldb/API/SBTypeSynthetic.h" +#include "lldb/API/SystemInitializerFull.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/State.h" @@ -48,1335 +48,1090 @@ #include "lldb/Target/TargetList.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/DynamicLibrary.h" +#include "llvm/Support/ManagedStatic.h" using namespace lldb; using namespace lldb_private; -static llvm::sys::DynamicLibrary -LoadPlugin (const lldb::DebuggerSP &debugger_sp, const FileSpec& spec, Error& error) -{ - llvm::sys::DynamicLibrary dynlib = llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str()); - if (dynlib.isValid()) - { - typedef bool (*LLDBCommandPluginInit) (lldb::SBDebugger& debugger); - - lldb::SBDebugger debugger_sb(debugger_sp); - // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger) function. - // TODO: mangle this differently for your system - on OSX, the first underscore needs to be removed and the second one stays - LLDBCommandPluginInit init_func = (LLDBCommandPluginInit)dynlib.getAddressOfSymbol("_ZN4lldb16PluginInitializeENS_10SBDebuggerE"); - if (init_func) - { - if (init_func(debugger_sb)) - return dynlib; - else - error.SetErrorString("plug-in refused to load (lldb::PluginInitialize(lldb::SBDebugger) returned false)"); - } - else - { - error.SetErrorString("plug-in is missing the required initialization: lldb::PluginInitialize(lldb::SBDebugger)"); - } +static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp, + const FileSpec &spec, + Error &error) { + llvm::sys::DynamicLibrary dynlib = + llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str()); + if (dynlib.isValid()) { + typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger); + + lldb::SBDebugger debugger_sb(debugger_sp); + // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger) + // function. + // TODO: mangle this differently for your system - on OSX, the first + // underscore needs to be removed and the second one stays + LLDBCommandPluginInit init_func = + (LLDBCommandPluginInit)dynlib.getAddressOfSymbol( + "_ZN4lldb16PluginInitializeENS_10SBDebuggerE"); + if (init_func) { + if (init_func(debugger_sb)) + return dynlib; + else + error.SetErrorString("plug-in refused to load " + "(lldb::PluginInitialize(lldb::SBDebugger) " + "returned false)"); + } else { + error.SetErrorString("plug-in is missing the required initialization: " + "lldb::PluginInitialize(lldb::SBDebugger)"); } + } else { + if (spec.Exists()) + error.SetErrorString("this file does not represent a loadable dylib"); else - { - if (spec.Exists()) - error.SetErrorString("this file does not represent a loadable dylib"); - else - error.SetErrorString("no such file"); - } - return llvm::sys::DynamicLibrary(); + error.SetErrorString("no such file"); + } + return llvm::sys::DynamicLibrary(); } static llvm::ManagedStatic g_debugger_lifetime; -SBError -SBInputReader::Initialize(lldb::SBDebugger &sb_debugger, - unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction, char const *, - unsigned long), - void *, lldb::InputReaderGranularity, char const *, char const *, bool) -{ - return SBError(); +SBError SBInputReader::Initialize( + lldb::SBDebugger &sb_debugger, + unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction, + char const *, unsigned long), + void *, lldb::InputReaderGranularity, char const *, char const *, bool) { + return SBError(); } -void -SBInputReader::SetIsDone(bool) -{ -} +void SBInputReader::SetIsDone(bool) {} -bool -SBInputReader::IsActive() const -{ - return false; -} +bool SBInputReader::IsActive() const { return false; } SBDebugger::SBDebugger() = default; -SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp) : - m_opaque_sp(debugger_sp) -{ -} +SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp) + : m_opaque_sp(debugger_sp) {} -SBDebugger::SBDebugger(const SBDebugger &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} SBDebugger::~SBDebugger() = default; -SBDebugger & -SBDebugger::operator = (const SBDebugger &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -void -SBDebugger::Initialize () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBDebugger::Initialize() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger::Initialize ()"); + if (log) + log->Printf("SBDebugger::Initialize ()"); - g_debugger_lifetime->Initialize(llvm::make_unique(), LoadPlugin); + g_debugger_lifetime->Initialize(llvm::make_unique(), + LoadPlugin); } -void -SBDebugger::Terminate () -{ - g_debugger_lifetime->Terminate(); -} +void SBDebugger::Terminate() { g_debugger_lifetime->Terminate(); } -void -SBDebugger::Clear () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBDebugger::Clear() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::Clear ()", - static_cast(m_opaque_sp.get())); + if (log) + log->Printf("SBDebugger(%p)::Clear ()", + static_cast(m_opaque_sp.get())); - if (m_opaque_sp) - m_opaque_sp->ClearIOHandlers (); + if (m_opaque_sp) + m_opaque_sp->ClearIOHandlers(); - m_opaque_sp.reset(); + m_opaque_sp.reset(); } -SBDebugger -SBDebugger::Create() -{ - return SBDebugger::Create(false, nullptr, nullptr); +SBDebugger SBDebugger::Create() { + return SBDebugger::Create(false, nullptr, nullptr); } -SBDebugger -SBDebugger::Create(bool source_init_files) -{ - return SBDebugger::Create (source_init_files, nullptr, nullptr); +SBDebugger SBDebugger::Create(bool source_init_files) { + return SBDebugger::Create(source_init_files, nullptr, nullptr); } -SBDebugger -SBDebugger::Create(bool source_init_files, lldb::LogOutputCallback callback, void *baton) +SBDebugger SBDebugger::Create(bool source_init_files, + lldb::LogOutputCallback callback, void *baton) { - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBDebugger debugger; - - // Currently we have issues if this function is called simultaneously on two different - // threads. The issues mainly revolve around the fact that the lldb_private::FormatManager - // uses global collections and having two threads parsing the .lldbinit files can cause - // mayhem. So to get around this for now we need to use a mutex to prevent bad things - // from happening. - static std::recursive_mutex g_mutex; - std::lock_guard guard(g_mutex); - - debugger.reset(Debugger::CreateInstance(callback, baton)); - - if (log) - { - SBStream sstr; - debugger.GetDescription (sstr); - log->Printf ("SBDebugger::Create () => SBDebugger(%p): %s", - static_cast(debugger.m_opaque_sp.get()), - sstr.GetData()); - } + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBCommandInterpreter interp = debugger.GetCommandInterpreter(); - if (source_init_files) - { - interp.get()->SkipLLDBInitFiles(false); - interp.get()->SkipAppInitFiles (false); - SBCommandReturnObject result; - interp.SourceInitFileInHomeDirectory(result); - } - else - { - interp.get()->SkipLLDBInitFiles(true); - interp.get()->SkipAppInitFiles (true); - } - return debugger; -} + SBDebugger debugger; -void -SBDebugger::Destroy (SBDebugger &debugger) -{ - Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - { - SBStream sstr; - debugger.GetDescription (sstr); - log->Printf ("SBDebugger::Destroy () => SBDebugger(%p): %s", - static_cast(debugger.m_opaque_sp.get()), - sstr.GetData()); - } + // Currently we have issues if this function is called simultaneously on two + // different + // threads. The issues mainly revolve around the fact that the + // lldb_private::FormatManager + // uses global collections and having two threads parsing the .lldbinit files + // can cause + // mayhem. So to get around this for now we need to use a mutex to prevent bad + // things + // from happening. + static std::recursive_mutex g_mutex; + std::lock_guard guard(g_mutex); - Debugger::Destroy (debugger.m_opaque_sp); + debugger.reset(Debugger::CreateInstance(callback, baton)); - if (debugger.m_opaque_sp.get() != nullptr) - debugger.m_opaque_sp.reset(); + if (log) { + SBStream sstr; + debugger.GetDescription(sstr); + log->Printf("SBDebugger::Create () => SBDebugger(%p): %s", + static_cast(debugger.m_opaque_sp.get()), + sstr.GetData()); + } + + SBCommandInterpreter interp = debugger.GetCommandInterpreter(); + if (source_init_files) { + interp.get()->SkipLLDBInitFiles(false); + interp.get()->SkipAppInitFiles(false); + SBCommandReturnObject result; + interp.SourceInitFileInHomeDirectory(result); + } else { + interp.get()->SkipLLDBInitFiles(true); + interp.get()->SkipAppInitFiles(true); + } + return debugger; } -void -SBDebugger::MemoryPressureDetected () -{ - // Since this function can be call asynchronously, we allow it to be - // non-mandatory. We have seen deadlocks with this function when called - // so we need to safeguard against this until we can determine what is - // causing the deadlocks. - Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - const bool mandatory = false; - if (log) - { - log->Printf ("SBDebugger::MemoryPressureDetected (), mandatory = %d", mandatory); - } - - ModuleList::RemoveOrphanSharedModules(mandatory); +void SBDebugger::Destroy(SBDebugger &debugger) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) { + SBStream sstr; + debugger.GetDescription(sstr); + log->Printf("SBDebugger::Destroy () => SBDebugger(%p): %s", + static_cast(debugger.m_opaque_sp.get()), + sstr.GetData()); + } + + Debugger::Destroy(debugger.m_opaque_sp); + + if (debugger.m_opaque_sp.get() != nullptr) + debugger.m_opaque_sp.reset(); } -bool -SBDebugger::IsValid() const -{ - return m_opaque_sp.get() != nullptr; +void SBDebugger::MemoryPressureDetected() { + // Since this function can be call asynchronously, we allow it to be + // non-mandatory. We have seen deadlocks with this function when called + // so we need to safeguard against this until we can determine what is + // causing the deadlocks. + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + const bool mandatory = false; + if (log) { + log->Printf("SBDebugger::MemoryPressureDetected (), mandatory = %d", + mandatory); + } + + ModuleList::RemoveOrphanSharedModules(mandatory); } -void -SBDebugger::SetAsync (bool b) -{ - if (m_opaque_sp) - m_opaque_sp->SetAsyncExecution(b); +bool SBDebugger::IsValid() const { return m_opaque_sp.get() != nullptr; } + +void SBDebugger::SetAsync(bool b) { + if (m_opaque_sp) + m_opaque_sp->SetAsyncExecution(b); } -bool -SBDebugger::GetAsync() -{ - return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false); +bool SBDebugger::GetAsync() { + return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false); } -void -SBDebugger::SkipLLDBInitFiles (bool b) -{ - if (m_opaque_sp) - m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles (b); +void SBDebugger::SkipLLDBInitFiles(bool b) { + if (m_opaque_sp) + m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b); } -void -SBDebugger::SkipAppInitFiles (bool b) -{ - if (m_opaque_sp) - m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles (b); +void SBDebugger::SkipAppInitFiles(bool b) { + if (m_opaque_sp) + m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b); } -// Shouldn't really be settable after initialization as this could cause lots of problems; don't want users +// Shouldn't really be settable after initialization as this could cause lots of +// problems; don't want users // trying to switch modes in the middle of a debugging session. -void -SBDebugger::SetInputFileHandle (FILE *fh, bool transfer_ownership) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::SetInputFileHandle (fh=%p, transfer_ownership=%i)", - static_cast(m_opaque_sp.get()), - static_cast(fh), transfer_ownership); + if (log) + log->Printf( + "SBDebugger(%p)::SetInputFileHandle (fh=%p, transfer_ownership=%i)", + static_cast(m_opaque_sp.get()), static_cast(fh), + transfer_ownership); - if (m_opaque_sp) - m_opaque_sp->SetInputFileHandle (fh, transfer_ownership); + if (m_opaque_sp) + m_opaque_sp->SetInputFileHandle(fh, transfer_ownership); } -void -SBDebugger::SetOutputFileHandle (FILE *fh, bool transfer_ownership) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - +void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::SetOutputFileHandle (fh=%p, transfer_ownership=%i)", - static_cast(m_opaque_sp.get()), - static_cast(fh), transfer_ownership); + if (log) + log->Printf( + "SBDebugger(%p)::SetOutputFileHandle (fh=%p, transfer_ownership=%i)", + static_cast(m_opaque_sp.get()), static_cast(fh), + transfer_ownership); - if (m_opaque_sp) - m_opaque_sp->SetOutputFileHandle (fh, transfer_ownership); + if (m_opaque_sp) + m_opaque_sp->SetOutputFileHandle(fh, transfer_ownership); } -void -SBDebugger::SetErrorFileHandle (FILE *fh, bool transfer_ownership) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - +void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::SetErrorFileHandle (fh=%p, transfer_ownership=%i)", - static_cast(m_opaque_sp.get()), - static_cast(fh), transfer_ownership); + if (log) + log->Printf( + "SBDebugger(%p)::SetErrorFileHandle (fh=%p, transfer_ownership=%i)", + static_cast(m_opaque_sp.get()), static_cast(fh), + transfer_ownership); - if (m_opaque_sp) - m_opaque_sp->SetErrorFileHandle (fh, transfer_ownership); + if (m_opaque_sp) + m_opaque_sp->SetErrorFileHandle(fh, transfer_ownership); } -FILE * -SBDebugger::GetInputFileHandle () -{ - if (m_opaque_sp) - { - StreamFileSP stream_file_sp (m_opaque_sp->GetInputFile()); - if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); - } - return nullptr; +FILE *SBDebugger::GetInputFileHandle() { + if (m_opaque_sp) { + StreamFileSP stream_file_sp(m_opaque_sp->GetInputFile()); + if (stream_file_sp) + return stream_file_sp->GetFile().GetStream(); + } + return nullptr; } -FILE * -SBDebugger::GetOutputFileHandle () -{ - if (m_opaque_sp) - { - StreamFileSP stream_file_sp (m_opaque_sp->GetOutputFile()); - if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); - } - return nullptr; +FILE *SBDebugger::GetOutputFileHandle() { + if (m_opaque_sp) { + StreamFileSP stream_file_sp(m_opaque_sp->GetOutputFile()); + if (stream_file_sp) + return stream_file_sp->GetFile().GetStream(); + } + return nullptr; } -FILE * -SBDebugger::GetErrorFileHandle () -{ - if (m_opaque_sp) - { - StreamFileSP stream_file_sp(m_opaque_sp->GetErrorFile()); - if (stream_file_sp) - return stream_file_sp->GetFile().GetStream(); - } - return nullptr; +FILE *SBDebugger::GetErrorFileHandle() { + if (m_opaque_sp) { + StreamFileSP stream_file_sp(m_opaque_sp->GetErrorFile()); + if (stream_file_sp) + return stream_file_sp->GetFile().GetStream(); + } + return nullptr; } -void -SBDebugger::SaveInputTerminalState() -{ - if (m_opaque_sp) - m_opaque_sp->SaveInputTerminalState(); +void SBDebugger::SaveInputTerminalState() { + if (m_opaque_sp) + m_opaque_sp->SaveInputTerminalState(); } -void -SBDebugger::RestoreInputTerminalState() -{ - if (m_opaque_sp) - m_opaque_sp->RestoreInputTerminalState(); - +void SBDebugger::RestoreInputTerminalState() { + if (m_opaque_sp) + m_opaque_sp->RestoreInputTerminalState(); } -SBCommandInterpreter -SBDebugger::GetCommandInterpreter () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBCommandInterpreter SBDebugger::GetCommandInterpreter() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBCommandInterpreter sb_interpreter; - if (m_opaque_sp) - sb_interpreter.reset (&m_opaque_sp->GetCommandInterpreter()); + SBCommandInterpreter sb_interpreter; + if (m_opaque_sp) + sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter()); - if (log) - log->Printf ("SBDebugger(%p)::GetCommandInterpreter () => SBCommandInterpreter(%p)", - static_cast(m_opaque_sp.get()), - static_cast(sb_interpreter.get())); + if (log) + log->Printf( + "SBDebugger(%p)::GetCommandInterpreter () => SBCommandInterpreter(%p)", + static_cast(m_opaque_sp.get()), + static_cast(sb_interpreter.get())); - return sb_interpreter; + return sb_interpreter; } -void -SBDebugger::HandleCommand (const char *command) -{ - if (m_opaque_sp) - { - TargetSP target_sp (m_opaque_sp->GetSelectedTarget()); - std::unique_lock lock; - if (target_sp) - lock = std::unique_lock(target_sp->GetAPIMutex()); - - SBCommandInterpreter sb_interpreter(GetCommandInterpreter ()); - SBCommandReturnObject result; - - sb_interpreter.HandleCommand (command, result, false); - - if (GetErrorFileHandle() != nullptr) - result.PutError (GetErrorFileHandle()); - if (GetOutputFileHandle() != nullptr) - result.PutOutput (GetOutputFileHandle()); - - if (!m_opaque_sp->GetAsyncExecution()) - { - SBProcess process(GetCommandInterpreter().GetProcess ()); - ProcessSP process_sp (process.GetSP()); - if (process_sp) - { - EventSP event_sp; - ListenerSP lldb_listener_sp = m_opaque_sp->GetListener(); - while (lldb_listener_sp->GetNextEventForBroadcaster (process_sp.get(), event_sp)) - { - SBEvent event(event_sp); - HandleProcessEvent (process, event, GetOutputFileHandle(), GetErrorFileHandle()); - } - } - } - } -} +void SBDebugger::HandleCommand(const char *command) { + if (m_opaque_sp) { + TargetSP target_sp(m_opaque_sp->GetSelectedTarget()); + std::unique_lock lock; + if (target_sp) + lock = std::unique_lock(target_sp->GetAPIMutex()); -SBListener -SBDebugger::GetListener () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + SBCommandInterpreter sb_interpreter(GetCommandInterpreter()); + SBCommandReturnObject result; - SBListener sb_listener; - if (m_opaque_sp) - sb_listener.reset(m_opaque_sp->GetListener()); + sb_interpreter.HandleCommand(command, result, false); - if (log) - log->Printf ("SBDebugger(%p)::GetListener () => SBListener(%p)", - static_cast(m_opaque_sp.get()), - static_cast(sb_listener.get())); + if (GetErrorFileHandle() != nullptr) + result.PutError(GetErrorFileHandle()); + if (GetOutputFileHandle() != nullptr) + result.PutOutput(GetOutputFileHandle()); - return sb_listener; + if (!m_opaque_sp->GetAsyncExecution()) { + SBProcess process(GetCommandInterpreter().GetProcess()); + ProcessSP process_sp(process.GetSP()); + if (process_sp) { + EventSP event_sp; + ListenerSP lldb_listener_sp = m_opaque_sp->GetListener(); + while (lldb_listener_sp->GetNextEventForBroadcaster(process_sp.get(), + event_sp)) { + SBEvent event(event_sp); + HandleProcessEvent(process, event, GetOutputFileHandle(), + GetErrorFileHandle()); + } + } + } + } } -void -SBDebugger::HandleProcessEvent (const SBProcess &process, const SBEvent &event, FILE *out, FILE *err) -{ - if (!process.IsValid()) - return; - - TargetSP target_sp (process.GetTarget().GetSP()); - if (!target_sp) - return; +SBListener SBDebugger::GetListener() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - const uint32_t event_type = event.GetType(); - char stdio_buffer[1024]; - size_t len; + SBListener sb_listener; + if (m_opaque_sp) + sb_listener.reset(m_opaque_sp->GetListener()); - std::lock_guard guard(target_sp->GetAPIMutex()); + if (log) + log->Printf("SBDebugger(%p)::GetListener () => SBListener(%p)", + static_cast(m_opaque_sp.get()), + static_cast(sb_listener.get())); - if (event_type & (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) - { - // Drain stdout when we stop just in case we have any bytes - while ((len = process.GetSTDOUT (stdio_buffer, sizeof (stdio_buffer))) > 0) - if (out != nullptr) - ::fwrite (stdio_buffer, 1, len, out); - } - - if (event_type & (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) - { - // Drain stderr when we stop just in case we have any bytes - while ((len = process.GetSTDERR (stdio_buffer, sizeof (stdio_buffer))) > 0) - if (err != nullptr) - ::fwrite (stdio_buffer, 1, len, err); - } - - if (event_type & Process::eBroadcastBitStateChanged) - { - StateType event_state = SBProcess::GetStateFromEvent (event); - - if (event_state == eStateInvalid) - return; - - bool is_stopped = StateIsStoppedState (event_state); - if (!is_stopped) - process.ReportEventState (event, out); - } + return sb_listener; } -SBSourceManager -SBDebugger::GetSourceManager () -{ - SBSourceManager sb_source_manager (*this); - return sb_source_manager; -} +void SBDebugger::HandleProcessEvent(const SBProcess &process, + const SBEvent &event, FILE *out, + FILE *err) { + if (!process.IsValid()) + return; -bool -SBDebugger::GetDefaultArchitecture (char *arch_name, size_t arch_name_len) -{ - if (arch_name && arch_name_len) - { - ArchSpec default_arch = Target::GetDefaultArchitecture (); - - if (default_arch.IsValid()) - { - const std::string &triple_str = default_arch.GetTriple().str(); - if (!triple_str.empty()) - ::snprintf (arch_name, arch_name_len, "%s", triple_str.c_str()); - else - ::snprintf (arch_name, arch_name_len, "%s", default_arch.GetArchitectureName()); - return true; - } - } - if (arch_name && arch_name_len) - arch_name[0] = '\0'; - return false; -} + TargetSP target_sp(process.GetTarget().GetSP()); + if (!target_sp) + return; -bool -SBDebugger::SetDefaultArchitecture (const char *arch_name) -{ - if (arch_name) - { - ArchSpec arch (arch_name); - if (arch.IsValid()) - { - Target::SetDefaultArchitecture (arch); - return true; - } - } - return false; -} + const uint32_t event_type = event.GetType(); + char stdio_buffer[1024]; + size_t len; -ScriptLanguage -SBDebugger::GetScriptingLanguage(const char *script_language_name) -{ - return Args::StringToScriptLanguage(script_language_name, - eScriptLanguageDefault, - nullptr); -} + std::lock_guard guard(target_sp->GetAPIMutex()); -const char * -SBDebugger::GetVersionString () -{ - return lldb_private::GetVersion(); -} + if (event_type & + (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) { + // Drain stdout when we stop just in case we have any bytes + while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0) + if (out != nullptr) + ::fwrite(stdio_buffer, 1, len, out); + } -const char * -SBDebugger::StateAsCString (StateType state) -{ - return lldb_private::StateAsCString (state); -} + if (event_type & + (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) { + // Drain stderr when we stop just in case we have any bytes + while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0) + if (err != nullptr) + ::fwrite(stdio_buffer, 1, len, err); + } -bool -SBDebugger::StateIsRunningState (StateType state) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + if (event_type & Process::eBroadcastBitStateChanged) { + StateType event_state = SBProcess::GetStateFromEvent(event); - const bool result = lldb_private::StateIsRunningState (state); - if (log) - log->Printf ("SBDebugger::StateIsRunningState (state=%s) => %i", - StateAsCString (state), result); + if (event_state == eStateInvalid) + return; - return result; + bool is_stopped = StateIsStoppedState(event_state); + if (!is_stopped) + process.ReportEventState(event, out); + } } -bool -SBDebugger::StateIsStoppedState (StateType state) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - const bool result = lldb_private::StateIsStoppedState (state, false); - if (log) - log->Printf ("SBDebugger::StateIsStoppedState (state=%s) => %i", - StateAsCString (state), result); - - return result; +SBSourceManager SBDebugger::GetSourceManager() { + SBSourceManager sb_source_manager(*this); + return sb_source_manager; } -lldb::SBTarget -SBDebugger::CreateTarget (const char *filename, - const char *target_triple, - const char *platform_name, - bool add_dependent_modules, - lldb::SBError& sb_error) -{ - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - sb_error.Clear(); - OptionGroupPlatform platform_options (false); - platform_options.SetPlatformName (platform_name); - - sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget (*m_opaque_sp, - filename, - target_triple, - add_dependent_modules, - &platform_options, - target_sp); - - if (sb_error.Success()) - sb_target.SetSP (target_sp); +bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) { + if (arch_name && arch_name_len) { + ArchSpec default_arch = Target::GetDefaultArchitecture(); + + if (default_arch.IsValid()) { + const std::string &triple_str = default_arch.GetTriple().str(); + if (!triple_str.empty()) + ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str()); + else + ::snprintf(arch_name, arch_name_len, "%s", + default_arch.GetArchitectureName()); + return true; } - else - { - sb_error.SetErrorString("invalid debugger"); + } + if (arch_name && arch_name_len) + arch_name[0] = '\0'; + return false; +} + +bool SBDebugger::SetDefaultArchitecture(const char *arch_name) { + if (arch_name) { + ArchSpec arch(arch_name); + if (arch.IsValid()) { + Target::SetDefaultArchitecture(arch); + return true; } - - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, platform_name=%s, add_dependent_modules=%u, error=%s) => SBTarget(%p)", - static_cast(m_opaque_sp.get()), filename, - target_triple, platform_name, add_dependent_modules, - sb_error.GetCString(), static_cast(target_sp.get())); - - return sb_target; + } + return false; } -SBTarget -SBDebugger::CreateTargetWithFileAndTargetTriple (const char *filename, - const char *target_triple) -{ - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - const bool add_dependent_modules = true; - Error error (m_opaque_sp->GetTargetList().CreateTarget(*m_opaque_sp, - filename, - target_triple, - add_dependent_modules, - nullptr, - target_sp)); - sb_target.SetSP (target_sp); - } - - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::CreateTargetWithFileAndTargetTriple (filename=\"%s\", triple=%s) => SBTarget(%p)", - static_cast(m_opaque_sp.get()), filename, - target_triple, static_cast(target_sp.get())); - - return sb_target; +ScriptLanguage +SBDebugger::GetScriptingLanguage(const char *script_language_name) { + return Args::StringToScriptLanguage(script_language_name, + eScriptLanguageDefault, nullptr); } -SBTarget -SBDebugger::CreateTargetWithFileAndArch (const char *filename, const char *arch_cstr) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - Error error; - const bool add_dependent_modules = true; - - error = m_opaque_sp->GetTargetList().CreateTarget(*m_opaque_sp, - filename, - arch_cstr, - add_dependent_modules, - nullptr, - target_sp); - - if (error.Success()) - { - m_opaque_sp->GetTargetList().SetSelectedTarget (target_sp.get()); - sb_target.SetSP (target_sp); - } - } - - if (log) - log->Printf ("SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", arch=%s) => SBTarget(%p)", - static_cast(m_opaque_sp.get()), filename, arch_cstr, - static_cast(target_sp.get())); - - return sb_target; +const char *SBDebugger::GetVersionString() { + return lldb_private::GetVersion(); } -SBTarget -SBDebugger::CreateTarget (const char *filename) -{ - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - Error error; - const bool add_dependent_modules = true; - error = m_opaque_sp->GetTargetList().CreateTarget(*m_opaque_sp, - filename, - nullptr, - add_dependent_modules, - nullptr, - target_sp); - - if (error.Success()) - { - m_opaque_sp->GetTargetList().SetSelectedTarget (target_sp.get()); - sb_target.SetSP (target_sp); - } - } - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)", - static_cast(m_opaque_sp.get()), filename, - static_cast(target_sp.get())); - return sb_target; +const char *SBDebugger::StateAsCString(StateType state) { + return lldb_private::StateAsCString(state); } -bool -SBDebugger::DeleteTarget (lldb::SBTarget &target) -{ - bool result = false; - if (m_opaque_sp) - { - TargetSP target_sp(target.GetSP()); - if (target_sp) - { - // No need to lock, the target list is thread safe - result = m_opaque_sp->GetTargetList().DeleteTarget (target_sp); - target_sp->Destroy(); - target.Clear(); - const bool mandatory = true; - ModuleList::RemoveOrphanSharedModules(mandatory); - } - } +bool SBDebugger::StateIsRunningState(StateType state) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i", - static_cast(m_opaque_sp.get()), - static_cast(target.m_opaque_sp.get()), result); + const bool result = lldb_private::StateIsRunningState(state); + if (log) + log->Printf("SBDebugger::StateIsRunningState (state=%s) => %i", + StateAsCString(state), result); - return result; + return result; } -SBTarget -SBDebugger::GetTargetAtIndex (uint32_t idx) -{ - SBTarget sb_target; - if (m_opaque_sp) - { - // No need to lock, the target list is thread safe - sb_target.SetSP (m_opaque_sp->GetTargetList().GetTargetAtIndex (idx)); - } - return sb_target; -} +bool SBDebugger::StateIsStoppedState(StateType state) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -uint32_t -SBDebugger::GetIndexOfTarget (lldb::SBTarget target) -{ + const bool result = lldb_private::StateIsStoppedState(state, false); + if (log) + log->Printf("SBDebugger::StateIsStoppedState (state=%s) => %i", + StateAsCString(state), result); - lldb::TargetSP target_sp = target.GetSP(); - if (!target_sp) - return UINT32_MAX; + return result; +} - if (!m_opaque_sp) - return UINT32_MAX; +lldb::SBTarget SBDebugger::CreateTarget(const char *filename, + const char *target_triple, + const char *platform_name, + bool add_dependent_modules, + lldb::SBError &sb_error) { + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + sb_error.Clear(); + OptionGroupPlatform platform_options(false); + platform_options.SetPlatformName(platform_name); - return m_opaque_sp->GetTargetList().GetIndexOfTarget (target.GetSP()); -} + sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, target_triple, add_dependent_modules, + &platform_options, target_sp); -SBTarget -SBDebugger::FindTargetWithProcessID (lldb::pid_t pid) -{ - SBTarget sb_target; - if (m_opaque_sp) - { - // No need to lock, the target list is thread safe - sb_target.SetSP (m_opaque_sp->GetTargetList().FindTargetWithProcessID (pid)); - } - return sb_target; -} + if (sb_error.Success()) + sb_target.SetSP(target_sp); + } else { + sb_error.SetErrorString("invalid debugger"); + } -SBTarget -SBDebugger::FindTargetWithFileAndArch (const char *filename, const char *arch_name) -{ - SBTarget sb_target; - if (m_opaque_sp && filename && filename[0]) - { - // No need to lock, the target list is thread safe - ArchSpec arch (arch_name, m_opaque_sp->GetPlatformList().GetSelectedPlatform().get()); - TargetSP target_sp (m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture(FileSpec(filename, false), arch_name ? &arch : nullptr)); - sb_target.SetSP (target_sp); - } - return sb_target; + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, " + "platform_name=%s, add_dependent_modules=%u, error=%s) => " + "SBTarget(%p)", + static_cast(m_opaque_sp.get()), filename, target_triple, + platform_name, add_dependent_modules, sb_error.GetCString(), + static_cast(target_sp.get())); + + return sb_target; } SBTarget -SBDebugger::FindTargetWithLLDBProcess (const ProcessSP &process_sp) -{ - SBTarget sb_target; - if (m_opaque_sp) - { - // No need to lock, the target list is thread safe - sb_target.SetSP (m_opaque_sp->GetTargetList().FindTargetWithProcess (process_sp.get())); - } - return sb_target; -} +SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename, + const char *target_triple) { + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + const bool add_dependent_modules = true; + Error error(m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, target_triple, add_dependent_modules, nullptr, + target_sp)); + sb_target.SetSP(target_sp); + } + + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBDebugger(%p)::CreateTargetWithFileAndTargetTriple " + "(filename=\"%s\", triple=%s) => SBTarget(%p)", + static_cast(m_opaque_sp.get()), filename, target_triple, + static_cast(target_sp.get())); + + return sb_target; +} + +SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename, + const char *arch_cstr) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + Error error; + const bool add_dependent_modules = true; -uint32_t -SBDebugger::GetNumTargets () -{ - if (m_opaque_sp) - { - // No need to lock, the target list is thread safe - return m_opaque_sp->GetTargetList().GetNumTargets (); - } - return 0; -} + error = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, arch_cstr, add_dependent_modules, nullptr, + target_sp); -SBTarget -SBDebugger::GetSelectedTarget () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - // No need to lock, the target list is thread safe - target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget (); - sb_target.SetSP (target_sp); + if (error.Success()) { + m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); + sb_target.SetSP(target_sp); } + } - if (log) - { - SBStream sstr; - sb_target.GetDescription (sstr, eDescriptionLevelBrief); - log->Printf ("SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s", - static_cast(m_opaque_sp.get()), - static_cast(target_sp.get()), sstr.GetData()); - } + if (log) + log->Printf("SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", " + "arch=%s) => SBTarget(%p)", + static_cast(m_opaque_sp.get()), filename, arch_cstr, + static_cast(target_sp.get())); - return sb_target; + return sb_target; } -void -SBDebugger::SetSelectedTarget (SBTarget &sb_target) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - TargetSP target_sp (sb_target.GetSP()); - if (m_opaque_sp) - { - m_opaque_sp->GetTargetList().SetSelectedTarget (target_sp.get()); +SBTarget SBDebugger::CreateTarget(const char *filename) { + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + Error error; + const bool add_dependent_modules = true; + error = m_opaque_sp->GetTargetList().CreateTarget( + *m_opaque_sp, filename, nullptr, add_dependent_modules, nullptr, + target_sp); + + if (error.Success()) { + m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); + sb_target.SetSP(target_sp); } - if (log) - { - SBStream sstr; - sb_target.GetDescription (sstr, eDescriptionLevelBrief); - log->Printf ("SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s", - static_cast(m_opaque_sp.get()), - static_cast(target_sp.get()), sstr.GetData()); + } + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)", + static_cast(m_opaque_sp.get()), filename, + static_cast(target_sp.get())); + return sb_target; +} + +bool SBDebugger::DeleteTarget(lldb::SBTarget &target) { + bool result = false; + if (m_opaque_sp) { + TargetSP target_sp(target.GetSP()); + if (target_sp) { + // No need to lock, the target list is thread safe + result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp); + target_sp->Destroy(); + target.Clear(); + const bool mandatory = true; + ModuleList::RemoveOrphanSharedModules(mandatory); } -} - -SBPlatform -SBDebugger::GetSelectedPlatform() -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + } - SBPlatform sb_platform; - DebuggerSP debugger_sp(m_opaque_sp); - if (debugger_sp) - { - sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform()); - } - if (log) - log->Printf ("SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s", - static_cast(m_opaque_sp.get()), - static_cast(sb_platform.GetSP().get()), - sb_platform.GetName()); - return sb_platform; -} + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i", + static_cast(m_opaque_sp.get()), + static_cast(target.m_opaque_sp.get()), result); + + return result; +} + +SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) { + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx)); + } + return sb_target; +} + +uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) { + + lldb::TargetSP target_sp = target.GetSP(); + if (!target_sp) + return UINT32_MAX; + + if (!m_opaque_sp) + return UINT32_MAX; + + return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP()); +} + +SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) { + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid)); + } + return sb_target; +} + +SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename, + const char *arch_name) { + SBTarget sb_target; + if (m_opaque_sp && filename && filename[0]) { + // No need to lock, the target list is thread safe + ArchSpec arch(arch_name, + m_opaque_sp->GetPlatformList().GetSelectedPlatform().get()); + TargetSP target_sp( + m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture( + FileSpec(filename, false), arch_name ? &arch : nullptr)); + sb_target.SetSP(target_sp); + } + return sb_target; +} + +SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) { + SBTarget sb_target; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + sb_target.SetSP( + m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get())); + } + return sb_target; +} + +uint32_t SBDebugger::GetNumTargets() { + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + return m_opaque_sp->GetTargetList().GetNumTargets(); + } + return 0; +} -void -SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBTarget SBDebugger::GetSelectedTarget() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + // No need to lock, the target list is thread safe + target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget(); + sb_target.SetSP(target_sp); + } - DebuggerSP debugger_sp(m_opaque_sp); - if (debugger_sp) - { - debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP()); - } + if (log) { + SBStream sstr; + sb_target.GetDescription(sstr, eDescriptionLevelBrief); + log->Printf("SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s", + static_cast(m_opaque_sp.get()), + static_cast(target_sp.get()), sstr.GetData()); + } - if (log) - log->Printf ("SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)", - static_cast(m_opaque_sp.get()), - static_cast(sb_platform.GetSP().get()), - sb_platform.GetName()); + return sb_target; } -void -SBDebugger::DispatchInput (void* baton, const void *data, size_t data_len) -{ - DispatchInput (data,data_len); +void SBDebugger::SetSelectedTarget(SBTarget &sb_target) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + TargetSP target_sp(sb_target.GetSP()); + if (m_opaque_sp) { + m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get()); + } + if (log) { + SBStream sstr; + sb_target.GetDescription(sstr, eDescriptionLevelBrief); + log->Printf("SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s", + static_cast(m_opaque_sp.get()), + static_cast(target_sp.get()), sstr.GetData()); + } +} + +SBPlatform SBDebugger::GetSelectedPlatform() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBPlatform sb_platform; + DebuggerSP debugger_sp(m_opaque_sp); + if (debugger_sp) { + sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform()); + } + if (log) + log->Printf("SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s", + static_cast(m_opaque_sp.get()), + static_cast(sb_platform.GetSP().get()), + sb_platform.GetName()); + return sb_platform; } -void -SBDebugger::DispatchInput (const void *data, size_t data_len) -{ -// Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); -// -// if (log) -// log->Printf ("SBDebugger(%p)::DispatchInput (data=\"%.*s\", size_t=%" PRIu64 ")", -// m_opaque_sp.get(), -// (int) data_len, -// (const char *) data, -// (uint64_t)data_len); -// -// if (m_opaque_sp) -// m_opaque_sp->DispatchInput ((const char *) data, data_len); -} +void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + DebuggerSP debugger_sp(m_opaque_sp); + if (debugger_sp) { + debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP()); + } -void -SBDebugger::DispatchInputInterrupt () -{ - if (m_opaque_sp) - m_opaque_sp->DispatchInputInterrupt (); + if (log) + log->Printf("SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)", + static_cast(m_opaque_sp.get()), + static_cast(sb_platform.GetSP().get()), + sb_platform.GetName()); +} + +void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) { + DispatchInput(data, data_len); +} + +void SBDebugger::DispatchInput(const void *data, size_t data_len) { + // Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + // + // if (log) + // log->Printf ("SBDebugger(%p)::DispatchInput (data=\"%.*s\", + // size_t=%" PRIu64 ")", + // m_opaque_sp.get(), + // (int) data_len, + // (const char *) data, + // (uint64_t)data_len); + // + // if (m_opaque_sp) + // m_opaque_sp->DispatchInput ((const char *) data, data_len); } -void -SBDebugger::DispatchInputEndOfFile () -{ - if (m_opaque_sp) - m_opaque_sp->DispatchInputEndOfFile (); +void SBDebugger::DispatchInputInterrupt() { + if (m_opaque_sp) + m_opaque_sp->DispatchInputInterrupt(); } -void -SBDebugger::PushInputReader (SBInputReader &reader) -{ +void SBDebugger::DispatchInputEndOfFile() { + if (m_opaque_sp) + m_opaque_sp->DispatchInputEndOfFile(); } -void -SBDebugger::RunCommandInterpreter (bool auto_handle_events, - bool spawn_thread) -{ - if (m_opaque_sp) - { - CommandInterpreterRunOptions options; +void SBDebugger::PushInputReader(SBInputReader &reader) {} - m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(auto_handle_events, - spawn_thread, - options); - } +void SBDebugger::RunCommandInterpreter(bool auto_handle_events, + bool spawn_thread) { + if (m_opaque_sp) { + CommandInterpreterRunOptions options; + + m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter( + auto_handle_events, spawn_thread, options); + } } -void -SBDebugger::RunCommandInterpreter (bool auto_handle_events, - bool spawn_thread, - SBCommandInterpreterRunOptions &options, - int &num_errors, - bool &quit_requested, - bool &stopped_for_crash) +void SBDebugger::RunCommandInterpreter(bool auto_handle_events, + bool spawn_thread, + SBCommandInterpreterRunOptions &options, + int &num_errors, bool &quit_requested, + bool &stopped_for_crash) { - if (m_opaque_sp) - { - CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); - interp.RunCommandInterpreter(auto_handle_events, spawn_thread, options.ref()); - num_errors = interp.GetNumErrors(); - quit_requested = interp.GetQuitRequested(); - stopped_for_crash = interp.GetStoppedForCrash(); - } + if (m_opaque_sp) { + CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter(); + interp.RunCommandInterpreter(auto_handle_events, spawn_thread, + options.ref()); + num_errors = interp.GetNumErrors(); + quit_requested = interp.GetQuitRequested(); + stopped_for_crash = interp.GetStoppedForCrash(); + } } -SBError -SBDebugger::RunREPL (lldb::LanguageType language, const char *repl_options) -{ - SBError error; - if (m_opaque_sp) - error.ref() = m_opaque_sp->RunREPL(language, repl_options); - else - error.SetErrorString ("invalid debugger"); - return error; +SBError SBDebugger::RunREPL(lldb::LanguageType language, + const char *repl_options) { + SBError error; + if (m_opaque_sp) + error.ref() = m_opaque_sp->RunREPL(language, repl_options); + else + error.SetErrorString("invalid debugger"); + return error; } -void -SBDebugger::reset (const DebuggerSP &debugger_sp) -{ - m_opaque_sp = debugger_sp; +void SBDebugger::reset(const DebuggerSP &debugger_sp) { + m_opaque_sp = debugger_sp; } -Debugger * -SBDebugger::get () const -{ - return m_opaque_sp.get(); -} +Debugger *SBDebugger::get() const { return m_opaque_sp.get(); } -Debugger & -SBDebugger::ref () const -{ - assert (m_opaque_sp.get()); - return *m_opaque_sp; +Debugger &SBDebugger::ref() const { + assert(m_opaque_sp.get()); + return *m_opaque_sp; } -const lldb::DebuggerSP & -SBDebugger::get_sp () const -{ - return m_opaque_sp; -} +const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; } -SBDebugger -SBDebugger::FindDebuggerWithID (int id) -{ - // No need to lock, the debugger list is thread safe - SBDebugger sb_debugger; - DebuggerSP debugger_sp = Debugger::FindDebuggerWithID (id); - if (debugger_sp) - sb_debugger.reset (debugger_sp); - return sb_debugger; +SBDebugger SBDebugger::FindDebuggerWithID(int id) { + // No need to lock, the debugger list is thread safe + SBDebugger sb_debugger; + DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id); + if (debugger_sp) + sb_debugger.reset(debugger_sp); + return sb_debugger; } -const char * -SBDebugger::GetInstanceName() -{ - return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr); +const char *SBDebugger::GetInstanceName() { + return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr); } -SBError -SBDebugger::SetInternalVariable (const char *var_name, const char *value, const char *debugger_instance_name) -{ - SBError sb_error; - DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName (ConstString(debugger_instance_name))); - Error error; - if (debugger_sp) - { - ExecutionContext exe_ctx (debugger_sp->GetCommandInterpreter().GetExecutionContext()); - error = debugger_sp->SetPropertyValue (&exe_ctx, - eVarSetOperationAssign, - var_name, - value); - } - else - { - error.SetErrorStringWithFormat ("invalid debugger instance name '%s'", debugger_instance_name); - } - if (error.Fail()) - sb_error.SetError(error); - return sb_error; +SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value, + const char *debugger_instance_name) { + SBError sb_error; + DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( + ConstString(debugger_instance_name))); + Error error; + if (debugger_sp) { + ExecutionContext exe_ctx( + debugger_sp->GetCommandInterpreter().GetExecutionContext()); + error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign, + var_name, value); + } else { + error.SetErrorStringWithFormat("invalid debugger instance name '%s'", + debugger_instance_name); + } + if (error.Fail()) + sb_error.SetError(error); + return sb_error; } SBStringList -SBDebugger::GetInternalVariableValue (const char *var_name, const char *debugger_instance_name) -{ - SBStringList ret_value; - DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName (ConstString(debugger_instance_name))); - Error error; - if (debugger_sp) - { - ExecutionContext exe_ctx (debugger_sp->GetCommandInterpreter().GetExecutionContext()); - lldb::OptionValueSP value_sp (debugger_sp->GetPropertyValue (&exe_ctx, - var_name, - false, - error)); - if (value_sp) - { - StreamString value_strm; - value_sp->DumpValue (&exe_ctx, value_strm, OptionValue::eDumpOptionValue); - const std::string &value_str = value_strm.GetString(); - if (!value_str.empty()) - { - StringList string_list; - string_list.SplitIntoLines(value_str); - return SBStringList(&string_list); - } - } +SBDebugger::GetInternalVariableValue(const char *var_name, + const char *debugger_instance_name) { + SBStringList ret_value; + DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( + ConstString(debugger_instance_name))); + Error error; + if (debugger_sp) { + ExecutionContext exe_ctx( + debugger_sp->GetCommandInterpreter().GetExecutionContext()); + lldb::OptionValueSP value_sp( + debugger_sp->GetPropertyValue(&exe_ctx, var_name, false, error)); + if (value_sp) { + StreamString value_strm; + value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue); + const std::string &value_str = value_strm.GetString(); + if (!value_str.empty()) { + StringList string_list; + string_list.SplitIntoLines(value_str); + return SBStringList(&string_list); + } } - return SBStringList(); + } + return SBStringList(); } -uint32_t -SBDebugger::GetTerminalWidth() const -{ - return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0); +uint32_t SBDebugger::GetTerminalWidth() const { + return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0); } -void -SBDebugger::SetTerminalWidth (uint32_t term_width) -{ - if (m_opaque_sp) - m_opaque_sp->SetTerminalWidth (term_width); +void SBDebugger::SetTerminalWidth(uint32_t term_width) { + if (m_opaque_sp) + m_opaque_sp->SetTerminalWidth(term_width); } -const char * -SBDebugger::GetPrompt() const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +const char *SBDebugger::GetPrompt() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBDebugger(%p)::GetPrompt () => \"%s\"", - static_cast(m_opaque_sp.get()), - (m_opaque_sp ? m_opaque_sp->GetPrompt() : "")); + if (log) + log->Printf("SBDebugger(%p)::GetPrompt () => \"%s\"", + static_cast(m_opaque_sp.get()), + (m_opaque_sp ? m_opaque_sp->GetPrompt() : "")); - return (m_opaque_sp ? m_opaque_sp->GetPrompt() : nullptr); + return (m_opaque_sp ? m_opaque_sp->GetPrompt() : nullptr); } -void -SBDebugger::SetPrompt (const char *prompt) -{ - if (m_opaque_sp) - m_opaque_sp->SetPrompt (prompt); +void SBDebugger::SetPrompt(const char *prompt) { + if (m_opaque_sp) + m_opaque_sp->SetPrompt(prompt); } - -ScriptLanguage -SBDebugger::GetScriptLanguage() const -{ - return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone); + +ScriptLanguage SBDebugger::GetScriptLanguage() const { + return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone); } -void -SBDebugger::SetScriptLanguage (ScriptLanguage script_lang) -{ - if (m_opaque_sp) - { - m_opaque_sp->SetScriptLanguage (script_lang); - } +void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) { + if (m_opaque_sp) { + m_opaque_sp->SetScriptLanguage(script_lang); + } } -bool -SBDebugger::SetUseExternalEditor(bool value) -{ - return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false); +bool SBDebugger::SetUseExternalEditor(bool value) { + return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false); } -bool -SBDebugger::GetUseExternalEditor() -{ - return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false); +bool SBDebugger::GetUseExternalEditor() { + return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false); } -bool -SBDebugger::SetUseColor(bool value) -{ - return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false); +bool SBDebugger::SetUseColor(bool value) { + return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false); } -bool -SBDebugger::GetUseColor() const -{ - return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false); +bool SBDebugger::GetUseColor() const { + return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false); } -bool -SBDebugger::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBDebugger::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - if (m_opaque_sp) - { - const char *name = m_opaque_sp->GetInstanceName().AsCString(); - user_id_t id = m_opaque_sp->GetID(); - strm.Printf ("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id); - } - else - strm.PutCString ("No value"); - - return true; + if (m_opaque_sp) { + const char *name = m_opaque_sp->GetInstanceName().AsCString(); + user_id_t id = m_opaque_sp->GetID(); + strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id); + } else + strm.PutCString("No value"); + + return true; } -user_id_t -SBDebugger::GetID() -{ - return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID); +user_id_t SBDebugger::GetID() { + return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID); } -SBError -SBDebugger::SetCurrentPlatform (const char *platform_name_cstr) -{ - SBError sb_error; - if (m_opaque_sp) - { - if (platform_name_cstr && platform_name_cstr[0]) - { - ConstString platform_name (platform_name_cstr); - PlatformSP platform_sp (Platform::Find (platform_name)); - - if (platform_sp) - { - // Already have a platform with this name, just select it - m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp); - } - else - { - // We don't have a platform by this name yet, create one - platform_sp = Platform::Create (platform_name, sb_error.ref()); - if (platform_sp) - { - // We created the platform, now append and select it - bool make_selected = true; - m_opaque_sp->GetPlatformList().Append (platform_sp, make_selected); - } - } - } - else - { - sb_error.ref().SetErrorString("invalid platform name"); +SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) { + SBError sb_error; + if (m_opaque_sp) { + if (platform_name_cstr && platform_name_cstr[0]) { + ConstString platform_name(platform_name_cstr); + PlatformSP platform_sp(Platform::Find(platform_name)); + + if (platform_sp) { + // Already have a platform with this name, just select it + m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp); + } else { + // We don't have a platform by this name yet, create one + platform_sp = Platform::Create(platform_name, sb_error.ref()); + if (platform_sp) { + // We created the platform, now append and select it + bool make_selected = true; + m_opaque_sp->GetPlatformList().Append(platform_sp, make_selected); } + } + } else { + sb_error.ref().SetErrorString("invalid platform name"); } - else - { - sb_error.ref().SetErrorString("invalid debugger"); + } else { + sb_error.ref().SetErrorString("invalid debugger"); + } + return sb_error; +} + +bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_opaque_sp) { + PlatformSP platform_sp( + m_opaque_sp->GetPlatformList().GetSelectedPlatform()); + + if (platform_sp) { + if (log && sysroot) + log->Printf("SBDebugger::SetCurrentPlatformSDKRoot (\"%s\")", sysroot); + platform_sp->SetSDKRootDirectory(ConstString(sysroot)); + return true; } - return sb_error; + } + return false; } -bool -SBDebugger::SetCurrentPlatformSDKRoot (const char *sysroot) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_opaque_sp) - { - PlatformSP platform_sp (m_opaque_sp->GetPlatformList().GetSelectedPlatform()); - - if (platform_sp) - { - if (log && sysroot) - log->Printf ("SBDebugger::SetCurrentPlatformSDKRoot (\"%s\")", sysroot); - platform_sp->SetSDKRootDirectory (ConstString (sysroot)); - return true; - } - } - return false; +bool SBDebugger::GetCloseInputOnEOF() const { + return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false); } -bool -SBDebugger::GetCloseInputOnEOF() const -{ - return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false); +void SBDebugger::SetCloseInputOnEOF(bool b) { + if (m_opaque_sp) + m_opaque_sp->SetCloseInputOnEOF(b); } -void -SBDebugger::SetCloseInputOnEOF (bool b) -{ - if (m_opaque_sp) - m_opaque_sp->SetCloseInputOnEOF (b); -} +SBTypeCategory SBDebugger::GetCategory(const char *category_name) { + if (!category_name || *category_name == 0) + return SBTypeCategory(); -SBTypeCategory -SBDebugger::GetCategory (const char* category_name) -{ - if (!category_name || *category_name == 0) - return SBTypeCategory(); - - TypeCategoryImplSP category_sp; - - if (DataVisualization::Categories::GetCategory(ConstString(category_name), category_sp, false)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); + TypeCategoryImplSP category_sp; + + if (DataVisualization::Categories::GetCategory(ConstString(category_name), + category_sp, false)) + return SBTypeCategory(category_sp); + else + return SBTypeCategory(); } -SBTypeCategory -SBDebugger::GetCategory (lldb::LanguageType lang_type) -{ - TypeCategoryImplSP category_sp; - if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); +SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) { + TypeCategoryImplSP category_sp; + if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) + return SBTypeCategory(category_sp); + else + return SBTypeCategory(); } -SBTypeCategory -SBDebugger::CreateCategory (const char* category_name) -{ - if (!category_name || *category_name == 0) - return SBTypeCategory(); - - TypeCategoryImplSP category_sp; - - if (DataVisualization::Categories::GetCategory(ConstString(category_name), category_sp, true)) - return SBTypeCategory(category_sp); - else - return SBTypeCategory(); +SBTypeCategory SBDebugger::CreateCategory(const char *category_name) { + if (!category_name || *category_name == 0) + return SBTypeCategory(); + + TypeCategoryImplSP category_sp; + + if (DataVisualization::Categories::GetCategory(ConstString(category_name), + category_sp, true)) + return SBTypeCategory(category_sp); + else + return SBTypeCategory(); } -bool -SBDebugger::DeleteCategory (const char* category_name) -{ - if (!category_name || *category_name == 0) - return false; - - return DataVisualization::Categories::Delete(ConstString(category_name)); +bool SBDebugger::DeleteCategory(const char *category_name) { + if (!category_name || *category_name == 0) + return false; + + return DataVisualization::Categories::Delete(ConstString(category_name)); } -uint32_t -SBDebugger::GetNumCategories() -{ - return DataVisualization::Categories::GetCount(); +uint32_t SBDebugger::GetNumCategories() { + return DataVisualization::Categories::GetCount(); } -SBTypeCategory -SBDebugger::GetCategoryAtIndex (uint32_t index) -{ - return SBTypeCategory(DataVisualization::Categories::GetCategoryAtIndex(index)); +SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) { + return SBTypeCategory( + DataVisualization::Categories::GetCategoryAtIndex(index)); } -SBTypeCategory -SBDebugger::GetDefaultCategory() -{ - return GetCategory("default"); +SBTypeCategory SBDebugger::GetDefaultCategory() { + return GetCategory("default"); } -SBTypeFormat -SBDebugger::GetFormatForType (SBTypeNameSpecifier type_name) -{ - SBTypeCategory default_category_sb = GetDefaultCategory(); - if (default_category_sb.GetEnabled()) - return default_category_sb.GetFormatForType(type_name); - return SBTypeFormat(); +SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) { + SBTypeCategory default_category_sb = GetDefaultCategory(); + if (default_category_sb.GetEnabled()) + return default_category_sb.GetFormatForType(type_name); + return SBTypeFormat(); } #ifndef LLDB_DISABLE_PYTHON -SBTypeSummary -SBDebugger::GetSummaryForType (SBTypeNameSpecifier type_name) -{ - if (!type_name.IsValid()) - return SBTypeSummary(); - return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP())); +SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) { + if (!type_name.IsValid()) + return SBTypeSummary(); + return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP())); } #endif // LLDB_DISABLE_PYTHON -SBTypeFilter -SBDebugger::GetFilterForType (SBTypeNameSpecifier type_name) -{ - if (!type_name.IsValid()) - return SBTypeFilter(); - return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP())); +SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) { + if (!type_name.IsValid()) + return SBTypeFilter(); + return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP())); } #ifndef LLDB_DISABLE_PYTHON -SBTypeSynthetic -SBDebugger::GetSyntheticForType (SBTypeNameSpecifier type_name) -{ - if (!type_name.IsValid()) - return SBTypeSynthetic(); - return SBTypeSynthetic(DataVisualization::GetSyntheticForType(type_name.GetSP())); +SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) { + if (!type_name.IsValid()) + return SBTypeSynthetic(); + return SBTypeSynthetic( + DataVisualization::GetSyntheticForType(type_name.GetSP())); } #endif // LLDB_DISABLE_PYTHON -bool -SBDebugger::EnableLog (const char *channel, const char **categories) -{ - if (m_opaque_sp) - { - uint32_t log_options = LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; - StreamString errors; - return m_opaque_sp->EnableLog(channel, categories, nullptr, log_options, errors); - } - else - return false; +bool SBDebugger::EnableLog(const char *channel, const char **categories) { + if (m_opaque_sp) { + uint32_t log_options = + LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; + StreamString errors; + return m_opaque_sp->EnableLog(channel, categories, nullptr, log_options, + errors); + } else + return false; } -void -SBDebugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton) -{ - if (m_opaque_sp) - { - return m_opaque_sp->SetLoggingCallback (log_callback, baton); - } +void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, + void *baton) { + if (m_opaque_sp) { + return m_opaque_sp->SetLoggingCallback(log_callback, baton); + } } diff --git a/lldb/source/API/SBDeclaration.cpp b/lldb/source/API/SBDeclaration.cpp index 8aea675afeb..fc21f83f7ce 100644 --- a/lldb/source/API/SBDeclaration.cpp +++ b/lldb/source/API/SBDeclaration.cpp @@ -1,4 +1,5 @@ -//===-- SBDeclaration.cpp -----------------------------------------*- C++ -*-===// +//===-- SBDeclaration.cpp -----------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -18,192 +19,135 @@ using namespace lldb; using namespace lldb_private; +SBDeclaration::SBDeclaration() : m_opaque_ap() {} -SBDeclaration::SBDeclaration () : - m_opaque_ap () -{ +SBDeclaration::SBDeclaration(const SBDeclaration &rhs) : m_opaque_ap() { + if (rhs.IsValid()) + ref() = rhs.ref(); } -SBDeclaration::SBDeclaration (const SBDeclaration &rhs) : - m_opaque_ap () -{ - if (rhs.IsValid()) - ref() = rhs.ref(); +SBDeclaration::SBDeclaration(const lldb_private::Declaration *lldb_object_ptr) + : m_opaque_ap() { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; } -SBDeclaration::SBDeclaration (const lldb_private::Declaration *lldb_object_ptr) : - m_opaque_ap () -{ - if (lldb_object_ptr) - ref() = *lldb_object_ptr; +const SBDeclaration &SBDeclaration::operator=(const SBDeclaration &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + ref() = rhs.ref(); + else + m_opaque_ap.reset(); + } + return *this; } -const SBDeclaration & -SBDeclaration::operator = (const SBDeclaration &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset(); - } - return *this; +void SBDeclaration::SetDeclaration( + const lldb_private::Declaration &lldb_object_ref) { + ref() = lldb_object_ref; } -void -SBDeclaration::SetDeclaration (const lldb_private::Declaration &lldb_object_ref) -{ - ref() = lldb_object_ref; +SBDeclaration::~SBDeclaration() {} + +bool SBDeclaration::IsValid() const { + return m_opaque_ap.get() && m_opaque_ap->IsValid(); } +SBFileSpec SBDeclaration::GetFileSpec() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBDeclaration::~SBDeclaration () -{ -} + SBFileSpec sb_file_spec; + if (m_opaque_ap.get() && m_opaque_ap->GetFile()) + sb_file_spec.SetFileSpec(m_opaque_ap->GetFile()); + if (log) { + SBStream sstr; + sb_file_spec.GetDescription(sstr); + log->Printf("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", + static_cast(m_opaque_ap.get()), + static_cast(sb_file_spec.get()), sstr.GetData()); + } -bool -SBDeclaration::IsValid () const -{ - return m_opaque_ap.get() && m_opaque_ap->IsValid(); + return sb_file_spec; } +uint32_t SBDeclaration::GetLine() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBFileSpec -SBDeclaration::GetFileSpec () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + uint32_t line = 0; + if (m_opaque_ap.get()) + line = m_opaque_ap->GetLine(); - SBFileSpec sb_file_spec; - if (m_opaque_ap.get() && m_opaque_ap->GetFile()) - sb_file_spec.SetFileSpec(m_opaque_ap->GetFile()); + if (log) + log->Printf("SBLineEntry(%p)::GetLine () => %u", + static_cast(m_opaque_ap.get()), line); - if (log) - { - SBStream sstr; - sb_file_spec.GetDescription (sstr); - log->Printf ("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", - static_cast(m_opaque_ap.get()), - static_cast(sb_file_spec.get()), - sstr.GetData()); - } - - return sb_file_spec; + return line; } -uint32_t -SBDeclaration::GetLine () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t line = 0; - if (m_opaque_ap.get()) - line = m_opaque_ap->GetLine(); - - if (log) - log->Printf ("SBLineEntry(%p)::GetLine () => %u", - static_cast(m_opaque_ap.get()), line); +uint32_t SBDeclaration::GetColumn() const { + if (m_opaque_ap.get()) + return m_opaque_ap->GetColumn(); + return 0; +} - return line; +void SBDeclaration::SetFileSpec(lldb::SBFileSpec filespec) { + if (filespec.IsValid()) + ref().SetFile(filespec.ref()); + else + ref().SetFile(FileSpec()); } +void SBDeclaration::SetLine(uint32_t line) { ref().SetLine(line); } +void SBDeclaration::SetColumn(uint32_t column) { ref().SetColumn(column); } -uint32_t -SBDeclaration::GetColumn () const -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetColumn(); - return 0; -} +bool SBDeclaration::operator==(const SBDeclaration &rhs) const { + lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); + lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); -void -SBDeclaration::SetFileSpec (lldb::SBFileSpec filespec) -{ - if (filespec.IsValid()) - ref().SetFile(filespec.ref()); - else - ref().SetFile(FileSpec()); -} -void -SBDeclaration::SetLine (uint32_t line) -{ - ref().SetLine(line); -} + if (lhs_ptr && rhs_ptr) + return lldb_private::Declaration::Compare(*lhs_ptr, *rhs_ptr) == 0; -void -SBDeclaration::SetColumn (uint32_t column) -{ - ref().SetColumn(column); + return lhs_ptr == rhs_ptr; } +bool SBDeclaration::operator!=(const SBDeclaration &rhs) const { + lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); + lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); + if (lhs_ptr && rhs_ptr) + return lldb_private::Declaration::Compare(*lhs_ptr, *rhs_ptr) != 0; -bool -SBDeclaration::operator == (const SBDeclaration &rhs) const -{ - lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); - lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); - - if (lhs_ptr && rhs_ptr) - return lldb_private::Declaration::Compare (*lhs_ptr, *rhs_ptr) == 0; - - return lhs_ptr == rhs_ptr; + return lhs_ptr != rhs_ptr; } -bool -SBDeclaration::operator != (const SBDeclaration &rhs) const -{ - lldb_private::Declaration *lhs_ptr = m_opaque_ap.get(); - lldb_private::Declaration *rhs_ptr = rhs.m_opaque_ap.get(); - - if (lhs_ptr && rhs_ptr) - return lldb_private::Declaration::Compare (*lhs_ptr, *rhs_ptr) != 0; - - return lhs_ptr != rhs_ptr; +const lldb_private::Declaration *SBDeclaration::operator->() const { + return m_opaque_ap.get(); } -const lldb_private::Declaration * -SBDeclaration::operator->() const -{ - return m_opaque_ap.get(); +lldb_private::Declaration &SBDeclaration::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new lldb_private::Declaration()); + return *m_opaque_ap; } -lldb_private::Declaration & -SBDeclaration::ref() -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new lldb_private::Declaration ()); - return *m_opaque_ap; +const lldb_private::Declaration &SBDeclaration::ref() const { + return *m_opaque_ap; } -const lldb_private::Declaration & -SBDeclaration::ref() const -{ - return *m_opaque_ap; -} +bool SBDeclaration::GetDescription(SBStream &description) { + Stream &strm = description.ref(); -bool -SBDeclaration::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - - if (m_opaque_ap.get()) - { - char file_path[PATH_MAX*2]; - m_opaque_ap->GetFile().GetPath (file_path, sizeof (file_path)); - strm.Printf ("%s:%u", file_path, GetLine()); - if (GetColumn() > 0) - strm.Printf (":%u", GetColumn()); - } - else - strm.PutCString ("No value"); - - return true; -} + if (m_opaque_ap.get()) { + char file_path[PATH_MAX * 2]; + m_opaque_ap->GetFile().GetPath(file_path, sizeof(file_path)); + strm.Printf("%s:%u", file_path, GetLine()); + if (GetColumn() > 0) + strm.Printf(":%u", GetColumn()); + } else + strm.PutCString("No value"); -lldb_private::Declaration * -SBDeclaration::get () -{ - return m_opaque_ap.get(); + return true; } + +lldb_private::Declaration *SBDeclaration::get() { return m_opaque_ap.get(); } diff --git a/lldb/source/API/SBError.cpp b/lldb/source/API/SBError.cpp index 157997b2502..451c0a709ec 100644 --- a/lldb/source/API/SBError.cpp +++ b/lldb/source/API/SBError.cpp @@ -17,221 +17,157 @@ using namespace lldb; using namespace lldb_private; +SBError::SBError() : m_opaque_ap() {} -SBError::SBError () : - m_opaque_ap () -{ +SBError::SBError(const SBError &rhs) : m_opaque_ap() { + if (rhs.IsValid()) + m_opaque_ap.reset(new Error(*rhs)); } -SBError::SBError (const SBError &rhs) : - m_opaque_ap () -{ - if (rhs.IsValid()) - m_opaque_ap.reset (new Error(*rhs)); -} - - -SBError::~SBError() -{ -} +SBError::~SBError() {} -const SBError & -SBError::operator = (const SBError &rhs) -{ - if (rhs.IsValid()) - { - if (m_opaque_ap.get()) - *m_opaque_ap = *rhs; - else - m_opaque_ap.reset (new Error(*rhs)); - } +const SBError &SBError::operator=(const SBError &rhs) { + if (rhs.IsValid()) { + if (m_opaque_ap.get()) + *m_opaque_ap = *rhs; else - m_opaque_ap.reset(); + m_opaque_ap.reset(new Error(*rhs)); + } else + m_opaque_ap.reset(); - return *this; + return *this; } - -const char * -SBError::GetCString () const -{ - if (m_opaque_ap.get()) - return m_opaque_ap->AsCString(); - return NULL; +const char *SBError::GetCString() const { + if (m_opaque_ap.get()) + return m_opaque_ap->AsCString(); + return NULL; } -void -SBError::Clear () -{ - if (m_opaque_ap.get()) - m_opaque_ap->Clear(); +void SBError::Clear() { + if (m_opaque_ap.get()) + m_opaque_ap->Clear(); } -bool -SBError::Fail () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBError::Fail() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool ret_value = false; - if (m_opaque_ap.get()) - ret_value = m_opaque_ap->Fail(); + bool ret_value = false; + if (m_opaque_ap.get()) + ret_value = m_opaque_ap->Fail(); - if (log) - log->Printf ("SBError(%p)::Fail () => %i", - static_cast(m_opaque_ap.get()), ret_value); + if (log) + log->Printf("SBError(%p)::Fail () => %i", + static_cast(m_opaque_ap.get()), ret_value); - return ret_value; + return ret_value; } -bool -SBError::Success () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool ret_value = true; - if (m_opaque_ap.get()) - ret_value = m_opaque_ap->Success(); +bool SBError::Success() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool ret_value = true; + if (m_opaque_ap.get()) + ret_value = m_opaque_ap->Success(); - if (log) - log->Printf ("SBError(%p)::Success () => %i", - static_cast(m_opaque_ap.get()), ret_value); + if (log) + log->Printf("SBError(%p)::Success () => %i", + static_cast(m_opaque_ap.get()), ret_value); - return ret_value; + return ret_value; } -uint32_t -SBError::GetError () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +uint32_t SBError::GetError() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - uint32_t err = 0; - if (m_opaque_ap.get()) - err = m_opaque_ap->GetError(); - - if (log) - log->Printf ("SBError(%p)::GetError () => 0x%8.8x", - static_cast(m_opaque_ap.get()), err); + uint32_t err = 0; + if (m_opaque_ap.get()) + err = m_opaque_ap->GetError(); + if (log) + log->Printf("SBError(%p)::GetError () => 0x%8.8x", + static_cast(m_opaque_ap.get()), err); - return err; + return err; } -ErrorType -SBError::GetType () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - ErrorType err_type = eErrorTypeInvalid; - if (m_opaque_ap.get()) - err_type = m_opaque_ap->GetType(); +ErrorType SBError::GetType() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + ErrorType err_type = eErrorTypeInvalid; + if (m_opaque_ap.get()) + err_type = m_opaque_ap->GetType(); - if (log) - log->Printf ("SBError(%p)::GetType () => %i", - static_cast(m_opaque_ap.get()), err_type); + if (log) + log->Printf("SBError(%p)::GetType () => %i", + static_cast(m_opaque_ap.get()), err_type); - return err_type; + return err_type; } -void -SBError::SetError (uint32_t err, ErrorType type) -{ - CreateIfNeeded (); - m_opaque_ap->SetError (err, type); +void SBError::SetError(uint32_t err, ErrorType type) { + CreateIfNeeded(); + m_opaque_ap->SetError(err, type); } -void -SBError::SetError (const Error &lldb_error) -{ - CreateIfNeeded (); - *m_opaque_ap = lldb_error; +void SBError::SetError(const Error &lldb_error) { + CreateIfNeeded(); + *m_opaque_ap = lldb_error; } - -void -SBError::SetErrorToErrno () -{ - CreateIfNeeded (); - m_opaque_ap->SetErrorToErrno (); +void SBError::SetErrorToErrno() { + CreateIfNeeded(); + m_opaque_ap->SetErrorToErrno(); } -void -SBError::SetErrorToGenericError () -{ - CreateIfNeeded (); - m_opaque_ap->SetErrorToErrno (); +void SBError::SetErrorToGenericError() { + CreateIfNeeded(); + m_opaque_ap->SetErrorToErrno(); } -void -SBError::SetErrorString (const char *err_str) -{ - CreateIfNeeded (); - m_opaque_ap->SetErrorString (err_str); +void SBError::SetErrorString(const char *err_str) { + CreateIfNeeded(); + m_opaque_ap->SetErrorString(err_str); } -int -SBError::SetErrorStringWithFormat (const char *format, ...) -{ - CreateIfNeeded (); - va_list args; - va_start (args, format); - int num_chars = m_opaque_ap->SetErrorStringWithVarArg (format, args); - va_end (args); - return num_chars; +int SBError::SetErrorStringWithFormat(const char *format, ...) { + CreateIfNeeded(); + va_list args; + va_start(args, format); + int num_chars = m_opaque_ap->SetErrorStringWithVarArg(format, args); + va_end(args); + return num_chars; } -bool -SBError::IsValid () const -{ - return m_opaque_ap.get() != NULL; -} +bool SBError::IsValid() const { return m_opaque_ap.get() != NULL; } -void -SBError::CreateIfNeeded () -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset(new Error ()); +void SBError::CreateIfNeeded() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new Error()); } +lldb_private::Error *SBError::operator->() { return m_opaque_ap.get(); } -lldb_private::Error * -SBError::operator->() -{ - return m_opaque_ap.get(); -} +lldb_private::Error *SBError::get() { return m_opaque_ap.get(); } -lldb_private::Error * -SBError::get() -{ - return m_opaque_ap.get(); +lldb_private::Error &SBError::ref() { + CreateIfNeeded(); + return *m_opaque_ap; } -lldb_private::Error & -SBError::ref() -{ - CreateIfNeeded(); - return *m_opaque_ap; +const lldb_private::Error &SBError::operator*() const { + // Be sure to call "IsValid()" before calling this function or it will crash + return *m_opaque_ap; } -const lldb_private::Error & -SBError::operator*() const -{ - // Be sure to call "IsValid()" before calling this function or it will crash - return *m_opaque_ap; -} - -bool -SBError::GetDescription (SBStream &description) -{ - if (m_opaque_ap.get()) - { - if (m_opaque_ap->Success()) - description.Printf ("success"); - else - { - const char * err_string = GetCString(); - description.Printf ("error: %s", (err_string != NULL ? err_string : "")); - } +bool SBError::GetDescription(SBStream &description) { + if (m_opaque_ap.get()) { + if (m_opaque_ap->Success()) + description.Printf("success"); + else { + const char *err_string = GetCString(); + description.Printf("error: %s", (err_string != NULL ? err_string : "")); } - else - description.Printf ("error: "); + } else + description.Printf("error: "); - return true; -} + return true; +} diff --git a/lldb/source/API/SBEvent.cpp b/lldb/source/API/SBEvent.cpp index 164636defc9..e0bb68c66c2 100644 --- a/lldb/source/API/SBEvent.cpp +++ b/lldb/source/API/SBEvent.cpp @@ -11,240 +11,181 @@ #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBStream.h" +#include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Core/ConstString.h" #include "lldb/Core/Event.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/ConstString.h" -#include "lldb/Target/Process.h" -#include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Target/Process.h" using namespace lldb; using namespace lldb_private; +SBEvent::SBEvent() : m_event_sp(), m_opaque_ptr(NULL) {} -SBEvent::SBEvent () : - m_event_sp (), - m_opaque_ptr (NULL) -{ -} +SBEvent::SBEvent(uint32_t event_type, const char *cstr, uint32_t cstr_len) + : m_event_sp(new Event(event_type, new EventDataBytes(cstr, cstr_len))), + m_opaque_ptr(m_event_sp.get()) {} -SBEvent::SBEvent (uint32_t event_type, const char *cstr, uint32_t cstr_len) : - m_event_sp (new Event (event_type, new EventDataBytes (cstr, cstr_len))), - m_opaque_ptr (m_event_sp.get()) -{ -} +SBEvent::SBEvent(EventSP &event_sp) + : m_event_sp(event_sp), m_opaque_ptr(event_sp.get()) {} -SBEvent::SBEvent (EventSP &event_sp) : - m_event_sp (event_sp), - m_opaque_ptr (event_sp.get()) -{ -} +SBEvent::SBEvent(Event *event_ptr) : m_event_sp(), m_opaque_ptr(event_ptr) {} -SBEvent::SBEvent (Event *event_ptr) : - m_event_sp (), - m_opaque_ptr (event_ptr) -{ -} +SBEvent::SBEvent(const SBEvent &rhs) + : m_event_sp(rhs.m_event_sp), m_opaque_ptr(rhs.m_opaque_ptr) {} -SBEvent::SBEvent (const SBEvent &rhs) : - m_event_sp (rhs.m_event_sp), - m_opaque_ptr (rhs.m_opaque_ptr) -{ - -} - -const SBEvent & -SBEvent::operator = (const SBEvent &rhs) -{ - if (this != &rhs) - { - m_event_sp = rhs.m_event_sp; - m_opaque_ptr = rhs.m_opaque_ptr; - } - return *this; +const SBEvent &SBEvent::operator=(const SBEvent &rhs) { + if (this != &rhs) { + m_event_sp = rhs.m_event_sp; + m_opaque_ptr = rhs.m_opaque_ptr; + } + return *this; } -SBEvent::~SBEvent() -{ -} +SBEvent::~SBEvent() {} -const char * -SBEvent::GetDataFlavor () -{ - Event *lldb_event = get(); - if (lldb_event) - { - EventData *event_data = lldb_event->GetData(); - if (event_data) - return lldb_event->GetData()->GetFlavor().AsCString(); - } - return NULL; +const char *SBEvent::GetDataFlavor() { + Event *lldb_event = get(); + if (lldb_event) { + EventData *event_data = lldb_event->GetData(); + if (event_data) + return lldb_event->GetData()->GetFlavor().AsCString(); + } + return NULL; } -uint32_t -SBEvent::GetType () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - const Event *lldb_event = get(); - uint32_t event_type = 0; - if (lldb_event) - event_type = lldb_event->GetType(); - - if (log) - { - StreamString sstr; - if (lldb_event && lldb_event->GetBroadcaster() && lldb_event->GetBroadcaster()->GetEventNames(sstr, event_type, true)) - log->Printf ("SBEvent(%p)::GetType () => 0x%8.8x (%s)", - static_cast(get()), event_type, sstr.GetData()); - else - log->Printf ("SBEvent(%p)::GetType () => 0x%8.8x", - static_cast(get()), event_type); - - } - - return event_type; -} +uint32_t SBEvent::GetType() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBBroadcaster -SBEvent::GetBroadcaster () const -{ - SBBroadcaster broadcaster; - const Event *lldb_event = get(); - if (lldb_event) - broadcaster.reset (lldb_event->GetBroadcaster(), false); - return broadcaster; -} + const Event *lldb_event = get(); + uint32_t event_type = 0; + if (lldb_event) + event_type = lldb_event->GetType(); -const char * -SBEvent::GetBroadcasterClass () const -{ - const Event *lldb_event = get(); - if (lldb_event) - return lldb_event->GetBroadcaster()->GetBroadcasterClass().AsCString(); + if (log) { + StreamString sstr; + if (lldb_event && lldb_event->GetBroadcaster() && + lldb_event->GetBroadcaster()->GetEventNames(sstr, event_type, true)) + log->Printf("SBEvent(%p)::GetType () => 0x%8.8x (%s)", + static_cast(get()), event_type, sstr.GetData()); else - return "unknown class"; + log->Printf("SBEvent(%p)::GetType () => 0x%8.8x", + static_cast(get()), event_type); + } + + return event_type; } -bool -SBEvent::BroadcasterMatchesPtr (const SBBroadcaster *broadcaster) -{ - if (broadcaster) - return BroadcasterMatchesRef (*broadcaster); - return false; +SBBroadcaster SBEvent::GetBroadcaster() const { + SBBroadcaster broadcaster; + const Event *lldb_event = get(); + if (lldb_event) + broadcaster.reset(lldb_event->GetBroadcaster(), false); + return broadcaster; } -bool -SBEvent::BroadcasterMatchesRef (const SBBroadcaster &broadcaster) -{ +const char *SBEvent::GetBroadcasterClass() const { + const Event *lldb_event = get(); + if (lldb_event) + return lldb_event->GetBroadcaster()->GetBroadcasterClass().AsCString(); + else + return "unknown class"; +} - Event *lldb_event = get(); - bool success = false; - if (lldb_event) - success = lldb_event->BroadcasterIs (broadcaster.get()); +bool SBEvent::BroadcasterMatchesPtr(const SBBroadcaster *broadcaster) { + if (broadcaster) + return BroadcasterMatchesRef(*broadcaster); + return false; +} - // For logging, this gets a little chatty so only enable this when verbose logging is on - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API | LIBLLDB_LOG_VERBOSE)); - if (log) - log->Printf ("SBEvent(%p)::BroadcasterMatchesRef (SBBroadcaster(%p): %s) => %i", - static_cast(get()), - static_cast(broadcaster.get()), - broadcaster.GetName(), success); +bool SBEvent::BroadcasterMatchesRef(const SBBroadcaster &broadcaster) { - return success; -} + Event *lldb_event = get(); + bool success = false; + if (lldb_event) + success = lldb_event->BroadcasterIs(broadcaster.get()); -void -SBEvent::Clear() -{ - Event *lldb_event = get(); - if (lldb_event) - lldb_event->Clear(); -} + // For logging, this gets a little chatty so only enable this when verbose + // logging is on + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API | + LIBLLDB_LOG_VERBOSE)); + if (log) + log->Printf( + "SBEvent(%p)::BroadcasterMatchesRef (SBBroadcaster(%p): %s) => %i", + static_cast(get()), static_cast(broadcaster.get()), + broadcaster.GetName(), success); -EventSP & -SBEvent::GetSP () const -{ - return m_event_sp; + return success; } -Event * -SBEvent::get() const -{ - // There is a dangerous accessor call GetSharedPtr which can be used, so if - // we have anything valid in m_event_sp, we must use that since if it gets - // used by a function that puts something in there, then it won't update - // m_opaque_ptr... - if (m_event_sp) - m_opaque_ptr = m_event_sp.get(); - - return m_opaque_ptr; +void SBEvent::Clear() { + Event *lldb_event = get(); + if (lldb_event) + lldb_event->Clear(); } -void -SBEvent::reset (EventSP &event_sp) -{ - m_event_sp = event_sp; +EventSP &SBEvent::GetSP() const { return m_event_sp; } + +Event *SBEvent::get() const { + // There is a dangerous accessor call GetSharedPtr which can be used, so if + // we have anything valid in m_event_sp, we must use that since if it gets + // used by a function that puts something in there, then it won't update + // m_opaque_ptr... + if (m_event_sp) m_opaque_ptr = m_event_sp.get(); + + return m_opaque_ptr; } -void -SBEvent::reset (Event* event_ptr) -{ - m_opaque_ptr = event_ptr; - m_event_sp.reset(); +void SBEvent::reset(EventSP &event_sp) { + m_event_sp = event_sp; + m_opaque_ptr = m_event_sp.get(); } -bool -SBEvent::IsValid() const -{ - // Do NOT use m_opaque_ptr directly!!! Must use the SBEvent::get() - // accessor. See comments in SBEvent::get().... - return SBEvent::get() != NULL; +void SBEvent::reset(Event *event_ptr) { + m_opaque_ptr = event_ptr; + m_event_sp.reset(); +} +bool SBEvent::IsValid() const { + // Do NOT use m_opaque_ptr directly!!! Must use the SBEvent::get() + // accessor. See comments in SBEvent::get().... + return SBEvent::get() != NULL; } -const char * -SBEvent::GetCStringFromEvent (const SBEvent &event) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +const char *SBEvent::GetCStringFromEvent(const SBEvent &event) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBEvent(%p)::GetCStringFromEvent () => \"%s\"", - static_cast(event.get()), - reinterpret_cast(EventDataBytes::GetBytesFromEvent (event.get()))); + if (log) + log->Printf("SBEvent(%p)::GetCStringFromEvent () => \"%s\"", + static_cast(event.get()), + reinterpret_cast( + EventDataBytes::GetBytesFromEvent(event.get()))); - return reinterpret_cast(EventDataBytes::GetBytesFromEvent (event.get())); + return reinterpret_cast( + EventDataBytes::GetBytesFromEvent(event.get())); } +bool SBEvent::GetDescription(SBStream &description) { + Stream &strm = description.ref(); -bool -SBEvent::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); + if (get()) { + m_opaque_ptr->Dump(&strm); + } else + strm.PutCString("No value"); - if (get()) - { - m_opaque_ptr->Dump (&strm); - } - else - strm.PutCString ("No value"); - - return true; + return true; } -bool -SBEvent::GetDescription (SBStream &description) const -{ - Stream &strm = description.ref(); +bool SBEvent::GetDescription(SBStream &description) const { + Stream &strm = description.ref(); - if (get()) - { - m_opaque_ptr->Dump (&strm); - } - else - strm.PutCString ("No value"); + if (get()) { + m_opaque_ptr->Dump(&strm); + } else + strm.PutCString("No value"); - return true; + return true; } diff --git a/lldb/source/API/SBExecutionContext.cpp b/lldb/source/API/SBExecutionContext.cpp index dc20c609213..74a543c77d2 100644 --- a/lldb/source/API/SBExecutionContext.cpp +++ b/lldb/source/API/SBExecutionContext.cpp @@ -1,4 +1,5 @@ -//===-- SBExecutionContext.cpp ------------------------------------*- C++ -*-===// +//===-- SBExecutionContext.cpp ------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -9,121 +10,93 @@ #include "lldb/API/SBExecutionContext.h" -#include "lldb/API/SBTarget.h" +#include "lldb/API/SBFrame.h" #include "lldb/API/SBProcess.h" +#include "lldb/API/SBTarget.h" #include "lldb/API/SBThread.h" -#include "lldb/API/SBFrame.h" #include "lldb/Target/ExecutionContext.h" using namespace lldb; using namespace lldb_private; -SBExecutionContext::SBExecutionContext() : -m_exe_ctx_sp() -{ -} +SBExecutionContext::SBExecutionContext() : m_exe_ctx_sp() {} -SBExecutionContext::SBExecutionContext (const lldb::SBExecutionContext &rhs) : -m_exe_ctx_sp(rhs.m_exe_ctx_sp) -{ -} +SBExecutionContext::SBExecutionContext(const lldb::SBExecutionContext &rhs) + : m_exe_ctx_sp(rhs.m_exe_ctx_sp) {} -SBExecutionContext::SBExecutionContext (lldb::ExecutionContextRefSP exe_ctx_ref_sp) : -m_exe_ctx_sp(exe_ctx_ref_sp) -{ -} +SBExecutionContext::SBExecutionContext( + lldb::ExecutionContextRefSP exe_ctx_ref_sp) + : m_exe_ctx_sp(exe_ctx_ref_sp) {} -SBExecutionContext::SBExecutionContext (const lldb::SBTarget &target) : -m_exe_ctx_sp(new ExecutionContextRef()) -{ - m_exe_ctx_sp->SetTargetSP(target.GetSP()); +SBExecutionContext::SBExecutionContext(const lldb::SBTarget &target) + : m_exe_ctx_sp(new ExecutionContextRef()) { + m_exe_ctx_sp->SetTargetSP(target.GetSP()); } -SBExecutionContext::SBExecutionContext (const lldb::SBProcess &process) : -m_exe_ctx_sp(new ExecutionContextRef()) -{ - m_exe_ctx_sp->SetProcessSP(process.GetSP()); +SBExecutionContext::SBExecutionContext(const lldb::SBProcess &process) + : m_exe_ctx_sp(new ExecutionContextRef()) { + m_exe_ctx_sp->SetProcessSP(process.GetSP()); } -SBExecutionContext::SBExecutionContext (lldb::SBThread thread) : -m_exe_ctx_sp(new ExecutionContextRef()) -{ - m_exe_ctx_sp->SetThreadPtr(thread.get()); +SBExecutionContext::SBExecutionContext(lldb::SBThread thread) + : m_exe_ctx_sp(new ExecutionContextRef()) { + m_exe_ctx_sp->SetThreadPtr(thread.get()); } -SBExecutionContext::SBExecutionContext (const lldb::SBFrame &frame) : -m_exe_ctx_sp(new ExecutionContextRef()) -{ - m_exe_ctx_sp->SetFrameSP(frame.GetFrameSP()); +SBExecutionContext::SBExecutionContext(const lldb::SBFrame &frame) + : m_exe_ctx_sp(new ExecutionContextRef()) { + m_exe_ctx_sp->SetFrameSP(frame.GetFrameSP()); } -SBExecutionContext::~SBExecutionContext() -{ -} +SBExecutionContext::~SBExecutionContext() {} -const SBExecutionContext & -SBExecutionContext::operator = (const lldb::SBExecutionContext &rhs) -{ - m_exe_ctx_sp = rhs.m_exe_ctx_sp; - return *this; +const SBExecutionContext &SBExecutionContext:: +operator=(const lldb::SBExecutionContext &rhs) { + m_exe_ctx_sp = rhs.m_exe_ctx_sp; + return *this; } -ExecutionContextRef * -SBExecutionContext::get () const -{ - return m_exe_ctx_sp.get(); +ExecutionContextRef *SBExecutionContext::get() const { + return m_exe_ctx_sp.get(); } -SBTarget -SBExecutionContext::GetTarget () const -{ - SBTarget sb_target; - if (m_exe_ctx_sp) - { - TargetSP target_sp(m_exe_ctx_sp->GetTargetSP()); - if (target_sp) - sb_target.SetSP(target_sp); - } - return sb_target; +SBTarget SBExecutionContext::GetTarget() const { + SBTarget sb_target; + if (m_exe_ctx_sp) { + TargetSP target_sp(m_exe_ctx_sp->GetTargetSP()); + if (target_sp) + sb_target.SetSP(target_sp); + } + return sb_target; } -SBProcess -SBExecutionContext::GetProcess () const -{ - SBProcess sb_process; - if (m_exe_ctx_sp) - { - ProcessSP process_sp(m_exe_ctx_sp->GetProcessSP()); - if (process_sp) - sb_process.SetSP(process_sp); - } - return sb_process; +SBProcess SBExecutionContext::GetProcess() const { + SBProcess sb_process; + if (m_exe_ctx_sp) { + ProcessSP process_sp(m_exe_ctx_sp->GetProcessSP()); + if (process_sp) + sb_process.SetSP(process_sp); + } + return sb_process; } -SBThread -SBExecutionContext::GetThread () const -{ - SBThread sb_thread; - if (m_exe_ctx_sp) - { - ThreadSP thread_sp(m_exe_ctx_sp->GetThreadSP()); - if (thread_sp) - sb_thread.SetThread(thread_sp); - } - return sb_thread; +SBThread SBExecutionContext::GetThread() const { + SBThread sb_thread; + if (m_exe_ctx_sp) { + ThreadSP thread_sp(m_exe_ctx_sp->GetThreadSP()); + if (thread_sp) + sb_thread.SetThread(thread_sp); + } + return sb_thread; } -SBFrame -SBExecutionContext::GetFrame () const -{ - SBFrame sb_frame; - if (m_exe_ctx_sp) - { - StackFrameSP frame_sp(m_exe_ctx_sp->GetFrameSP()); - if (frame_sp) - sb_frame.SetFrameSP(frame_sp); - } - return sb_frame; +SBFrame SBExecutionContext::GetFrame() const { + SBFrame sb_frame; + if (m_exe_ctx_sp) { + StackFrameSP frame_sp(m_exe_ctx_sp->GetFrameSP()); + if (frame_sp) + sb_frame.SetFrameSP(frame_sp); + } + return sb_frame; } - diff --git a/lldb/source/API/SBExpressionOptions.cpp b/lldb/source/API/SBExpressionOptions.cpp index 328a96ef6b5..218d93e96c3 100644 --- a/lldb/source/API/SBExpressionOptions.cpp +++ b/lldb/source/API/SBExpressionOptions.cpp @@ -1,4 +1,5 @@ -//===-- SBExpressionOptions.cpp ---------------------------------------------*- C++ -*-===// +//===-- SBExpressionOptions.cpp ---------------------------------------------*- +//C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -15,220 +16,150 @@ using namespace lldb; using namespace lldb_private; +SBExpressionOptions::SBExpressionOptions() + : m_opaque_ap(new EvaluateExpressionOptions()) {} -SBExpressionOptions::SBExpressionOptions () : - m_opaque_ap(new EvaluateExpressionOptions()) -{ +SBExpressionOptions::SBExpressionOptions(const SBExpressionOptions &rhs) { + m_opaque_ap.reset(new EvaluateExpressionOptions()); + *(m_opaque_ap.get()) = rhs.ref(); } -SBExpressionOptions::SBExpressionOptions (const SBExpressionOptions &rhs) -{ - m_opaque_ap.reset(new EvaluateExpressionOptions()); - *(m_opaque_ap.get()) = rhs.ref(); +const SBExpressionOptions &SBExpressionOptions:: +operator=(const SBExpressionOptions &rhs) { + if (this != &rhs) { + this->ref() = rhs.ref(); + } + return *this; } -const SBExpressionOptions & -SBExpressionOptions::operator = (const SBExpressionOptions &rhs) -{ - if (this != &rhs) - { - this->ref() = rhs.ref(); - } - return *this; -} - -SBExpressionOptions::~SBExpressionOptions() -{ -} +SBExpressionOptions::~SBExpressionOptions() {} -bool -SBExpressionOptions::GetCoerceResultToId () const -{ - return m_opaque_ap->DoesCoerceToId (); +bool SBExpressionOptions::GetCoerceResultToId() const { + return m_opaque_ap->DoesCoerceToId(); } -void -SBExpressionOptions::SetCoerceResultToId (bool coerce) -{ - m_opaque_ap->SetCoerceToId (coerce); +void SBExpressionOptions::SetCoerceResultToId(bool coerce) { + m_opaque_ap->SetCoerceToId(coerce); } -bool -SBExpressionOptions::GetUnwindOnError () const -{ - return m_opaque_ap->DoesUnwindOnError (); +bool SBExpressionOptions::GetUnwindOnError() const { + return m_opaque_ap->DoesUnwindOnError(); } -void -SBExpressionOptions::SetUnwindOnError (bool unwind) -{ - m_opaque_ap->SetUnwindOnError (unwind); +void SBExpressionOptions::SetUnwindOnError(bool unwind) { + m_opaque_ap->SetUnwindOnError(unwind); } -bool -SBExpressionOptions::GetIgnoreBreakpoints () const -{ - return m_opaque_ap->DoesIgnoreBreakpoints (); +bool SBExpressionOptions::GetIgnoreBreakpoints() const { + return m_opaque_ap->DoesIgnoreBreakpoints(); } -void -SBExpressionOptions::SetIgnoreBreakpoints (bool ignore) -{ - m_opaque_ap->SetIgnoreBreakpoints (ignore); +void SBExpressionOptions::SetIgnoreBreakpoints(bool ignore) { + m_opaque_ap->SetIgnoreBreakpoints(ignore); } -lldb::DynamicValueType -SBExpressionOptions::GetFetchDynamicValue () const -{ - return m_opaque_ap->GetUseDynamic (); +lldb::DynamicValueType SBExpressionOptions::GetFetchDynamicValue() const { + return m_opaque_ap->GetUseDynamic(); } -void -SBExpressionOptions::SetFetchDynamicValue (lldb::DynamicValueType dynamic) -{ - m_opaque_ap->SetUseDynamic (dynamic); +void SBExpressionOptions::SetFetchDynamicValue(lldb::DynamicValueType dynamic) { + m_opaque_ap->SetUseDynamic(dynamic); } -uint32_t -SBExpressionOptions::GetTimeoutInMicroSeconds () const -{ - return m_opaque_ap->GetTimeoutUsec (); +uint32_t SBExpressionOptions::GetTimeoutInMicroSeconds() const { + return m_opaque_ap->GetTimeoutUsec(); } -void -SBExpressionOptions::SetTimeoutInMicroSeconds (uint32_t timeout) -{ - m_opaque_ap->SetTimeoutUsec (timeout); +void SBExpressionOptions::SetTimeoutInMicroSeconds(uint32_t timeout) { + m_opaque_ap->SetTimeoutUsec(timeout); } -uint32_t -SBExpressionOptions::GetOneThreadTimeoutInMicroSeconds () const -{ - return m_opaque_ap->GetOneThreadTimeoutUsec (); +uint32_t SBExpressionOptions::GetOneThreadTimeoutInMicroSeconds() const { + return m_opaque_ap->GetOneThreadTimeoutUsec(); } -void -SBExpressionOptions::SetOneThreadTimeoutInMicroSeconds (uint32_t timeout) -{ - m_opaque_ap->SetOneThreadTimeoutUsec (timeout); +void SBExpressionOptions::SetOneThreadTimeoutInMicroSeconds(uint32_t timeout) { + m_opaque_ap->SetOneThreadTimeoutUsec(timeout); } -bool -SBExpressionOptions::GetTryAllThreads () const -{ - return m_opaque_ap->GetTryAllThreads (); +bool SBExpressionOptions::GetTryAllThreads() const { + return m_opaque_ap->GetTryAllThreads(); } -void -SBExpressionOptions::SetTryAllThreads (bool run_others) -{ - m_opaque_ap->SetTryAllThreads (run_others); +void SBExpressionOptions::SetTryAllThreads(bool run_others) { + m_opaque_ap->SetTryAllThreads(run_others); } -bool -SBExpressionOptions::GetStopOthers () const -{ - return m_opaque_ap->GetStopOthers (); +bool SBExpressionOptions::GetStopOthers() const { + return m_opaque_ap->GetStopOthers(); } -void -SBExpressionOptions::SetStopOthers (bool run_others) -{ - m_opaque_ap->SetStopOthers (run_others); +void SBExpressionOptions::SetStopOthers(bool run_others) { + m_opaque_ap->SetStopOthers(run_others); } -bool -SBExpressionOptions::GetTrapExceptions () const -{ - return m_opaque_ap->GetTrapExceptions (); +bool SBExpressionOptions::GetTrapExceptions() const { + return m_opaque_ap->GetTrapExceptions(); } -void -SBExpressionOptions::SetTrapExceptions (bool trap_exceptions) -{ - m_opaque_ap->SetTrapExceptions (trap_exceptions); +void SBExpressionOptions::SetTrapExceptions(bool trap_exceptions) { + m_opaque_ap->SetTrapExceptions(trap_exceptions); } -void -SBExpressionOptions::SetLanguage (lldb::LanguageType language) -{ - m_opaque_ap->SetLanguage(language); +void SBExpressionOptions::SetLanguage(lldb::LanguageType language) { + m_opaque_ap->SetLanguage(language); } -void -SBExpressionOptions::SetCancelCallback (lldb::ExpressionCancelCallback callback, void *baton) -{ - m_opaque_ap->SetCancelCallback (callback, baton); +void SBExpressionOptions::SetCancelCallback( + lldb::ExpressionCancelCallback callback, void *baton) { + m_opaque_ap->SetCancelCallback(callback, baton); } -bool -SBExpressionOptions::GetGenerateDebugInfo () -{ - return m_opaque_ap->GetGenerateDebugInfo(); +bool SBExpressionOptions::GetGenerateDebugInfo() { + return m_opaque_ap->GetGenerateDebugInfo(); } -void -SBExpressionOptions::SetGenerateDebugInfo (bool b) -{ - return m_opaque_ap->SetGenerateDebugInfo(b); +void SBExpressionOptions::SetGenerateDebugInfo(bool b) { + return m_opaque_ap->SetGenerateDebugInfo(b); } -bool -SBExpressionOptions::GetSuppressPersistentResult () -{ - return m_opaque_ap->GetResultIsInternal (); +bool SBExpressionOptions::GetSuppressPersistentResult() { + return m_opaque_ap->GetResultIsInternal(); } -void -SBExpressionOptions::SetSuppressPersistentResult (bool b) -{ - return m_opaque_ap->SetResultIsInternal (b); +void SBExpressionOptions::SetSuppressPersistentResult(bool b) { + return m_opaque_ap->SetResultIsInternal(b); } -const char * -SBExpressionOptions::GetPrefix () const -{ - return m_opaque_ap->GetPrefix(); +const char *SBExpressionOptions::GetPrefix() const { + return m_opaque_ap->GetPrefix(); } -void -SBExpressionOptions::SetPrefix (const char *prefix) -{ - return m_opaque_ap->SetPrefix(prefix); +void SBExpressionOptions::SetPrefix(const char *prefix) { + return m_opaque_ap->SetPrefix(prefix); } -bool -SBExpressionOptions::GetAutoApplyFixIts () -{ - return m_opaque_ap->GetAutoApplyFixIts (); +bool SBExpressionOptions::GetAutoApplyFixIts() { + return m_opaque_ap->GetAutoApplyFixIts(); } -void -SBExpressionOptions::SetAutoApplyFixIts (bool b) -{ - return m_opaque_ap->SetAutoApplyFixIts (b); +void SBExpressionOptions::SetAutoApplyFixIts(bool b) { + return m_opaque_ap->SetAutoApplyFixIts(b); } -bool -SBExpressionOptions::GetTopLevel () -{ - return m_opaque_ap->GetExecutionPolicy() == eExecutionPolicyTopLevel; +bool SBExpressionOptions::GetTopLevel() { + return m_opaque_ap->GetExecutionPolicy() == eExecutionPolicyTopLevel; } -void -SBExpressionOptions::SetTopLevel (bool b) -{ - m_opaque_ap->SetExecutionPolicy(b ? eExecutionPolicyTopLevel : m_opaque_ap->default_execution_policy); +void SBExpressionOptions::SetTopLevel(bool b) { + m_opaque_ap->SetExecutionPolicy(b ? eExecutionPolicyTopLevel + : m_opaque_ap->default_execution_policy); } -EvaluateExpressionOptions * -SBExpressionOptions::get() const -{ - return m_opaque_ap.get(); +EvaluateExpressionOptions *SBExpressionOptions::get() const { + return m_opaque_ap.get(); } -EvaluateExpressionOptions & -SBExpressionOptions::ref () const -{ - return *(m_opaque_ap.get()); +EvaluateExpressionOptions &SBExpressionOptions::ref() const { + return *(m_opaque_ap.get()); } diff --git a/lldb/source/API/SBFileSpec.cpp b/lldb/source/API/SBFileSpec.cpp index 23bc5bc8eb6..88baf3b17ab 100644 --- a/lldb/source/API/SBFileSpec.cpp +++ b/lldb/source/API/SBFileSpec.cpp @@ -12,208 +12,155 @@ #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBStream.h" -#include "lldb/Host/FileSpec.h" #include "lldb/Core/Log.h" #include "lldb/Core/Stream.h" +#include "lldb/Host/FileSpec.h" #include "llvm/ADT/SmallString.h" using namespace lldb; using namespace lldb_private; +SBFileSpec::SBFileSpec() : m_opaque_ap(new lldb_private::FileSpec()) {} +SBFileSpec::SBFileSpec(const SBFileSpec &rhs) + : m_opaque_ap(new lldb_private::FileSpec(*rhs.m_opaque_ap)) {} -SBFileSpec::SBFileSpec () : - m_opaque_ap(new lldb_private::FileSpec()) -{ -} - -SBFileSpec::SBFileSpec (const SBFileSpec &rhs) : - m_opaque_ap(new lldb_private::FileSpec(*rhs.m_opaque_ap)) -{ -} - -SBFileSpec::SBFileSpec (const lldb_private::FileSpec& fspec) : - m_opaque_ap(new lldb_private::FileSpec(fspec)) -{ -} +SBFileSpec::SBFileSpec(const lldb_private::FileSpec &fspec) + : m_opaque_ap(new lldb_private::FileSpec(fspec)) {} // Deprecated!!! -SBFileSpec::SBFileSpec (const char *path) : - m_opaque_ap(new FileSpec (path, true)) -{ -} +SBFileSpec::SBFileSpec(const char *path) + : m_opaque_ap(new FileSpec(path, true)) {} -SBFileSpec::SBFileSpec (const char *path, bool resolve) : - m_opaque_ap(new FileSpec (path, resolve)) -{ -} +SBFileSpec::SBFileSpec(const char *path, bool resolve) + : m_opaque_ap(new FileSpec(path, resolve)) {} -SBFileSpec::~SBFileSpec () -{ -} +SBFileSpec::~SBFileSpec() {} -const SBFileSpec & -SBFileSpec::operator = (const SBFileSpec &rhs) -{ - if (this != &rhs) - *m_opaque_ap = *rhs.m_opaque_ap; - return *this; +const SBFileSpec &SBFileSpec::operator=(const SBFileSpec &rhs) { + if (this != &rhs) + *m_opaque_ap = *rhs.m_opaque_ap; + return *this; } -bool -SBFileSpec::IsValid() const -{ - return m_opaque_ap->operator bool(); -} +bool SBFileSpec::IsValid() const { return m_opaque_ap->operator bool(); } -bool -SBFileSpec::Exists () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBFileSpec::Exists() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool result = m_opaque_ap->Exists(); + bool result = m_opaque_ap->Exists(); - if (log) - log->Printf ("SBFileSpec(%p)::Exists () => %s", - static_cast(m_opaque_ap.get()), - (result ? "true" : "false")); + if (log) + log->Printf("SBFileSpec(%p)::Exists () => %s", + static_cast(m_opaque_ap.get()), + (result ? "true" : "false")); - return result; + return result; } -bool -SBFileSpec::ResolveExecutableLocation () -{ - return m_opaque_ap->ResolveExecutableLocation (); +bool SBFileSpec::ResolveExecutableLocation() { + return m_opaque_ap->ResolveExecutableLocation(); } -int -SBFileSpec::ResolvePath (const char *src_path, char *dst_path, size_t dst_len) -{ - llvm::SmallString<64> result(src_path); - lldb_private::FileSpec::Resolve (result); - ::snprintf(dst_path, dst_len, "%s", result.c_str()); - return std::min(dst_len-1, result.size()); +int SBFileSpec::ResolvePath(const char *src_path, char *dst_path, + size_t dst_len) { + llvm::SmallString<64> result(src_path); + lldb_private::FileSpec::Resolve(result); + ::snprintf(dst_path, dst_len, "%s", result.c_str()); + return std::min(dst_len - 1, result.size()); } -const char * -SBFileSpec::GetFilename() const -{ - const char *s = m_opaque_ap->GetFilename().AsCString(); +const char *SBFileSpec::GetFilename() const { + const char *s = m_opaque_ap->GetFilename().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (s) - log->Printf ("SBFileSpec(%p)::GetFilename () => \"%s\"", - static_cast(m_opaque_ap.get()), s); - else - log->Printf ("SBFileSpec(%p)::GetFilename () => NULL", - static_cast(m_opaque_ap.get())); - } - - return s; -} - -const char * -SBFileSpec::GetDirectory() const -{ - FileSpec directory{*m_opaque_ap}; - directory.GetFilename().Clear(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (directory) - log->Printf ("SBFileSpec(%p)::GetDirectory () => \"%s\"", - static_cast(m_opaque_ap.get()), directory.GetCString()); - else - log->Printf ("SBFileSpec(%p)::GetDirectory () => NULL", - static_cast(m_opaque_ap.get())); - } - return directory.GetCString(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (s) + log->Printf("SBFileSpec(%p)::GetFilename () => \"%s\"", + static_cast(m_opaque_ap.get()), s); + else + log->Printf("SBFileSpec(%p)::GetFilename () => NULL", + static_cast(m_opaque_ap.get())); + } + + return s; +} + +const char *SBFileSpec::GetDirectory() const { + FileSpec directory{*m_opaque_ap}; + directory.GetFilename().Clear(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (directory) + log->Printf("SBFileSpec(%p)::GetDirectory () => \"%s\"", + static_cast(m_opaque_ap.get()), + directory.GetCString()); + else + log->Printf("SBFileSpec(%p)::GetDirectory () => NULL", + static_cast(m_opaque_ap.get())); + } + return directory.GetCString(); } -void -SBFileSpec::SetFilename(const char *filename) -{ - if (filename && filename[0]) - m_opaque_ap->GetFilename().SetCString(filename); - else - m_opaque_ap->GetFilename().Clear(); +void SBFileSpec::SetFilename(const char *filename) { + if (filename && filename[0]) + m_opaque_ap->GetFilename().SetCString(filename); + else + m_opaque_ap->GetFilename().Clear(); } -void -SBFileSpec::SetDirectory(const char *directory) -{ - if (directory && directory[0]) - m_opaque_ap->GetDirectory().SetCString(directory); - else - m_opaque_ap->GetDirectory().Clear(); +void SBFileSpec::SetDirectory(const char *directory) { + if (directory && directory[0]) + m_opaque_ap->GetDirectory().SetCString(directory); + else + m_opaque_ap->GetDirectory().Clear(); } -uint32_t -SBFileSpec::GetPath (char *dst_path, size_t dst_len) const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +uint32_t SBFileSpec::GetPath(char *dst_path, size_t dst_len) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - uint32_t result = m_opaque_ap->GetPath (dst_path, dst_len); + uint32_t result = m_opaque_ap->GetPath(dst_path, dst_len); - if (log) - log->Printf ("SBFileSpec(%p)::GetPath (dst_path=\"%.*s\", dst_len=%" PRIu64 ") => %u", - static_cast(m_opaque_ap.get()), result, dst_path, - static_cast(dst_len), result); + if (log) + log->Printf("SBFileSpec(%p)::GetPath (dst_path=\"%.*s\", dst_len=%" PRIu64 + ") => %u", + static_cast(m_opaque_ap.get()), result, dst_path, + static_cast(dst_len), result); - if (result == 0 && dst_path && dst_len > 0) - *dst_path = '\0'; - return result; + if (result == 0 && dst_path && dst_len > 0) + *dst_path = '\0'; + return result; } - -const lldb_private::FileSpec * -SBFileSpec::operator->() const -{ - return m_opaque_ap.get(); +const lldb_private::FileSpec *SBFileSpec::operator->() const { + return m_opaque_ap.get(); } -const lldb_private::FileSpec * -SBFileSpec::get() const -{ - return m_opaque_ap.get(); +const lldb_private::FileSpec *SBFileSpec::get() const { + return m_opaque_ap.get(); } - -const lldb_private::FileSpec & -SBFileSpec::operator*() const -{ - return *m_opaque_ap.get(); +const lldb_private::FileSpec &SBFileSpec::operator*() const { + return *m_opaque_ap.get(); } -const lldb_private::FileSpec & -SBFileSpec::ref() const -{ - return *m_opaque_ap.get(); +const lldb_private::FileSpec &SBFileSpec::ref() const { + return *m_opaque_ap.get(); } - -void -SBFileSpec::SetFileSpec (const lldb_private::FileSpec& fs) -{ - *m_opaque_ap = fs; +void SBFileSpec::SetFileSpec(const lldb_private::FileSpec &fs) { + *m_opaque_ap = fs; } -bool -SBFileSpec::GetDescription (SBStream &description) const -{ - Stream &strm = description.ref(); - char path[PATH_MAX]; - if (m_opaque_ap->GetPath(path, sizeof(path))) - strm.PutCString (path); - return true; +bool SBFileSpec::GetDescription(SBStream &description) const { + Stream &strm = description.ref(); + char path[PATH_MAX]; + if (m_opaque_ap->GetPath(path, sizeof(path))) + strm.PutCString(path); + return true; } -void -SBFileSpec::AppendPathComponent (const char *fn) -{ - m_opaque_ap->AppendPathComponent (fn); +void SBFileSpec::AppendPathComponent(const char *fn) { + m_opaque_ap->AppendPathComponent(fn); } diff --git a/lldb/source/API/SBFileSpecList.cpp b/lldb/source/API/SBFileSpecList.cpp index a457a754f0d..9e157ea201d 100644 --- a/lldb/source/API/SBFileSpecList.cpp +++ b/lldb/source/API/SBFileSpecList.cpp @@ -1,4 +1,5 @@ -//===-- SBFileSpecListList.cpp ------------------------------------------*- C++ -*-===// +//===-- SBFileSpecListList.cpp ------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -20,124 +21,83 @@ using namespace lldb; using namespace lldb_private; +SBFileSpecList::SBFileSpecList() : m_opaque_ap(new FileSpecList()) {} +SBFileSpecList::SBFileSpecList(const SBFileSpecList &rhs) : m_opaque_ap() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBFileSpecList::SBFileSpecList () : - m_opaque_ap(new FileSpecList()) -{ -} - -SBFileSpecList::SBFileSpecList (const SBFileSpecList &rhs) : - m_opaque_ap() -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (rhs.m_opaque_ap.get()) - m_opaque_ap.reset (new FileSpecList (*(rhs.get()))); + if (rhs.m_opaque_ap.get()) + m_opaque_ap.reset(new FileSpecList(*(rhs.get()))); - if (log) - { - log->Printf ("SBFileSpecList::SBFileSpecList (const SBFileSpecList rhs.ap=%p) => SBFileSpecList(%p)", - static_cast(rhs.m_opaque_ap.get()), - static_cast(m_opaque_ap.get())); - } + if (log) { + log->Printf("SBFileSpecList::SBFileSpecList (const SBFileSpecList " + "rhs.ap=%p) => SBFileSpecList(%p)", + static_cast(rhs.m_opaque_ap.get()), + static_cast(m_opaque_ap.get())); + } } -SBFileSpecList::~SBFileSpecList () -{ -} +SBFileSpecList::~SBFileSpecList() {} -const SBFileSpecList & -SBFileSpecList::operator = (const SBFileSpecList &rhs) -{ - if (this != &rhs) - { - m_opaque_ap.reset (new lldb_private::FileSpecList(*(rhs.get()))); - } - return *this; +const SBFileSpecList &SBFileSpecList::operator=(const SBFileSpecList &rhs) { + if (this != &rhs) { + m_opaque_ap.reset(new lldb_private::FileSpecList(*(rhs.get()))); + } + return *this; } -uint32_t -SBFileSpecList::GetSize () const -{ - return m_opaque_ap->GetSize(); -} +uint32_t SBFileSpecList::GetSize() const { return m_opaque_ap->GetSize(); } -void -SBFileSpecList::Append (const SBFileSpec &sb_file) -{ - m_opaque_ap->Append (sb_file.ref()); +void SBFileSpecList::Append(const SBFileSpec &sb_file) { + m_opaque_ap->Append(sb_file.ref()); } -bool -SBFileSpecList::AppendIfUnique (const SBFileSpec &sb_file) -{ - return m_opaque_ap->AppendIfUnique (sb_file.ref()); +bool SBFileSpecList::AppendIfUnique(const SBFileSpec &sb_file) { + return m_opaque_ap->AppendIfUnique(sb_file.ref()); } -void -SBFileSpecList::Clear() -{ - m_opaque_ap->Clear(); -} +void SBFileSpecList::Clear() { m_opaque_ap->Clear(); } -uint32_t -SBFileSpecList::FindFileIndex (uint32_t idx, const SBFileSpec &sb_file, bool full) -{ - return m_opaque_ap->FindFileIndex (idx, sb_file.ref(), full); +uint32_t SBFileSpecList::FindFileIndex(uint32_t idx, const SBFileSpec &sb_file, + bool full) { + return m_opaque_ap->FindFileIndex(idx, sb_file.ref(), full); } -const SBFileSpec -SBFileSpecList::GetFileSpecAtIndex (uint32_t idx) const -{ - SBFileSpec new_spec; - new_spec.SetFileSpec(m_opaque_ap->GetFileSpecAtIndex(idx)); - return new_spec; +const SBFileSpec SBFileSpecList::GetFileSpecAtIndex(uint32_t idx) const { + SBFileSpec new_spec; + new_spec.SetFileSpec(m_opaque_ap->GetFileSpecAtIndex(idx)); + return new_spec; } -const lldb_private::FileSpecList * -SBFileSpecList::operator->() const -{ - return m_opaque_ap.get(); +const lldb_private::FileSpecList *SBFileSpecList::operator->() const { + return m_opaque_ap.get(); } -const lldb_private::FileSpecList * -SBFileSpecList::get() const -{ - return m_opaque_ap.get(); +const lldb_private::FileSpecList *SBFileSpecList::get() const { + return m_opaque_ap.get(); } - -const lldb_private::FileSpecList & -SBFileSpecList::operator*() const -{ - return *m_opaque_ap.get(); +const lldb_private::FileSpecList &SBFileSpecList::operator*() const { + return *m_opaque_ap.get(); } -const lldb_private::FileSpecList & -SBFileSpecList::ref() const -{ - return *m_opaque_ap.get(); +const lldb_private::FileSpecList &SBFileSpecList::ref() const { + return *m_opaque_ap.get(); } -bool -SBFileSpecList::GetDescription (SBStream &description) const -{ - Stream &strm = description.ref(); - - if (m_opaque_ap.get()) - { - uint32_t num_files = m_opaque_ap->GetSize(); - strm.Printf ("%d files: ", num_files); - for (uint32_t i = 0; i < num_files; i++) - { - char path[PATH_MAX]; - if (m_opaque_ap->GetFileSpecAtIndex(i).GetPath(path, sizeof(path))) - strm.Printf ("\n %s", path); - } +bool SBFileSpecList::GetDescription(SBStream &description) const { + Stream &strm = description.ref(); + + if (m_opaque_ap.get()) { + uint32_t num_files = m_opaque_ap->GetSize(); + strm.Printf("%d files: ", num_files); + for (uint32_t i = 0; i < num_files; i++) { + char path[PATH_MAX]; + if (m_opaque_ap->GetFileSpecAtIndex(i).GetPath(path, sizeof(path))) + strm.Printf("\n %s", path); } - else - strm.PutCString ("No value"); - - return true; + } else + strm.PutCString("No value"); + + return true; } diff --git a/lldb/source/API/SBFrame.cpp b/lldb/source/API/SBFrame.cpp index 38bbfb8675f..31ac0a78eb1 100644 --- a/lldb/source/API/SBFrame.cpp +++ b/lldb/source/API/SBFrame.cpp @@ -19,6 +19,7 @@ #include "lldb/lldb-types.h" +#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Core/Address.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/Log.h" @@ -26,1116 +27,911 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Core/ValueObjectRegister.h" #include "lldb/Core/ValueObjectVariable.h" -#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Expression/UserExpression.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/Block.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/SymbolContext.h" -#include "lldb/Symbol/VariableList.h" #include "lldb/Symbol/Variable.h" +#include "lldb/Symbol/VariableList.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Target/Target.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/StackID.h" +#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" -#include "lldb/API/SBDebugger.h" -#include "lldb/API/SBValue.h" #include "lldb/API/SBAddress.h" +#include "lldb/API/SBDebugger.h" #include "lldb/API/SBExpressionOptions.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBSymbolContext.h" #include "lldb/API/SBThread.h" +#include "lldb/API/SBValue.h" #include "lldb/API/SBVariablesOptions.h" using namespace lldb; using namespace lldb_private; -SBFrame::SBFrame () : - m_opaque_sp (new ExecutionContextRef()) -{ -} +SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) {} -SBFrame::SBFrame (const StackFrameSP &lldb_object_sp) : - m_opaque_sp (new ExecutionContextRef (lldb_object_sp)) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBFrame::SBFrame(const StackFrameSP &lldb_object_sp) + : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - GetDescription (sstr); - log->Printf ("SBFrame::SBFrame (sp=%p) => SBFrame(%p): %s", - static_cast(lldb_object_sp.get()), - static_cast(lldb_object_sp.get()), sstr.GetData()); - } + if (log) { + SBStream sstr; + GetDescription(sstr); + log->Printf("SBFrame::SBFrame (sp=%p) => SBFrame(%p): %s", + static_cast(lldb_object_sp.get()), + static_cast(lldb_object_sp.get()), sstr.GetData()); + } } -SBFrame::SBFrame(const SBFrame &rhs) : - m_opaque_sp (new ExecutionContextRef (*rhs.m_opaque_sp)) -{ -} +SBFrame::SBFrame(const SBFrame &rhs) + : m_opaque_sp(new ExecutionContextRef(*rhs.m_opaque_sp)) {} SBFrame::~SBFrame() = default; -const SBFrame & -SBFrame::operator = (const SBFrame &rhs) -{ - if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; +const SBFrame &SBFrame::operator=(const SBFrame &rhs) { + if (this != &rhs) + *m_opaque_sp = *rhs.m_opaque_sp; + return *this; } -StackFrameSP -SBFrame::GetFrameSP() const -{ - return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP()); +StackFrameSP SBFrame::GetFrameSP() const { + return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP()); } -void -SBFrame::SetFrameSP (const StackFrameSP &lldb_object_sp) -{ - return m_opaque_sp->SetFrameSP(lldb_object_sp); +void SBFrame::SetFrameSP(const StackFrameSP &lldb_object_sp) { + return m_opaque_sp->SetFrameSP(lldb_object_sp); } -bool -SBFrame::IsValid() const -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - return GetFrameSP().get() != nullptr; - } - - // Without a target & process we can't have a valid stack frame. - return false; +bool SBFrame::IsValid() const { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) + return GetFrameSP().get() != nullptr; + } + + // Without a target & process we can't have a valid stack frame. + return false; } -SBSymbolContext -SBFrame::GetSymbolContext (uint32_t resolve_scope) const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBSymbolContext sb_sym_ctx; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_sym_ctx.SetSymbolContext(&frame->GetSymbolContext (resolve_scope)); - } - else - { - if (log) - log->Printf ("SBFrame::GetVariables () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetSymbolContext () => error: process is running"); - } +SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBSymbolContext sb_sym_ctx; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_sym_ctx.SetSymbolContext(&frame->GetSymbolContext(resolve_scope)); + } else { + if (log) + log->Printf("SBFrame::GetVariables () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf( + "SBFrame::GetSymbolContext () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetSymbolContext (resolve_scope=0x%8.8x) => SBSymbolContext(%p)", - static_cast(frame), resolve_scope, - static_cast(sb_sym_ctx.get())); + if (log) + log->Printf("SBFrame(%p)::GetSymbolContext (resolve_scope=0x%8.8x) => " + "SBSymbolContext(%p)", + static_cast(frame), resolve_scope, + static_cast(sb_sym_ctx.get())); - return sb_sym_ctx; + return sb_sym_ctx; } -SBModule -SBFrame::GetModule () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBModule sb_module; - ModuleSP module_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - module_sp = frame->GetSymbolContext (eSymbolContextModule).module_sp; - sb_module.SetSP (module_sp); - } - else - { - if (log) - log->Printf ("SBFrame::GetModule () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetModule () => error: process is running"); - } +SBModule SBFrame::GetModule() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBModule sb_module; + ModuleSP module_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp; + sb_module.SetSP(module_sp); + } else { + if (log) + log->Printf("SBFrame::GetModule () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetModule () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetModule () => SBModule(%p)", - static_cast(frame), - static_cast(module_sp.get())); + if (log) + log->Printf("SBFrame(%p)::GetModule () => SBModule(%p)", + static_cast(frame), + static_cast(module_sp.get())); - return sb_module; + return sb_module; } -SBCompileUnit -SBFrame::GetCompileUnit () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBCompileUnit sb_comp_unit; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_comp_unit.reset (frame->GetSymbolContext (eSymbolContextCompUnit).comp_unit); - } - else - { - if (log) - log->Printf ("SBFrame::GetCompileUnit () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetCompileUnit () => error: process is running"); - } +SBCompileUnit SBFrame::GetCompileUnit() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBCompileUnit sb_comp_unit; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_comp_unit.reset( + frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit); + } else { + if (log) + log->Printf("SBFrame::GetCompileUnit () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetCompileUnit () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetCompileUnit () => SBCompileUnit(%p)", - static_cast(frame), - static_cast(sb_comp_unit.get())); + } + if (log) + log->Printf("SBFrame(%p)::GetCompileUnit () => SBCompileUnit(%p)", + static_cast(frame), + static_cast(sb_comp_unit.get())); - return sb_comp_unit; + return sb_comp_unit; } -SBFunction -SBFrame::GetFunction () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBFunction sb_function; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_function.reset(frame->GetSymbolContext (eSymbolContextFunction).function); - } - else - { - if (log) - log->Printf ("SBFrame::GetFunction () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetFunction () => error: process is running"); - } +SBFunction SBFrame::GetFunction() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBFunction sb_function; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_function.reset( + frame->GetSymbolContext(eSymbolContextFunction).function); + } else { + if (log) + log->Printf("SBFrame::GetFunction () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetFunction () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetFunction () => SBFunction(%p)", - static_cast(frame), - static_cast(sb_function.get())); + } + if (log) + log->Printf("SBFrame(%p)::GetFunction () => SBFunction(%p)", + static_cast(frame), + static_cast(sb_function.get())); - return sb_function; + return sb_function; } -SBSymbol -SBFrame::GetSymbol () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBSymbol sb_symbol; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_symbol.reset(frame->GetSymbolContext (eSymbolContextSymbol).symbol); - } - else - { - if (log) - log->Printf ("SBFrame::GetSymbol () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetSymbol () => error: process is running"); - } +SBSymbol SBFrame::GetSymbol() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBSymbol sb_symbol; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol); + } else { + if (log) + log->Printf("SBFrame::GetSymbol () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetSymbol () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetSymbol () => SBSymbol(%p)", - static_cast(frame), - static_cast(sb_symbol.get())); - return sb_symbol; + } + if (log) + log->Printf("SBFrame(%p)::GetSymbol () => SBSymbol(%p)", + static_cast(frame), + static_cast(sb_symbol.get())); + return sb_symbol; } -SBBlock -SBFrame::GetBlock () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBBlock sb_block; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_block.SetPtr (frame->GetSymbolContext (eSymbolContextBlock).block); - } - else - { - if (log) - log->Printf ("SBFrame::GetBlock () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame(%p)::GetBlock () => error: process is running", - static_cast(frame)); - } +SBBlock SBFrame::GetBlock() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBBlock sb_block; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block); + } else { + if (log) + log->Printf("SBFrame::GetBlock () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame(%p)::GetBlock () => error: process is running", + static_cast(frame)); } - if (log) - log->Printf ("SBFrame(%p)::GetBlock () => SBBlock(%p)", - static_cast(frame), - static_cast(sb_block.GetPtr())); - return sb_block; + } + if (log) + log->Printf("SBFrame(%p)::GetBlock () => SBBlock(%p)", + static_cast(frame), + static_cast(sb_block.GetPtr())); + return sb_block; } -SBBlock -SBFrame::GetFrameBlock () const -{ - SBBlock sb_block; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_block.SetPtr(frame->GetFrameBlock ()); - } - else - { - if (log) - log->Printf ("SBFrame::GetFrameBlock () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetFrameBlock () => error: process is running"); - } +SBBlock SBFrame::GetFrameBlock() const { + SBBlock sb_block; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_block.SetPtr(frame->GetFrameBlock()); + } else { + if (log) + log->Printf("SBFrame::GetFrameBlock () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetFrameBlock () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetFrameBlock () => SBBlock(%p)", - static_cast(frame), - static_cast(sb_block.GetPtr())); - return sb_block; + } + if (log) + log->Printf("SBFrame(%p)::GetFrameBlock () => SBBlock(%p)", + static_cast(frame), + static_cast(sb_block.GetPtr())); + return sb_block; } -SBLineEntry -SBFrame::GetLineEntry () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBLineEntry sb_line_entry; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_line_entry.SetLineEntry (frame->GetSymbolContext (eSymbolContextLineEntry).line_entry); - } - else - { - if (log) - log->Printf ("SBFrame::GetLineEntry () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetLineEntry () => error: process is running"); - } +SBLineEntry SBFrame::GetLineEntry() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBLineEntry sb_line_entry; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_line_entry.SetLineEntry( + frame->GetSymbolContext(eSymbolContextLineEntry).line_entry); + } else { + if (log) + log->Printf("SBFrame::GetLineEntry () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetLineEntry () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetLineEntry () => SBLineEntry(%p)", - static_cast(frame), - static_cast(sb_line_entry.get())); - return sb_line_entry; + } + if (log) + log->Printf("SBFrame(%p)::GetLineEntry () => SBLineEntry(%p)", + static_cast(frame), + static_cast(sb_line_entry.get())); + return sb_line_entry; } -uint32_t -SBFrame::GetFrameID () const -{ - uint32_t frame_idx = UINT32_MAX; +uint32_t SBFrame::GetFrameID() const { + uint32_t frame_idx = UINT32_MAX; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame) - frame_idx = frame->GetFrameIndex (); + StackFrame *frame = exe_ctx.GetFramePtr(); + if (frame) + frame_idx = frame->GetFrameIndex(); - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBFrame(%p)::GetFrameID () => %u", - static_cast(frame), frame_idx); - return frame_idx; + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBFrame(%p)::GetFrameID () => %u", static_cast(frame), + frame_idx); + return frame_idx; } -lldb::addr_t -SBFrame::GetCFA () const -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); +lldb::addr_t SBFrame::GetCFA() const { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - StackFrame *frame = exe_ctx.GetFramePtr(); - if (frame) - return frame->GetStackID().GetCallFrameAddress(); - return LLDB_INVALID_ADDRESS; + StackFrame *frame = exe_ctx.GetFramePtr(); + if (frame) + return frame->GetStackID().GetCallFrameAddress(); + return LLDB_INVALID_ADDRESS; } -addr_t -SBFrame::GetPC () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - addr_t addr = LLDB_INVALID_ADDRESS; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress (target, eAddressClassCode); - } - else - { - if (log) - log->Printf ("SBFrame::GetPC () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetPC () => error: process is running"); - } +addr_t SBFrame::GetPC() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress( + target, eAddressClassCode); + } else { + if (log) + log->Printf("SBFrame::GetPC () => error: could not reconstruct frame " + "object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetPC () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetPC () => 0x%" PRIx64, - static_cast(frame), addr); + if (log) + log->Printf("SBFrame(%p)::GetPC () => 0x%" PRIx64, + static_cast(frame), addr); - return addr; + return addr; } -bool -SBFrame::SetPC (addr_t new_pc) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool ret_val = false; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - ret_val = frame->GetRegisterContext()->SetPC (new_pc); - } - else - { - if (log) - log->Printf ("SBFrame::SetPC () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::SetPC () => error: process is running"); - } +bool SBFrame::SetPC(addr_t new_pc) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool ret_val = false; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + ret_val = frame->GetRegisterContext()->SetPC(new_pc); + } else { + if (log) + log->Printf("SBFrame::SetPC () => error: could not reconstruct frame " + "object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::SetPC () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::SetPC (new_pc=0x%" PRIx64 ") => %i", - static_cast(frame), new_pc, ret_val); + if (log) + log->Printf("SBFrame(%p)::SetPC (new_pc=0x%" PRIx64 ") => %i", + static_cast(frame), new_pc, ret_val); - return ret_val; + return ret_val; } -addr_t -SBFrame::GetSP () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - addr_t addr = LLDB_INVALID_ADDRESS; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - addr = frame->GetRegisterContext()->GetSP(); - } - else - { - if (log) - log->Printf ("SBFrame::GetSP () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetSP () => error: process is running"); - } +addr_t SBFrame::GetSP() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + addr = frame->GetRegisterContext()->GetSP(); + } else { + if (log) + log->Printf("SBFrame::GetSP () => error: could not reconstruct frame " + "object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetSP () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetSP () => 0x%" PRIx64, - static_cast(frame), addr); + } + if (log) + log->Printf("SBFrame(%p)::GetSP () => 0x%" PRIx64, + static_cast(frame), addr); - return addr; + return addr; } -addr_t -SBFrame::GetFP () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - addr_t addr = LLDB_INVALID_ADDRESS; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - addr = frame->GetRegisterContext()->GetFP(); - } - else - { - if (log) - log->Printf ("SBFrame::GetFP () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetFP () => error: process is running"); - } +addr_t SBFrame::GetFP() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + addr_t addr = LLDB_INVALID_ADDRESS; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + addr = frame->GetRegisterContext()->GetFP(); + } else { + if (log) + log->Printf("SBFrame::GetFP () => error: could not reconstruct frame " + "object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetFP () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetFP () => 0x%" PRIx64, - static_cast(frame), addr); - return addr; + if (log) + log->Printf("SBFrame(%p)::GetFP () => 0x%" PRIx64, + static_cast(frame), addr); + return addr; } -SBAddress -SBFrame::GetPCAddress () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBAddress sb_addr; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - sb_addr.SetAddress (&frame->GetFrameCodeAddress()); - } - else - { - if (log) - log->Printf ("SBFrame::GetPCAddress () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetPCAddress () => error: process is running"); - } +SBAddress SBFrame::GetPCAddress() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBAddress sb_addr; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + sb_addr.SetAddress(&frame->GetFrameCodeAddress()); + } else { + if (log) + log->Printf("SBFrame::GetPCAddress () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetPCAddress () => error: process is running"); } - if (log) - log->Printf ("SBFrame(%p)::GetPCAddress () => SBAddress(%p)", - static_cast(frame), - static_cast(sb_addr.get())); - return sb_addr; + } + if (log) + log->Printf("SBFrame(%p)::GetPCAddress () => SBAddress(%p)", + static_cast(frame), static_cast(sb_addr.get())); + return sb_addr; } -void -SBFrame::Clear() -{ - m_opaque_sp->Clear(); +void SBFrame::Clear() { m_opaque_sp->Clear(); } + +lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) { + SBValue sb_value; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + sb_value = GetValueForVariablePath(var_path, use_dynamic); + } + return sb_value; } -lldb::SBValue -SBFrame::GetValueForVariablePath (const char *var_path) -{ - SBValue sb_value; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (frame && target) - { - lldb::DynamicValueType use_dynamic = frame->CalculateTarget()->GetPreferDynamicValue(); - sb_value = GetValueForVariablePath (var_path, use_dynamic); - } +lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path, + DynamicValueType use_dynamic) { + SBValue sb_value; + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (var_path == nullptr || var_path[0] == '\0') { + if (log) + log->Printf( + "SBFrame::GetValueForVariablePath called with empty variable path."); return sb_value; -} - -lldb::SBValue -SBFrame::GetValueForVariablePath (const char *var_path, DynamicValueType use_dynamic) -{ - SBValue sb_value; - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (var_path == nullptr || var_path[0] == '\0') - { + } + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + VariableSP var_sp; + Error error; + ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath( + var_path, eNoDynamicValues, + StackFrame::eExpressionPathOptionCheckPtrVsMember | + StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, + var_sp, error)); + sb_value.SetSP(value_sp, use_dynamic); + } else { if (log) - log->Printf ("SBFrame::GetValueForVariablePath called with empty variable path."); - return sb_value; + log->Printf("SBFrame::GetValueForVariablePath () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf( + "SBFrame::GetValueForVariablePath () => error: process is running"); } - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - VariableSP var_sp; - Error error; - ValueObjectSP value_sp (frame->GetValueForVariableExpressionPath (var_path, - eNoDynamicValues, - StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, - var_sp, - error)); - sb_value.SetSP(value_sp, use_dynamic); - } - else - { - if (log) - log->Printf ("SBFrame::GetValueForVariablePath () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetValueForVariablePath () => error: process is running"); - } - } - return sb_value; + } + return sb_value; } -SBValue -SBFrame::FindVariable (const char *name) -{ - SBValue value; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (frame && target) - { - lldb::DynamicValueType use_dynamic = frame->CalculateTarget()->GetPreferDynamicValue(); - value = FindVariable (name, use_dynamic); - } - return value; +SBValue SBFrame::FindVariable(const char *name) { + SBValue value; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + value = FindVariable(name, use_dynamic); + } + return value; } -SBValue -SBFrame::FindVariable (const char *name, lldb::DynamicValueType use_dynamic) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - VariableSP var_sp; - SBValue sb_value; - - if (name == nullptr || name[0] == '\0') - { - if (log) - log->Printf ("SBFrame::FindVariable called with empty name"); - return sb_value; - } - - ValueObjectSP value_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - VariableList variable_list; - SymbolContext sc (frame->GetSymbolContext (eSymbolContextBlock)); - - if (sc.block) - { - const bool can_create = true; - const bool get_parent_variables = true; - const bool stop_if_block_is_inlined_function = true; - - if (sc.block->AppendVariables (can_create, - get_parent_variables, - stop_if_block_is_inlined_function, - [frame](Variable* v) { return v->IsInScope(frame); }, - &variable_list)) - { - var_sp = variable_list.FindVariable (ConstString(name)); - } - } +SBValue SBFrame::FindVariable(const char *name, + lldb::DynamicValueType use_dynamic) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + VariableSP var_sp; + SBValue sb_value; - if (var_sp) - { - value_sp = frame->GetValueObjectForFrameVariable(var_sp, eNoDynamicValues); - sb_value.SetSP(value_sp, use_dynamic); - } - } - else - { - if (log) - log->Printf ("SBFrame::FindVariable () => error: could not reconstruct frame object for this SBFrame."); - } + if (name == nullptr || name[0] == '\0') { + if (log) + log->Printf("SBFrame::FindVariable called with empty name"); + return sb_value; + } + + ValueObjectSP value_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + VariableList variable_list; + SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock)); + + if (sc.block) { + const bool can_create = true; + const bool get_parent_variables = true; + const bool stop_if_block_is_inlined_function = true; + + if (sc.block->AppendVariables( + can_create, get_parent_variables, + stop_if_block_is_inlined_function, + [frame](Variable *v) { return v->IsInScope(frame); }, + &variable_list)) { + var_sp = variable_list.FindVariable(ConstString(name)); + } } - else - { - if (log) - log->Printf ("SBFrame::FindVariable () => error: process is running"); + + if (var_sp) { + value_sp = + frame->GetValueObjectForFrameVariable(var_sp, eNoDynamicValues); + sb_value.SetSP(value_sp, use_dynamic); } + } else { + if (log) + log->Printf("SBFrame::FindVariable () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::FindVariable () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::FindVariable (name=\"%s\") => SBValue(%p)", - static_cast(frame), name, - static_cast(value_sp.get())); + if (log) + log->Printf("SBFrame(%p)::FindVariable (name=\"%s\") => SBValue(%p)", + static_cast(frame), name, + static_cast(value_sp.get())); - return sb_value; + return sb_value; } -SBValue -SBFrame::FindValue (const char *name, ValueType value_type) -{ - SBValue value; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (frame && target) - { - lldb::DynamicValueType use_dynamic = frame->CalculateTarget()->GetPreferDynamicValue(); - value = FindValue (name, value_type, use_dynamic); - } - return value; +SBValue SBFrame::FindValue(const char *name, ValueType value_type) { + SBValue value; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + value = FindValue(name, value_type, use_dynamic); + } + return value; } -SBValue -SBFrame::FindValue (const char *name, ValueType value_type, lldb::DynamicValueType use_dynamic) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBValue sb_value; - - if (name == nullptr || name[0] == '\0') - { - if (log) - log->Printf ("SBFrame::FindValue called with empty name."); - return sb_value; - } +SBValue SBFrame::FindValue(const char *name, ValueType value_type, + lldb::DynamicValueType use_dynamic) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBValue sb_value; - ValueObjectSP value_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) + if (name == nullptr || name[0] == '\0') { + if (log) + log->Printf("SBFrame::FindValue called with empty name."); + return sb_value; + } + + ValueObjectSP value_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + VariableList variable_list; + + switch (value_type) { + case eValueTypeVariableGlobal: // global variable + case eValueTypeVariableStatic: // static variable + case eValueTypeVariableArgument: // function argument variables + case eValueTypeVariableLocal: // function local variables + case eValueTypeVariableThreadLocal: // thread local variables { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - VariableList variable_list; - - switch (value_type) - { - case eValueTypeVariableGlobal: // global variable - case eValueTypeVariableStatic: // static variable - case eValueTypeVariableArgument: // function argument variables - case eValueTypeVariableLocal: // function local variables - case eValueTypeVariableThreadLocal: // thread local variables - { - SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock)); - - const bool can_create = true; - const bool get_parent_variables = true; - const bool stop_if_block_is_inlined_function = true; - - if (sc.block) - sc.block->AppendVariables(can_create, get_parent_variables, stop_if_block_is_inlined_function, - [frame](Variable *v) { return v->IsInScope(frame); }, &variable_list); - if (value_type == eValueTypeVariableGlobal) - { - const bool get_file_globals = true; - VariableList *frame_vars = frame->GetVariableList(get_file_globals); - if (frame_vars) - frame_vars->AppendVariablesIfUnique(variable_list); - } - ConstString const_name(name); - VariableSP variable_sp(variable_list.FindVariable(const_name, value_type)); - if (variable_sp) - { - value_sp = frame->GetValueObjectForFrameVariable(variable_sp, eNoDynamicValues); - sb_value.SetSP(value_sp, use_dynamic); - } - } - break; - - case eValueTypeRegister: // stack frame register value - { - RegisterContextSP reg_ctx (frame->GetRegisterContext()); - if (reg_ctx) - { - const uint32_t num_regs = reg_ctx->GetRegisterCount(); - for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) - { - const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_idx); - if (reg_info && - ((reg_info->name && strcasecmp (reg_info->name, name) == 0) || - (reg_info->alt_name && strcasecmp (reg_info->alt_name, name) == 0))) - { - value_sp = ValueObjectRegister::Create (frame, reg_ctx, reg_idx); - sb_value.SetSP (value_sp); - break; - } - } - } - } - break; - - case eValueTypeRegisterSet: // A collection of stack frame register values - { - RegisterContextSP reg_ctx (frame->GetRegisterContext()); - if (reg_ctx) - { - const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); - for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) - { - const RegisterSet *reg_set = reg_ctx->GetRegisterSet (set_idx); - if (reg_set && - ((reg_set->name && strcasecmp (reg_set->name, name) == 0) || - (reg_set->short_name && strcasecmp (reg_set->short_name, name) == 0))) - { - value_sp = ValueObjectRegisterSet::Create (frame, reg_ctx, set_idx); - sb_value.SetSP (value_sp); - break; - } - } - } - } - break; - - case eValueTypeConstResult: // constant result variables - { - ConstString const_name(name); - ExpressionVariableSP expr_var_sp (target->GetPersistentVariable (const_name)); - if (expr_var_sp) - { - value_sp = expr_var_sp->GetValueObject(); - sb_value.SetSP (value_sp, use_dynamic); - } - } - break; - - default: - break; - } + SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock)); + + const bool can_create = true; + const bool get_parent_variables = true; + const bool stop_if_block_is_inlined_function = true; + + if (sc.block) + sc.block->AppendVariables( + can_create, get_parent_variables, + stop_if_block_is_inlined_function, + [frame](Variable *v) { return v->IsInScope(frame); }, + &variable_list); + if (value_type == eValueTypeVariableGlobal) { + const bool get_file_globals = true; + VariableList *frame_vars = frame->GetVariableList(get_file_globals); + if (frame_vars) + frame_vars->AppendVariablesIfUnique(variable_list); + } + ConstString const_name(name); + VariableSP variable_sp( + variable_list.FindVariable(const_name, value_type)); + if (variable_sp) { + value_sp = frame->GetValueObjectForFrameVariable(variable_sp, + eNoDynamicValues); + sb_value.SetSP(value_sp, use_dynamic); + } + } break; + + case eValueTypeRegister: // stack frame register value + { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_regs = reg_ctx->GetRegisterCount(); + for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) { + const RegisterInfo *reg_info = + reg_ctx->GetRegisterInfoAtIndex(reg_idx); + if (reg_info && + ((reg_info->name && strcasecmp(reg_info->name, name) == 0) || + (reg_info->alt_name && + strcasecmp(reg_info->alt_name, name) == 0))) { + value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_idx); + sb_value.SetSP(value_sp); + break; + } } - else - { - if (log) - log->Printf ("SBFrame::FindValue () => error: could not reconstruct frame object for this SBFrame."); + } + } break; + + case eValueTypeRegisterSet: // A collection of stack frame register + // values + { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); + for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { + const RegisterSet *reg_set = reg_ctx->GetRegisterSet(set_idx); + if (reg_set && + ((reg_set->name && strcasecmp(reg_set->name, name) == 0) || + (reg_set->short_name && + strcasecmp(reg_set->short_name, name) == 0))) { + value_sp = + ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx); + sb_value.SetSP(value_sp); + break; + } } - } - else + } + } break; + + case eValueTypeConstResult: // constant result variables { - if (log) - log->Printf ("SBFrame::FindValue () => error: process is running"); + ConstString const_name(name); + ExpressionVariableSP expr_var_sp( + target->GetPersistentVariable(const_name)); + if (expr_var_sp) { + value_sp = expr_var_sp->GetValueObject(); + sb_value.SetSP(value_sp, use_dynamic); + } + } break; + + default: + break; } + } else { + if (log) + log->Printf("SBFrame::FindValue () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::FindValue () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::FindVariableInScope (name=\"%s\", value_type=%i) => SBValue(%p)", - static_cast(frame), name, value_type, - static_cast(value_sp.get())); + if (log) + log->Printf("SBFrame(%p)::FindVariableInScope (name=\"%s\", value_type=%i) " + "=> SBValue(%p)", + static_cast(frame), name, value_type, + static_cast(value_sp.get())); - return sb_value; + return sb_value; } -bool -SBFrame::IsEqual (const SBFrame &that) const -{ - lldb::StackFrameSP this_sp = GetFrameSP(); - lldb::StackFrameSP that_sp = that.GetFrameSP(); - return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID()); +bool SBFrame::IsEqual(const SBFrame &that) const { + lldb::StackFrameSP this_sp = GetFrameSP(); + lldb::StackFrameSP that_sp = that.GetFrameSP(); + return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID()); } -bool -SBFrame::operator == (const SBFrame &rhs) const -{ - return IsEqual(rhs); -} +bool SBFrame::operator==(const SBFrame &rhs) const { return IsEqual(rhs); } -bool -SBFrame::operator != (const SBFrame &rhs) const -{ - return !IsEqual(rhs); -} +bool SBFrame::operator!=(const SBFrame &rhs) const { return !IsEqual(rhs); } -SBThread -SBFrame::GetThread () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBThread SBFrame::GetThread() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - ThreadSP thread_sp (exe_ctx.GetThreadSP()); - SBThread sb_thread (thread_sp); + ThreadSP thread_sp(exe_ctx.GetThreadSP()); + SBThread sb_thread(thread_sp); - if (log) - { - SBStream sstr; - sb_thread.GetDescription (sstr); - log->Printf ("SBFrame(%p)::GetThread () => SBThread(%p): %s", - static_cast(exe_ctx.GetFramePtr()), - static_cast(thread_sp.get()), sstr.GetData()); - } + if (log) { + SBStream sstr; + sb_thread.GetDescription(sstr); + log->Printf("SBFrame(%p)::GetThread () => SBThread(%p): %s", + static_cast(exe_ctx.GetFramePtr()), + static_cast(thread_sp.get()), sstr.GetData()); + } - return sb_thread; + return sb_thread; } -const char * -SBFrame::Disassemble () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *disassembly = nullptr; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - disassembly = frame->Disassemble(); - } - else - { - if (log) - log->Printf ("SBFrame::Disassemble () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::Disassemble () => error: process is running"); - } +const char *SBFrame::Disassemble() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *disassembly = nullptr; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + disassembly = frame->Disassemble(); + } else { + if (log) + log->Printf("SBFrame::Disassemble () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::Disassemble () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::Disassemble () => %s", - static_cast(frame), disassembly); + if (log) + log->Printf("SBFrame(%p)::Disassemble () => %s", static_cast(frame), + disassembly); - return disassembly; + return disassembly; } -SBValueList -SBFrame::GetVariables (bool arguments, - bool locals, - bool statics, - bool in_scope_only) -{ - SBValueList value_list; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (frame && target) - { - lldb::DynamicValueType use_dynamic = frame->CalculateTarget()->GetPreferDynamicValue(); - const bool include_runtime_support_values = target ? target->GetDisplayRuntimeSupportValues() : false; - - SBVariablesOptions options; - options.SetIncludeArguments(arguments); - options.SetIncludeLocals(locals); - options.SetIncludeStatics(statics); - options.SetInScopeOnly(in_scope_only); - options.SetIncludeRuntimeSupportValues(include_runtime_support_values); - options.SetUseDynamic(use_dynamic); - - value_list = GetVariables (options); - } - return value_list; -} +SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics, + bool in_scope_only) { + SBValueList value_list; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { + lldb::DynamicValueType use_dynamic = + frame->CalculateTarget()->GetPreferDynamicValue(); + const bool include_runtime_support_values = + target ? target->GetDisplayRuntimeSupportValues() : false; -lldb::SBValueList -SBFrame::GetVariables (bool arguments, - bool locals, - bool statics, - bool in_scope_only, - lldb::DynamicValueType use_dynamic) -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - Target *target = exe_ctx.GetTargetPtr(); - const bool include_runtime_support_values = target ? target->GetDisplayRuntimeSupportValues() : false; SBVariablesOptions options; options.SetIncludeArguments(arguments); options.SetIncludeLocals(locals); @@ -1143,587 +939,533 @@ SBFrame::GetVariables (bool arguments, options.SetInScopeOnly(in_scope_only); options.SetIncludeRuntimeSupportValues(include_runtime_support_values); options.SetUseDynamic(use_dynamic); - return GetVariables(options); + + value_list = GetVariables(options); + } + return value_list; } -SBValueList -SBFrame::GetVariables (const lldb::SBVariablesOptions& options) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBValueList value_list; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - - const bool statics = options.GetIncludeStatics(); - const bool arguments = options.GetIncludeArguments(); - const bool locals = options.GetIncludeLocals(); - const bool in_scope_only = options.GetInScopeOnly(); - const bool include_runtime_support_values = options.GetIncludeRuntimeSupportValues(); - const lldb::DynamicValueType use_dynamic = options.GetUseDynamic(); - - if (log) - log->Printf ("SBFrame::GetVariables (arguments=%i, locals=%i, statics=%i, in_scope_only=%i runtime=%i dynamic=%i)", - arguments, locals, - statics, in_scope_only, - include_runtime_support_values, use_dynamic); - - std::set variable_set; - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - size_t i; - VariableList *variable_list = nullptr; - variable_list = frame->GetVariableList(true); - if (variable_list) - { - const size_t num_variables = variable_list->GetSize(); - if (num_variables) - { - for (i = 0; i < num_variables; ++i) - { - VariableSP variable_sp (variable_list->GetVariableAtIndex(i)); - if (variable_sp) - { - bool add_variable = false; - switch (variable_sp->GetScope()) - { - case eValueTypeVariableGlobal: - case eValueTypeVariableStatic: - case eValueTypeVariableThreadLocal: - add_variable = statics; - break; - - case eValueTypeVariableArgument: - add_variable = arguments; - break; - - case eValueTypeVariableLocal: - add_variable = locals; - break; - - default: - break; - } - if (add_variable) - { - // Only add variables once so we don't end up with duplicates - if (variable_set.find(variable_sp) == variable_set.end()) - variable_set.insert(variable_sp); - else - continue; - - if (in_scope_only && !variable_sp->IsInScope(frame)) - continue; - - ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable (variable_sp, eNoDynamicValues)); - - if (!include_runtime_support_values && - valobj_sp != nullptr && - valobj_sp->IsRuntimeSupportValue()) - continue; - - SBValue value_sb; - value_sb.SetSP(valobj_sp,use_dynamic); - value_list.Append(value_sb); - } - } - } - } +lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals, + bool statics, bool in_scope_only, + lldb::DynamicValueType use_dynamic) { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + const bool include_runtime_support_values = + target ? target->GetDisplayRuntimeSupportValues() : false; + SBVariablesOptions options; + options.SetIncludeArguments(arguments); + options.SetIncludeLocals(locals); + options.SetIncludeStatics(statics); + options.SetInScopeOnly(in_scope_only); + options.SetIncludeRuntimeSupportValues(include_runtime_support_values); + options.SetUseDynamic(use_dynamic); + return GetVariables(options); +} + +SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBValueList value_list; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + + const bool statics = options.GetIncludeStatics(); + const bool arguments = options.GetIncludeArguments(); + const bool locals = options.GetIncludeLocals(); + const bool in_scope_only = options.GetInScopeOnly(); + const bool include_runtime_support_values = + options.GetIncludeRuntimeSupportValues(); + const lldb::DynamicValueType use_dynamic = options.GetUseDynamic(); + + if (log) + log->Printf("SBFrame::GetVariables (arguments=%i, locals=%i, statics=%i, " + "in_scope_only=%i runtime=%i dynamic=%i)", + arguments, locals, statics, in_scope_only, + include_runtime_support_values, use_dynamic); + + std::set variable_set; + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + size_t i; + VariableList *variable_list = nullptr; + variable_list = frame->GetVariableList(true); + if (variable_list) { + const size_t num_variables = variable_list->GetSize(); + if (num_variables) { + for (i = 0; i < num_variables; ++i) { + VariableSP variable_sp(variable_list->GetVariableAtIndex(i)); + if (variable_sp) { + bool add_variable = false; + switch (variable_sp->GetScope()) { + case eValueTypeVariableGlobal: + case eValueTypeVariableStatic: + case eValueTypeVariableThreadLocal: + add_variable = statics; + break; + + case eValueTypeVariableArgument: + add_variable = arguments; + break; + + case eValueTypeVariableLocal: + add_variable = locals; + break; + + default: + break; } + if (add_variable) { + // Only add variables once so we don't end up with duplicates + if (variable_set.find(variable_sp) == variable_set.end()) + variable_set.insert(variable_sp); + else + continue; + + if (in_scope_only && !variable_sp->IsInScope(frame)) + continue; + + ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable( + variable_sp, eNoDynamicValues)); + + if (!include_runtime_support_values && valobj_sp != nullptr && + valobj_sp->IsRuntimeSupportValue()) + continue; + + SBValue value_sb; + value_sb.SetSP(valobj_sp, use_dynamic); + value_list.Append(value_sb); + } + } } - else - { - if (log) - log->Printf ("SBFrame::GetVariables () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetVariables () => error: process is running"); + } } + } else { + if (log) + log->Printf("SBFrame::GetVariables () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetVariables () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetVariables (...) => SBValueList(%p)", - static_cast(frame), - static_cast(value_list.opaque_ptr())); + if (log) + log->Printf("SBFrame(%p)::GetVariables (...) => SBValueList(%p)", + static_cast(frame), + static_cast(value_list.opaque_ptr())); - return value_list; + return value_list; } -SBValueList -SBFrame::GetRegisters () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBValueList value_list; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - RegisterContextSP reg_ctx (frame->GetRegisterContext()); - if (reg_ctx) - { - const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); - for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) - { - value_list.Append(ValueObjectRegisterSet::Create (frame, reg_ctx, set_idx)); - } - } - } - else - { - if (log) - log->Printf ("SBFrame::GetRegisters () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetRegisters () => error: process is running"); +SBValueList SBFrame::GetRegisters() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBValueList value_list; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_sets = reg_ctx->GetRegisterSetCount(); + for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) { + value_list.Append( + ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx)); + } } + } else { + if (log) + log->Printf("SBFrame::GetRegisters () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetRegisters () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::GetRegisters () => SBValueList(%p)", - static_cast(frame), - static_cast(value_list.opaque_ptr())); + if (log) + log->Printf("SBFrame(%p)::GetRegisters () => SBValueList(%p)", + static_cast(frame), + static_cast(value_list.opaque_ptr())); - return value_list; + return value_list; } -SBValue -SBFrame::FindRegister (const char *name) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBValue result; - ValueObjectSP value_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - RegisterContextSP reg_ctx (frame->GetRegisterContext()); - if (reg_ctx) - { - const uint32_t num_regs = reg_ctx->GetRegisterCount(); - for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) - { - const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_idx); - if (reg_info && - ((reg_info->name && strcasecmp (reg_info->name, name) == 0) || - (reg_info->alt_name && strcasecmp (reg_info->alt_name, name) == 0))) - { - value_sp = ValueObjectRegister::Create (frame, reg_ctx, reg_idx); - result.SetSP (value_sp); - break; - } - } - } +SBValue SBFrame::FindRegister(const char *name) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBValue result; + ValueObjectSP value_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + RegisterContextSP reg_ctx(frame->GetRegisterContext()); + if (reg_ctx) { + const uint32_t num_regs = reg_ctx->GetRegisterCount(); + for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) { + const RegisterInfo *reg_info = + reg_ctx->GetRegisterInfoAtIndex(reg_idx); + if (reg_info && + ((reg_info->name && strcasecmp(reg_info->name, name) == 0) || + (reg_info->alt_name && + strcasecmp(reg_info->alt_name, name) == 0))) { + value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_idx); + result.SetSP(value_sp); + break; } - else - { - if (log) - log->Printf ("SBFrame::FindRegister () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::FindRegister () => error: process is running"); + } } + } else { + if (log) + log->Printf("SBFrame::FindRegister () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::FindRegister () => error: process is running"); } + } - if (log) - log->Printf ("SBFrame(%p)::FindRegister () => SBValue(%p)", - static_cast(frame), - static_cast(value_sp.get())); + if (log) + log->Printf("SBFrame(%p)::FindRegister () => SBValue(%p)", + static_cast(frame), + static_cast(value_sp.get())); - return result; + return result; } -bool -SBFrame::GetDescription (SBStream &description) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - Stream &strm = description.ref(); - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - frame->DumpUsingSettingsFormat (&strm); - } - else - { - if (log) - log->Printf ("SBFrame::GetDescription () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetDescription () => error: process is running"); - } - +bool SBFrame::GetDescription(SBStream &description) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + Stream &strm = description.ref(); + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + frame->DumpUsingSettingsFormat(&strm); + } else { + if (log) + log->Printf("SBFrame::GetDescription () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetDescription () => error: process is running"); } - else - strm.PutCString ("No value"); - return true; -} + } else + strm.PutCString("No value"); -SBValue -SBFrame::EvaluateExpression (const char *expr) -{ - SBValue result; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (frame && target) - { - SBExpressionOptions options; - lldb::DynamicValueType fetch_dynamic_value = frame->CalculateTarget()->GetPreferDynamicValue(); - options.SetFetchDynamicValue (fetch_dynamic_value); - options.SetUnwindOnError (true); - options.SetIgnoreBreakpoints (true); - if (target->GetLanguage() != eLanguageTypeUnknown) - options.SetLanguage(target->GetLanguage()); - else - options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression (expr, options); - } - return result; + return true; } -SBValue -SBFrame::EvaluateExpression (const char *expr, lldb::DynamicValueType fetch_dynamic_value) -{ +SBValue SBFrame::EvaluateExpression(const char *expr) { + SBValue result; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (frame && target) { SBExpressionOptions options; - options.SetFetchDynamicValue (fetch_dynamic_value); - options.SetUnwindOnError (true); - options.SetIgnoreBreakpoints (true); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (target && target->GetLanguage() != eLanguageTypeUnknown) - options.SetLanguage(target->GetLanguage()); - else if (frame) - options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression (expr, options); + lldb::DynamicValueType fetch_dynamic_value = + frame->CalculateTarget()->GetPreferDynamicValue(); + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + if (target->GetLanguage() != eLanguageTypeUnknown) + options.SetLanguage(target->GetLanguage()); + else + options.SetLanguage(frame->GetLanguage()); + return EvaluateExpression(expr, options); + } + return result; } SBValue -SBFrame::EvaluateExpression (const char *expr, lldb::DynamicValueType fetch_dynamic_value, bool unwind_on_error) -{ - SBExpressionOptions options; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - options.SetFetchDynamicValue (fetch_dynamic_value); - options.SetUnwindOnError (unwind_on_error); - options.SetIgnoreBreakpoints (true); - StackFrame *frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); - if (target && target->GetLanguage() != eLanguageTypeUnknown) - options.SetLanguage(target->GetLanguage()); - else if (frame) - options.SetLanguage(frame->GetLanguage()); - return EvaluateExpression (expr, options); +SBFrame::EvaluateExpression(const char *expr, + lldb::DynamicValueType fetch_dynamic_value) { + SBExpressionOptions options; + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (target && target->GetLanguage() != eLanguageTypeUnknown) + options.SetLanguage(target->GetLanguage()); + else if (frame) + options.SetLanguage(frame->GetLanguage()); + return EvaluateExpression(expr, options); } -lldb::SBValue -SBFrame::EvaluateExpression (const char *expr, const SBExpressionOptions &options) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBValue SBFrame::EvaluateExpression(const char *expr, + lldb::DynamicValueType fetch_dynamic_value, + bool unwind_on_error) { + SBExpressionOptions options; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(unwind_on_error); + options.SetIgnoreBreakpoints(true); + StackFrame *frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); + if (target && target->GetLanguage() != eLanguageTypeUnknown) + options.SetLanguage(target->GetLanguage()); + else if (frame) + options.SetLanguage(frame->GetLanguage()); + return EvaluateExpression(expr, options); +} + +lldb::SBValue SBFrame::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); #ifndef LLDB_DISABLE_PYTHON - Log *expr_log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); + Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); #endif - ExpressionResults exe_results = eExpressionSetupError; - SBValue expr_result; - - if (expr == nullptr || expr[0] == '\0') - { - if (log) - log->Printf ("SBFrame::EvaluateExpression called with an empty expression"); - return expr_result; - } - - ValueObjectSP expr_value_sp; - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + ExpressionResults exe_results = eExpressionSetupError; + SBValue expr_result; + if (expr == nullptr || expr[0] == '\0') { if (log) - log->Printf ("SBFrame()::EvaluateExpression (expr=\"%s\")...", expr); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - if (target->GetDisplayExpressionsInCrashlogs()) - { - StreamString frame_description; - frame->DumpUsingSettingsFormat (&frame_description); - Host::SetCrashDescriptionWithFormat ("SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value = %u) %s", - expr, options.GetFetchDynamicValue(), frame_description.GetString().c_str()); - } + log->Printf( + "SBFrame::EvaluateExpression called with an empty expression"); + return expr_result; + } + + ValueObjectSP expr_value_sp; + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (log) + log->Printf("SBFrame()::EvaluateExpression (expr=\"%s\")...", expr); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + if (target->GetDisplayExpressionsInCrashlogs()) { + StreamString frame_description; + frame->DumpUsingSettingsFormat(&frame_description); + Host::SetCrashDescriptionWithFormat( + "SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value " + "= %u) %s", + expr, options.GetFetchDynamicValue(), + frame_description.GetString().c_str()); + } - exe_results = target->EvaluateExpression (expr, - frame, - expr_value_sp, - options.ref()); - expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); + exe_results = target->EvaluateExpression(expr, frame, expr_value_sp, + options.ref()); + expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); - if (target->GetDisplayExpressionsInCrashlogs()) - Host::SetCrashDescription(nullptr); - } - else - { - if (log) - log->Printf ("SBFrame::EvaluateExpression () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::EvaluateExpression () => error: process is running"); - } + if (target->GetDisplayExpressionsInCrashlogs()) + Host::SetCrashDescription(nullptr); + } else { + if (log) + log->Printf("SBFrame::EvaluateExpression () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf( + "SBFrame::EvaluateExpression () => error: process is running"); } + } #ifndef LLDB_DISABLE_PYTHON - if (expr_log) - expr_log->Printf("** [SBFrame::EvaluateExpression] Expression result is %s, summary %s **", - expr_result.GetValue(), expr_result.GetSummary()); - - if (log) - log->Printf ("SBFrame(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) (execution result=%d)", - static_cast(frame), expr, - static_cast(expr_value_sp.get()), exe_results); + if (expr_log) + expr_log->Printf("** [SBFrame::EvaluateExpression] Expression result is " + "%s, summary %s **", + expr_result.GetValue(), expr_result.GetSummary()); + + if (log) + log->Printf("SBFrame(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) " + "(execution result=%d)", + static_cast(frame), expr, + static_cast(expr_value_sp.get()), exe_results); #endif - return expr_result; + return expr_result; } -bool -SBFrame::IsInlined() -{ - return static_cast(this)->IsInlined(); +bool SBFrame::IsInlined() { + return static_cast(this)->IsInlined(); } -bool -SBFrame::IsInlined() const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - - Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; - if (block) - return block->GetContainingInlinedBlock() != nullptr; - } - else - { - if (log) - log->Printf ("SBFrame::IsInlined () => error: could not reconstruct frame object for this SBFrame."); - } - } - else - { - if (log) - log->Printf ("SBFrame::IsInlined () => error: process is running"); - } - +bool SBFrame::IsInlined() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + + Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; + if (block) + return block->GetContainingInlinedBlock() != nullptr; + } else { + if (log) + log->Printf("SBFrame::IsInlined () => error: could not reconstruct " + "frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::IsInlined () => error: process is running"); } - return false; + } + return false; } -const char * -SBFrame::GetFunctionName() -{ - return static_cast(this)->GetFunctionName(); +const char *SBFrame::GetFunctionName() { + return static_cast(this)->GetFunctionName(); } -const char * -SBFrame::GetFunctionName() const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *name = nullptr; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - SymbolContext sc (frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextBlock | eSymbolContextSymbol)); - if (sc.block) - { - Block *inlined_block = sc.block->GetContainingInlinedBlock (); - if (inlined_block) - { - const InlineFunctionInfo* inlined_info = inlined_block->GetInlinedFunctionInfo(); - name = inlined_info->GetName(sc.function->GetLanguage()).AsCString(); - } - } - - if (name == nullptr) - { - if (sc.function) - name = sc.function->GetName().GetCString(); - } +const char *SBFrame::GetFunctionName() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *name = nullptr; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextBlock | + eSymbolContextSymbol)); + if (sc.block) { + Block *inlined_block = sc.block->GetContainingInlinedBlock(); + if (inlined_block) { + const InlineFunctionInfo *inlined_info = + inlined_block->GetInlinedFunctionInfo(); + name = + inlined_info->GetName(sc.function->GetLanguage()).AsCString(); + } + } - if (name == nullptr) - { - if (sc.symbol) - name = sc.symbol->GetName().GetCString(); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetFunctionName () => error: could not reconstruct frame object for this SBFrame."); - } + if (name == nullptr) { + if (sc.function) + name = sc.function->GetName().GetCString(); } - else - { - if (log) - log->Printf ("SBFrame::GetFunctionName() => error: process is running"); + if (name == nullptr) { + if (sc.symbol) + name = sc.symbol->GetName().GetCString(); } + } else { + if (log) + log->Printf("SBFrame::GetFunctionName () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf("SBFrame::GetFunctionName() => error: process is running"); } - return name; + } + return name; } -const char * -SBFrame::GetDisplayFunctionName() -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *name = nullptr; - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrame *frame = nullptr; - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - { - frame = exe_ctx.GetFramePtr(); - if (frame) - { - SymbolContext sc (frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextBlock | eSymbolContextSymbol)); - if (sc.block) - { - Block *inlined_block = sc.block->GetContainingInlinedBlock (); - if (inlined_block) - { - const InlineFunctionInfo* inlined_info = inlined_block->GetInlinedFunctionInfo(); - name = inlined_info->GetDisplayName(sc.function->GetLanguage()).AsCString(); - } - } - - if (name == nullptr) - { - if (sc.function) - name = sc.function->GetDisplayName().GetCString(); - } - - if (name == nullptr) - { - if (sc.symbol) - name = sc.symbol->GetDisplayName().GetCString(); - } - } - else - { - if (log) - log->Printf ("SBFrame::GetDisplayFunctionName () => error: could not reconstruct frame object for this SBFrame."); - } +const char *SBFrame::GetDisplayFunctionName() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *name = nullptr; + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrame *frame = nullptr; + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) { + frame = exe_ctx.GetFramePtr(); + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextBlock | + eSymbolContextSymbol)); + if (sc.block) { + Block *inlined_block = sc.block->GetContainingInlinedBlock(); + if (inlined_block) { + const InlineFunctionInfo *inlined_info = + inlined_block->GetInlinedFunctionInfo(); + name = inlined_info->GetDisplayName(sc.function->GetLanguage()) + .AsCString(); + } } - else - { - if (log) - log->Printf ("SBFrame::GetDisplayFunctionName() => error: process is running"); - + + if (name == nullptr) { + if (sc.function) + name = sc.function->GetDisplayName().GetCString(); + } + + if (name == nullptr) { + if (sc.symbol) + name = sc.symbol->GetDisplayName().GetCString(); } + } else { + if (log) + log->Printf("SBFrame::GetDisplayFunctionName () => error: could not " + "reconstruct frame object for this SBFrame."); + } + } else { + if (log) + log->Printf( + "SBFrame::GetDisplayFunctionName() => error: process is running"); } - return name; + } + return name; } diff --git a/lldb/source/API/SBFunction.cpp b/lldb/source/API/SBFunction.cpp index b5983d763be..9065cc383ef 100644 --- a/lldb/source/API/SBFunction.cpp +++ b/lldb/source/API/SBFunction.cpp @@ -23,267 +23,200 @@ using namespace lldb; using namespace lldb_private; -SBFunction::SBFunction () : - m_opaque_ptr (NULL) -{ -} - -SBFunction::SBFunction (lldb_private::Function *lldb_object_ptr) : - m_opaque_ptr (lldb_object_ptr) -{ -} - -SBFunction::SBFunction (const lldb::SBFunction &rhs) : - m_opaque_ptr (rhs.m_opaque_ptr) -{ -} - -const SBFunction & -SBFunction::operator = (const SBFunction &rhs) -{ - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; -} - -SBFunction::~SBFunction () -{ - m_opaque_ptr = NULL; -} - -bool -SBFunction::IsValid () const -{ - return m_opaque_ptr != NULL; -} - -const char * -SBFunction::GetName() const -{ - const char *cstr = NULL; - if (m_opaque_ptr) - cstr = m_opaque_ptr->GetName().AsCString(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (cstr) - log->Printf ("SBFunction(%p)::GetName () => \"%s\"", - static_cast(m_opaque_ptr), cstr); - else - log->Printf ("SBFunction(%p)::GetName () => NULL", - static_cast(m_opaque_ptr)); - } - return cstr; -} - -const char * -SBFunction::GetDisplayName() const -{ - const char *cstr = NULL; - if (m_opaque_ptr) - cstr = m_opaque_ptr->GetMangled().GetDisplayDemangledName(m_opaque_ptr->GetLanguage()).AsCString(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (cstr) - log->Printf ("SBFunction(%p)::GetDisplayName () => \"%s\"", - static_cast(m_opaque_ptr), cstr); - else - log->Printf ("SBFunction(%p)::GetDisplayName () => NULL", - static_cast(m_opaque_ptr)); - } - return cstr; -} - -const char * -SBFunction::GetMangledName () const -{ - const char *cstr = NULL; - if (m_opaque_ptr) - cstr = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (cstr) - log->Printf ("SBFunction(%p)::GetMangledName () => \"%s\"", - static_cast(m_opaque_ptr), cstr); - else - log->Printf ("SBFunction(%p)::GetMangledName () => NULL", - static_cast(m_opaque_ptr)); +SBFunction::SBFunction() : m_opaque_ptr(NULL) {} + +SBFunction::SBFunction(lldb_private::Function *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} + +SBFunction::SBFunction(const lldb::SBFunction &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) {} + +const SBFunction &SBFunction::operator=(const SBFunction &rhs) { + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; +} + +SBFunction::~SBFunction() { m_opaque_ptr = NULL; } + +bool SBFunction::IsValid() const { return m_opaque_ptr != NULL; } + +const char *SBFunction::GetName() const { + const char *cstr = NULL; + if (m_opaque_ptr) + cstr = m_opaque_ptr->GetName().AsCString(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (cstr) + log->Printf("SBFunction(%p)::GetName () => \"%s\"", + static_cast(m_opaque_ptr), cstr); + else + log->Printf("SBFunction(%p)::GetName () => NULL", + static_cast(m_opaque_ptr)); + } + return cstr; +} + +const char *SBFunction::GetDisplayName() const { + const char *cstr = NULL; + if (m_opaque_ptr) + cstr = m_opaque_ptr->GetMangled() + .GetDisplayDemangledName(m_opaque_ptr->GetLanguage()) + .AsCString(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (cstr) + log->Printf("SBFunction(%p)::GetDisplayName () => \"%s\"", + static_cast(m_opaque_ptr), cstr); + else + log->Printf("SBFunction(%p)::GetDisplayName () => NULL", + static_cast(m_opaque_ptr)); + } + return cstr; +} + +const char *SBFunction::GetMangledName() const { + const char *cstr = NULL; + if (m_opaque_ptr) + cstr = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (cstr) + log->Printf("SBFunction(%p)::GetMangledName () => \"%s\"", + static_cast(m_opaque_ptr), cstr); + else + log->Printf("SBFunction(%p)::GetMangledName () => NULL", + static_cast(m_opaque_ptr)); + } + return cstr; +} + +bool SBFunction::operator==(const SBFunction &rhs) const { + return m_opaque_ptr == rhs.m_opaque_ptr; +} + +bool SBFunction::operator!=(const SBFunction &rhs) const { + return m_opaque_ptr != rhs.m_opaque_ptr; +} + +bool SBFunction::GetDescription(SBStream &s) { + if (m_opaque_ptr) { + s.Printf("SBFunction: id = 0x%8.8" PRIx64 ", name = %s", + m_opaque_ptr->GetID(), m_opaque_ptr->GetName().AsCString()); + Type *func_type = m_opaque_ptr->GetType(); + if (func_type) + s.Printf(", type = %s", func_type->GetName().AsCString()); + return true; + } + s.Printf("No value"); + return false; +} + +SBInstructionList SBFunction::GetInstructions(SBTarget target) { + return GetInstructions(target, NULL); +} + +SBInstructionList SBFunction::GetInstructions(SBTarget target, + const char *flavor) { + SBInstructionList sb_instructions; + if (m_opaque_ptr) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock lock; + if (target_sp) { + lock = std::unique_lock(target_sp->GetAPIMutex()); + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); } - return cstr; -} - -bool -SBFunction::operator == (const SBFunction &rhs) const -{ - return m_opaque_ptr == rhs.m_opaque_ptr; -} - -bool -SBFunction::operator != (const SBFunction &rhs) const -{ - return m_opaque_ptr != rhs.m_opaque_ptr; -} - -bool -SBFunction::GetDescription (SBStream &s) -{ - if (m_opaque_ptr) - { - s.Printf ("SBFunction: id = 0x%8.8" PRIx64 ", name = %s", - m_opaque_ptr->GetID(), - m_opaque_ptr->GetName().AsCString()); - Type *func_type = m_opaque_ptr->GetType(); - if (func_type) - s.Printf(", type = %s", func_type->GetName().AsCString()); - return true; - } - s.Printf ("No value"); - return false; -} - -SBInstructionList -SBFunction::GetInstructions (SBTarget target) -{ - return GetInstructions (target, NULL); -} - -SBInstructionList -SBFunction::GetInstructions (SBTarget target, const char *flavor) -{ - SBInstructionList sb_instructions; - if (m_opaque_ptr) - { - ExecutionContext exe_ctx; - TargetSP target_sp (target.GetSP()); - std::unique_lock lock; - if (target_sp) - { - lock = std::unique_lock(target_sp->GetAPIMutex()); - target_sp->CalculateExecutionContext (exe_ctx); - exe_ctx.SetProcessSP(target_sp->GetProcessSP()); - } - ModuleSP module_sp (m_opaque_ptr->GetAddressRange().GetBaseAddress().GetModule()); - if (module_sp) - { - const bool prefer_file_cache = false; - sb_instructions.SetDisassembler (Disassembler::DisassembleRange (module_sp->GetArchitecture(), - NULL, - flavor, - exe_ctx, - m_opaque_ptr->GetAddressRange(), - prefer_file_cache)); - } + ModuleSP module_sp( + m_opaque_ptr->GetAddressRange().GetBaseAddress().GetModule()); + if (module_sp) { + const bool prefer_file_cache = false; + sb_instructions.SetDisassembler(Disassembler::DisassembleRange( + module_sp->GetArchitecture(), NULL, flavor, exe_ctx, + m_opaque_ptr->GetAddressRange(), prefer_file_cache)); } - return sb_instructions; + } + return sb_instructions; } -lldb_private::Function * -SBFunction::get () -{ - return m_opaque_ptr; -} +lldb_private::Function *SBFunction::get() { return m_opaque_ptr; } -void -SBFunction::reset (lldb_private::Function *lldb_object_ptr) -{ - m_opaque_ptr = lldb_object_ptr; +void SBFunction::reset(lldb_private::Function *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; } -SBAddress -SBFunction::GetStartAddress () -{ - SBAddress addr; - if (m_opaque_ptr) - addr.SetAddress (&m_opaque_ptr->GetAddressRange().GetBaseAddress()); - return addr; +SBAddress SBFunction::GetStartAddress() { + SBAddress addr; + if (m_opaque_ptr) + addr.SetAddress(&m_opaque_ptr->GetAddressRange().GetBaseAddress()); + return addr; } -SBAddress -SBFunction::GetEndAddress () -{ - SBAddress addr; - if (m_opaque_ptr) - { - addr_t byte_size = m_opaque_ptr->GetAddressRange().GetByteSize(); - if (byte_size > 0) - { - addr.SetAddress (&m_opaque_ptr->GetAddressRange().GetBaseAddress()); - addr->Slide (byte_size); - } +SBAddress SBFunction::GetEndAddress() { + SBAddress addr; + if (m_opaque_ptr) { + addr_t byte_size = m_opaque_ptr->GetAddressRange().GetByteSize(); + if (byte_size > 0) { + addr.SetAddress(&m_opaque_ptr->GetAddressRange().GetBaseAddress()); + addr->Slide(byte_size); } - return addr; -} - -const char * -SBFunction::GetArgumentName (uint32_t arg_idx) -{ - if (m_opaque_ptr) - { - Block &block = m_opaque_ptr->GetBlock(true); - VariableListSP variable_list_sp = block.GetBlockVariableList(true); - if (variable_list_sp) - { - VariableList arguments; - variable_list_sp->AppendVariablesWithScope (eValueTypeVariableArgument, arguments, true); - lldb::VariableSP variable_sp = arguments.GetVariableAtIndex(arg_idx); - if (variable_sp) - return variable_sp->GetName().GetCString(); - } + } + return addr; +} + +const char *SBFunction::GetArgumentName(uint32_t arg_idx) { + if (m_opaque_ptr) { + Block &block = m_opaque_ptr->GetBlock(true); + VariableListSP variable_list_sp = block.GetBlockVariableList(true); + if (variable_list_sp) { + VariableList arguments; + variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, + arguments, true); + lldb::VariableSP variable_sp = arguments.GetVariableAtIndex(arg_idx); + if (variable_sp) + return variable_sp->GetName().GetCString(); } - return nullptr; + } + return nullptr; } -uint32_t -SBFunction::GetPrologueByteSize () -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetPrologueByteSize(); - return 0; +uint32_t SBFunction::GetPrologueByteSize() { + if (m_opaque_ptr) + return m_opaque_ptr->GetPrologueByteSize(); + return 0; } -SBType -SBFunction::GetType () -{ - SBType sb_type; - if (m_opaque_ptr) - { - Type *function_type = m_opaque_ptr->GetType(); - if (function_type) - sb_type.ref().SetType (function_type->shared_from_this()); - } - return sb_type; +SBType SBFunction::GetType() { + SBType sb_type; + if (m_opaque_ptr) { + Type *function_type = m_opaque_ptr->GetType(); + if (function_type) + sb_type.ref().SetType(function_type->shared_from_this()); + } + return sb_type; } -SBBlock -SBFunction::GetBlock () -{ - SBBlock sb_block; - if (m_opaque_ptr) - sb_block.SetPtr (&m_opaque_ptr->GetBlock (true)); - return sb_block; +SBBlock SBFunction::GetBlock() { + SBBlock sb_block; + if (m_opaque_ptr) + sb_block.SetPtr(&m_opaque_ptr->GetBlock(true)); + return sb_block; } -lldb::LanguageType -SBFunction::GetLanguage () -{ - if (m_opaque_ptr) - { - if (m_opaque_ptr->GetCompileUnit()) - return m_opaque_ptr->GetCompileUnit()->GetLanguage(); - } - return lldb::eLanguageTypeUnknown; +lldb::LanguageType SBFunction::GetLanguage() { + if (m_opaque_ptr) { + if (m_opaque_ptr->GetCompileUnit()) + return m_opaque_ptr->GetCompileUnit()->GetLanguage(); + } + return lldb::eLanguageTypeUnknown; } -bool -SBFunction::GetIsOptimized () -{ - if (m_opaque_ptr) - { - if (m_opaque_ptr->GetCompileUnit()) - return m_opaque_ptr->GetCompileUnit()->GetIsOptimized(); - } - return false; +bool SBFunction::GetIsOptimized() { + if (m_opaque_ptr) { + if (m_opaque_ptr->GetCompileUnit()) + return m_opaque_ptr->GetCompileUnit()->GetIsOptimized(); + } + return false; } diff --git a/lldb/source/API/SBHostOS.cpp b/lldb/source/API/SBHostOS.cpp index 6c172997bdc..8df74d931ec 100644 --- a/lldb/source/API/SBHostOS.cpp +++ b/lldb/source/API/SBHostOS.cpp @@ -9,133 +9,108 @@ #include "lldb/API/SBHostOS.h" #include "lldb/API/SBError.h" -#include "lldb/Host/FileSpec.h" #include "lldb/Core/Log.h" +#include "lldb/Host/FileSpec.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/HostNativeThread.h" #include "lldb/Host/HostThread.h" #include "lldb/Host/ThreadLauncher.h" -#include "llvm/Support/Path.h" #include "llvm/ADT/SmallString.h" +#include "llvm/Support/Path.h" using namespace lldb; using namespace lldb_private; +SBFileSpec SBHostOS::GetProgramFileSpec() { + SBFileSpec sb_filespec; + sb_filespec.SetFileSpec(HostInfo::GetProgramFileSpec()); + return sb_filespec; +} - -SBFileSpec -SBHostOS::GetProgramFileSpec () -{ - SBFileSpec sb_filespec; - sb_filespec.SetFileSpec(HostInfo::GetProgramFileSpec()); - return sb_filespec; +SBFileSpec SBHostOS::GetLLDBPythonPath() { + SBFileSpec sb_lldb_python_filespec; + FileSpec lldb_python_spec; + if (HostInfo::GetLLDBPath(ePathTypePythonDir, lldb_python_spec)) { + sb_lldb_python_filespec.SetFileSpec(lldb_python_spec); + } + return sb_lldb_python_filespec; } -SBFileSpec -SBHostOS::GetLLDBPythonPath () -{ - SBFileSpec sb_lldb_python_filespec; - FileSpec lldb_python_spec; - if (HostInfo::GetLLDBPath(ePathTypePythonDir, lldb_python_spec)) - { - sb_lldb_python_filespec.SetFileSpec (lldb_python_spec); - } - return sb_lldb_python_filespec; +SBFileSpec SBHostOS::GetLLDBPath(lldb::PathType path_type) { + SBFileSpec sb_fspec; + FileSpec fspec; + if (HostInfo::GetLLDBPath(path_type, fspec)) + sb_fspec.SetFileSpec(fspec); + return sb_fspec; } +SBFileSpec SBHostOS::GetUserHomeDirectory() { + SBFileSpec sb_fspec; -SBFileSpec -SBHostOS::GetLLDBPath (lldb::PathType path_type) -{ - SBFileSpec sb_fspec; - FileSpec fspec; - if (HostInfo::GetLLDBPath(path_type, fspec)) - sb_fspec.SetFileSpec (fspec); - return sb_fspec; + llvm::SmallString<64> home_dir_path; + llvm::sys::path::home_directory(home_dir_path); + FileSpec homedir(home_dir_path.c_str(), true); + + sb_fspec.SetFileSpec(homedir); + return sb_fspec; } -SBFileSpec -SBHostOS::GetUserHomeDirectory () -{ - SBFileSpec sb_fspec; +lldb::thread_t SBHostOS::ThreadCreate(const char *name, + lldb::thread_func_t thread_function, + void *thread_arg, SBError *error_ptr) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - llvm::SmallString<64> home_dir_path; - llvm::sys::path::home_directory (home_dir_path); - FileSpec homedir (home_dir_path.c_str(), true); + if (log) + log->Printf( + "SBHostOS::ThreadCreate (name=\"%s\", thread_function=%p, " + "thread_arg=%p, error_ptr=%p)", + name, + reinterpret_cast(reinterpret_cast(thread_function)), + static_cast(thread_arg), static_cast(error_ptr)); - sb_fspec.SetFileSpec (homedir); - return sb_fspec; -} + // FIXME: You should log the return value? -lldb::thread_t -SBHostOS::ThreadCreate -( - const char *name, - lldb::thread_func_t thread_function, - void *thread_arg, - SBError *error_ptr -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBHostOS::ThreadCreate (name=\"%s\", thread_function=%p, thread_arg=%p, error_ptr=%p)", - name, reinterpret_cast(reinterpret_cast(thread_function)), - static_cast(thread_arg), - static_cast(error_ptr)); - - // FIXME: You should log the return value? - - HostThread thread(ThreadLauncher::LaunchThread(name, thread_function, thread_arg, error_ptr ? error_ptr->get() : NULL)); - return thread.Release(); + HostThread thread(ThreadLauncher::LaunchThread( + name, thread_function, thread_arg, error_ptr ? error_ptr->get() : NULL)); + return thread.Release(); } -void -SBHostOS::ThreadCreated (const char *name) -{ -} +void SBHostOS::ThreadCreated(const char *name) {} -bool -SBHostOS::ThreadCancel (lldb::thread_t thread, SBError *error_ptr) -{ - Error error; - HostThread host_thread(thread); - error = host_thread.Cancel(); - if (error_ptr) - error_ptr->SetError(error); - host_thread.Release(); - return error.Success(); +bool SBHostOS::ThreadCancel(lldb::thread_t thread, SBError *error_ptr) { + Error error; + HostThread host_thread(thread); + error = host_thread.Cancel(); + if (error_ptr) + error_ptr->SetError(error); + host_thread.Release(); + return error.Success(); } -bool -SBHostOS::ThreadDetach (lldb::thread_t thread, SBError *error_ptr) -{ - Error error; +bool SBHostOS::ThreadDetach(lldb::thread_t thread, SBError *error_ptr) { + Error error; #if defined(_WIN32) - if (error_ptr) - error_ptr->SetErrorString("ThreadDetach is not supported on this platform"); + if (error_ptr) + error_ptr->SetErrorString("ThreadDetach is not supported on this platform"); #else - HostThread host_thread(thread); - error = host_thread.GetNativeThread().Detach(); - if (error_ptr) - error_ptr->SetError(error); - host_thread.Release(); + HostThread host_thread(thread); + error = host_thread.GetNativeThread().Detach(); + if (error_ptr) + error_ptr->SetError(error); + host_thread.Release(); #endif - return error.Success(); + return error.Success(); } -bool -SBHostOS::ThreadJoin (lldb::thread_t thread, lldb::thread_result_t *result, SBError *error_ptr) -{ - Error error; - HostThread host_thread(thread); - error = host_thread.Join(result); - if (error_ptr) - error_ptr->SetError(error); - host_thread.Release(); - return error.Success(); +bool SBHostOS::ThreadJoin(lldb::thread_t thread, lldb::thread_result_t *result, + SBError *error_ptr) { + Error error; + HostThread host_thread(thread); + error = host_thread.Join(result); + if (error_ptr) + error_ptr->SetError(error); + host_thread.Release(); + return error.Success(); } - - diff --git a/lldb/source/API/SBInstruction.cpp b/lldb/source/API/SBInstruction.cpp index ccf561edb90..8c616da5a7f 100644 --- a/lldb/source/API/SBInstruction.cpp +++ b/lldb/source/API/SBInstruction.cpp @@ -47,299 +47,232 @@ // the disassembler and the instruction so that the object can live and // successfully respond to all queries. //---------------------------------------------------------------------- -class InstructionImpl -{ +class InstructionImpl { public: - InstructionImpl (const lldb::DisassemblerSP &disasm_sp, const lldb::InstructionSP& inst_sp) : - m_disasm_sp(disasm_sp), - m_inst_sp(inst_sp) - { - } + InstructionImpl(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) + : m_disasm_sp(disasm_sp), m_inst_sp(inst_sp) {} - lldb::InstructionSP - GetSP() const - { - return m_inst_sp; - } + lldb::InstructionSP GetSP() const { return m_inst_sp; } - bool - IsValid() const - { - return (bool)m_inst_sp; - } + bool IsValid() const { return (bool)m_inst_sp; } protected: - lldb::DisassemblerSP m_disasm_sp; // Can be empty/invalid - lldb::InstructionSP m_inst_sp; + lldb::DisassemblerSP m_disasm_sp; // Can be empty/invalid + lldb::InstructionSP m_inst_sp; }; using namespace lldb; using namespace lldb_private; -SBInstruction::SBInstruction() : - m_opaque_sp() -{ -} +SBInstruction::SBInstruction() : m_opaque_sp() {} -SBInstruction::SBInstruction(const lldb::DisassemblerSP &disasm_sp, const lldb::InstructionSP& inst_sp) : - m_opaque_sp(new InstructionImpl(disasm_sp, inst_sp)) -{ -} +SBInstruction::SBInstruction(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) + : m_opaque_sp(new InstructionImpl(disasm_sp, inst_sp)) {} -SBInstruction::SBInstruction(const SBInstruction &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBInstruction::SBInstruction(const SBInstruction &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -const SBInstruction & -SBInstruction::operator = (const SBInstruction &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBInstruction &SBInstruction::operator=(const SBInstruction &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -SBInstruction::~SBInstruction () -{ -} +SBInstruction::~SBInstruction() {} -bool -SBInstruction::IsValid() -{ - return m_opaque_sp && m_opaque_sp->IsValid(); -} +bool SBInstruction::IsValid() { return m_opaque_sp && m_opaque_sp->IsValid(); } -SBAddress -SBInstruction::GetAddress() -{ - SBAddress sb_addr; - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp && inst_sp->GetAddress().IsValid()) - sb_addr.SetAddress(&inst_sp->GetAddress()); - return sb_addr; +SBAddress SBInstruction::GetAddress() { + SBAddress sb_addr; + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp && inst_sp->GetAddress().IsValid()) + sb_addr.SetAddress(&inst_sp->GetAddress()); + return sb_addr; } -const char * -SBInstruction::GetMnemonic(SBTarget target) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - ExecutionContext exe_ctx; - TargetSP target_sp (target.GetSP()); - std::unique_lock lock; - if (target_sp) - { - lock = std::unique_lock(target_sp->GetAPIMutex()); - - target_sp->CalculateExecutionContext (exe_ctx); - exe_ctx.SetProcessSP(target_sp->GetProcessSP()); - } - return inst_sp->GetMnemonic(&exe_ctx); +const char *SBInstruction::GetMnemonic(SBTarget target) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock lock; + if (target_sp) { + lock = std::unique_lock(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); } - return NULL; + return inst_sp->GetMnemonic(&exe_ctx); + } + return NULL; } -const char * -SBInstruction::GetOperands(SBTarget target) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - ExecutionContext exe_ctx; - TargetSP target_sp (target.GetSP()); - std::unique_lock lock; - if (target_sp) - { - lock = std::unique_lock(target_sp->GetAPIMutex()); - - target_sp->CalculateExecutionContext (exe_ctx); - exe_ctx.SetProcessSP(target_sp->GetProcessSP()); - } - return inst_sp->GetOperands(&exe_ctx); +const char *SBInstruction::GetOperands(SBTarget target) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock lock; + if (target_sp) { + lock = std::unique_lock(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); } - return NULL; + return inst_sp->GetOperands(&exe_ctx); + } + return NULL; } -const char * -SBInstruction::GetComment(SBTarget target) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - ExecutionContext exe_ctx; - TargetSP target_sp (target.GetSP()); - std::unique_lock lock; - if (target_sp) - { - lock = std::unique_lock(target_sp->GetAPIMutex()); - - target_sp->CalculateExecutionContext (exe_ctx); - exe_ctx.SetProcessSP(target_sp->GetProcessSP()); - } - return inst_sp->GetComment(&exe_ctx); +const char *SBInstruction::GetComment(SBTarget target) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock lock; + if (target_sp) { + lock = std::unique_lock(target_sp->GetAPIMutex()); + + target_sp->CalculateExecutionContext(exe_ctx); + exe_ctx.SetProcessSP(target_sp->GetProcessSP()); } - return NULL; + return inst_sp->GetComment(&exe_ctx); + } + return NULL; } -size_t -SBInstruction::GetByteSize () -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - return inst_sp->GetOpcode().GetByteSize(); - return 0; +size_t SBInstruction::GetByteSize() { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->GetOpcode().GetByteSize(); + return 0; } -SBData -SBInstruction::GetData (SBTarget target) -{ - lldb::SBData sb_data; - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - DataExtractorSP data_extractor_sp (new DataExtractor()); - if (inst_sp->GetData (*data_extractor_sp)) - { - sb_data.SetOpaque (data_extractor_sp); - } +SBData SBInstruction::GetData(SBTarget target) { + lldb::SBData sb_data; + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + DataExtractorSP data_extractor_sp(new DataExtractor()); + if (inst_sp->GetData(*data_extractor_sp)) { + sb_data.SetOpaque(data_extractor_sp); } - return sb_data; + } + return sb_data; } - - -bool -SBInstruction::DoesBranch () -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - return inst_sp->DoesBranch (); - return false; +bool SBInstruction::DoesBranch() { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->DoesBranch(); + return false; } -bool -SBInstruction::HasDelaySlot () -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - return inst_sp->HasDelaySlot (); - return false; +bool SBInstruction::HasDelaySlot() { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->HasDelaySlot(); + return false; } -lldb::InstructionSP -SBInstruction::GetOpaque () -{ - if (m_opaque_sp) - return m_opaque_sp->GetSP(); - else - return lldb::InstructionSP(); +lldb::InstructionSP SBInstruction::GetOpaque() { + if (m_opaque_sp) + return m_opaque_sp->GetSP(); + else + return lldb::InstructionSP(); } -void -SBInstruction::SetOpaque (const lldb::DisassemblerSP &disasm_sp, const lldb::InstructionSP& inst_sp) -{ - m_opaque_sp.reset(new InstructionImpl(disasm_sp, inst_sp)); +void SBInstruction::SetOpaque(const lldb::DisassemblerSP &disasm_sp, + const lldb::InstructionSP &inst_sp) { + m_opaque_sp.reset(new InstructionImpl(disasm_sp, inst_sp)); } -bool -SBInstruction::GetDescription (lldb::SBStream &s) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - SymbolContext sc; - const Address &addr = inst_sp->GetAddress(); - ModuleSP module_sp (addr.GetModule()); - if (module_sp) - module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, sc); - // Use the "ref()" instead of the "get()" accessor in case the SBStream - // didn't have a stream already created, one will get created... - FormatEntity::Entry format; - FormatEntity::Parse("${addr}: ", format); - inst_sp->Dump (&s.ref(), 0, true, false, NULL, &sc, NULL, &format, 0); - return true; - } - return false; +bool SBInstruction::GetDescription(lldb::SBStream &s) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + SymbolContext sc; + const Address &addr = inst_sp->GetAddress(); + ModuleSP module_sp(addr.GetModule()); + if (module_sp) + module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, + sc); + // Use the "ref()" instead of the "get()" accessor in case the SBStream + // didn't have a stream already created, one will get created... + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + inst_sp->Dump(&s.ref(), 0, true, false, NULL, &sc, NULL, &format, 0); + return true; + } + return false; } -void -SBInstruction::Print (FILE *out) -{ - if (out == NULL) - return; - - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - SymbolContext sc; - const Address &addr = inst_sp->GetAddress(); - ModuleSP module_sp (addr.GetModule()); - if (module_sp) - module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, sc); - StreamFile out_stream (out, false); - FormatEntity::Entry format; - FormatEntity::Parse("${addr}: ", format); - inst_sp->Dump (&out_stream, 0, true, false, NULL, &sc, NULL, &format, 0); - } +void SBInstruction::Print(FILE *out) { + if (out == NULL) + return; + + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + SymbolContext sc; + const Address &addr = inst_sp->GetAddress(); + ModuleSP module_sp(addr.GetModule()); + if (module_sp) + module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, + sc); + StreamFile out_stream(out, false); + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + inst_sp->Dump(&out_stream, 0, true, false, NULL, &sc, NULL, &format, 0); + } } -bool -SBInstruction::EmulateWithFrame (lldb::SBFrame &frame, uint32_t evaluate_options) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - { - lldb::StackFrameSP frame_sp (frame.GetFrameSP()); - - if (frame_sp) - { - lldb_private::ExecutionContext exe_ctx; - frame_sp->CalculateExecutionContext (exe_ctx); - lldb_private::Target *target = exe_ctx.GetTargetPtr(); - lldb_private::ArchSpec arch = target->GetArchitecture(); - - return inst_sp->Emulate(arch, - evaluate_options, - (void *) frame_sp.get(), - &lldb_private::EmulateInstruction::ReadMemoryFrame, - &lldb_private::EmulateInstruction::WriteMemoryFrame, - &lldb_private::EmulateInstruction::ReadRegisterFrame, - &lldb_private::EmulateInstruction::WriteRegisterFrame); - } +bool SBInstruction::EmulateWithFrame(lldb::SBFrame &frame, + uint32_t evaluate_options) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) { + lldb::StackFrameSP frame_sp(frame.GetFrameSP()); + + if (frame_sp) { + lldb_private::ExecutionContext exe_ctx; + frame_sp->CalculateExecutionContext(exe_ctx); + lldb_private::Target *target = exe_ctx.GetTargetPtr(); + lldb_private::ArchSpec arch = target->GetArchitecture(); + + return inst_sp->Emulate( + arch, evaluate_options, (void *)frame_sp.get(), + &lldb_private::EmulateInstruction::ReadMemoryFrame, + &lldb_private::EmulateInstruction::WriteMemoryFrame, + &lldb_private::EmulateInstruction::ReadRegisterFrame, + &lldb_private::EmulateInstruction::WriteRegisterFrame); } - return false; + } + return false; } -bool -SBInstruction::DumpEmulation (const char *triple) -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp && triple) - { - lldb_private::ArchSpec arch (triple, NULL); - return inst_sp->DumpEmulation (arch); - } - return false; +bool SBInstruction::DumpEmulation(const char *triple) { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp && triple) { + lldb_private::ArchSpec arch(triple, NULL); + return inst_sp->DumpEmulation(arch); + } + return false; } -bool -SBInstruction::TestEmulation (lldb::SBStream &output_stream, const char *test_file) -{ - if (!m_opaque_sp) - SetOpaque(lldb::DisassemblerSP(), lldb::InstructionSP(new PseudoInstruction())); +bool SBInstruction::TestEmulation(lldb::SBStream &output_stream, + const char *test_file) { + if (!m_opaque_sp) + SetOpaque(lldb::DisassemblerSP(), + lldb::InstructionSP(new PseudoInstruction())); - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - return inst_sp->TestEmulation (output_stream.get(), test_file); - return false; + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->TestEmulation(output_stream.get(), test_file); + return false; } -lldb::AddressClass -SBInstruction::GetAddressClass () -{ - lldb::InstructionSP inst_sp(GetOpaque()); - if (inst_sp) - return inst_sp->GetAddressClass(); - return eAddressClassInvalid; +lldb::AddressClass SBInstruction::GetAddressClass() { + lldb::InstructionSP inst_sp(GetOpaque()); + if (inst_sp) + return inst_sp->GetAddressClass(); + return eAddressClassInvalid; } diff --git a/lldb/source/API/SBInstructionList.cpp b/lldb/source/API/SBInstructionList.cpp index 9be38b483eb..8ab3aca2181 100644 --- a/lldb/source/API/SBInstructionList.cpp +++ b/lldb/source/API/SBInstructionList.cpp @@ -18,130 +18,94 @@ using namespace lldb; using namespace lldb_private; +SBInstructionList::SBInstructionList() : m_opaque_sp() {} -SBInstructionList::SBInstructionList () : - m_opaque_sp() -{ -} +SBInstructionList::SBInstructionList(const SBInstructionList &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBInstructionList::SBInstructionList(const SBInstructionList &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ +const SBInstructionList &SBInstructionList:: +operator=(const SBInstructionList &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -const SBInstructionList & -SBInstructionList::operator = (const SBInstructionList &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; -} +SBInstructionList::~SBInstructionList() {} +bool SBInstructionList::IsValid() const { return m_opaque_sp.get() != NULL; } -SBInstructionList::~SBInstructionList () -{ +size_t SBInstructionList::GetSize() { + if (m_opaque_sp) + return m_opaque_sp->GetInstructionList().GetSize(); + return 0; } -bool -SBInstructionList::IsValid () const -{ - return m_opaque_sp.get() != NULL; +SBInstruction SBInstructionList::GetInstructionAtIndex(uint32_t idx) { + SBInstruction inst; + if (m_opaque_sp && idx < m_opaque_sp->GetInstructionList().GetSize()) + inst.SetOpaque( + m_opaque_sp, + m_opaque_sp->GetInstructionList().GetInstructionAtIndex(idx)); + return inst; } -size_t -SBInstructionList::GetSize () -{ - if (m_opaque_sp) - return m_opaque_sp->GetInstructionList().GetSize(); - return 0; -} +void SBInstructionList::Clear() { m_opaque_sp.reset(); } -SBInstruction -SBInstructionList::GetInstructionAtIndex (uint32_t idx) -{ - SBInstruction inst; - if (m_opaque_sp && idx < m_opaque_sp->GetInstructionList().GetSize()) - inst.SetOpaque (m_opaque_sp, m_opaque_sp->GetInstructionList().GetInstructionAtIndex (idx)); - return inst; -} +void SBInstructionList::AppendInstruction(SBInstruction insn) {} -void -SBInstructionList::Clear () -{ - m_opaque_sp.reset(); +void SBInstructionList::SetDisassembler(const lldb::DisassemblerSP &opaque_sp) { + m_opaque_sp = opaque_sp; } -void -SBInstructionList::AppendInstruction (SBInstruction insn) -{ +void SBInstructionList::Print(FILE *out) { + if (out == NULL) + return; } -void -SBInstructionList::SetDisassembler (const lldb::DisassemblerSP &opaque_sp) -{ - m_opaque_sp = opaque_sp; -} - -void -SBInstructionList::Print (FILE *out) -{ - if (out == NULL) - return; -} - - -bool -SBInstructionList::GetDescription (lldb::SBStream &description) -{ - if (m_opaque_sp) - { - size_t num_instructions = GetSize (); - if (num_instructions) - { - // Call the ref() to make sure a stream is created if one deesn't - // exist already inside description... - Stream &sref = description.ref(); - const uint32_t max_opcode_byte_size = m_opaque_sp->GetInstructionList().GetMaxOpcocdeByteSize(); - FormatEntity::Entry format; - FormatEntity::Parse("${addr}: ", format); - SymbolContext sc; - SymbolContext prev_sc; - for (size_t i=0; iGetInstructionList().GetInstructionAtIndex (i).get(); - if (inst == NULL) - break; - - const Address &addr = inst->GetAddress(); - prev_sc = sc; - ModuleSP module_sp (addr.GetModule()); - if (module_sp) - { - module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, sc); - } - - inst->Dump (&sref, max_opcode_byte_size, true, false, NULL, &sc, &prev_sc, &format, 0); - sref.EOL(); - } - return true; +bool SBInstructionList::GetDescription(lldb::SBStream &description) { + if (m_opaque_sp) { + size_t num_instructions = GetSize(); + if (num_instructions) { + // Call the ref() to make sure a stream is created if one deesn't + // exist already inside description... + Stream &sref = description.ref(); + const uint32_t max_opcode_byte_size = + m_opaque_sp->GetInstructionList().GetMaxOpcocdeByteSize(); + FormatEntity::Entry format; + FormatEntity::Parse("${addr}: ", format); + SymbolContext sc; + SymbolContext prev_sc; + for (size_t i = 0; i < num_instructions; ++i) { + Instruction *inst = + m_opaque_sp->GetInstructionList().GetInstructionAtIndex(i).get(); + if (inst == NULL) + break; + + const Address &addr = inst->GetAddress(); + prev_sc = sc; + ModuleSP module_sp(addr.GetModule()); + if (module_sp) { + module_sp->ResolveSymbolContextForAddress( + addr, eSymbolContextEverything, sc); } + + inst->Dump(&sref, max_opcode_byte_size, true, false, NULL, &sc, + &prev_sc, &format, 0); + sref.EOL(); + } + return true; } - return false; + } + return false; } - -bool -SBInstructionList::DumpEmulationForAllInstructions (const char *triple) -{ - if (m_opaque_sp) - { - size_t len = GetSize(); - for (size_t i = 0; i < len; ++i) - { - if (!GetInstructionAtIndex((uint32_t) i).DumpEmulation (triple)) - return false; - } +bool SBInstructionList::DumpEmulationForAllInstructions(const char *triple) { + if (m_opaque_sp) { + size_t len = GetSize(); + for (size_t i = 0; i < len; ++i) { + if (!GetInstructionAtIndex((uint32_t)i).DumpEmulation(triple)) + return false; } - return true; + } + return true; } - diff --git a/lldb/source/API/SBLanguageRuntime.cpp b/lldb/source/API/SBLanguageRuntime.cpp index 743343e4858..c6a96dcef53 100644 --- a/lldb/source/API/SBLanguageRuntime.cpp +++ b/lldb/source/API/SBLanguageRuntime.cpp @@ -14,13 +14,11 @@ using namespace lldb; using namespace lldb_private; lldb::LanguageType -SBLanguageRuntime::GetLanguageTypeFromString (const char *string) -{ - return Language::GetLanguageTypeFromString(string); +SBLanguageRuntime::GetLanguageTypeFromString(const char *string) { + return Language::GetLanguageTypeFromString(string); } const char * -SBLanguageRuntime::GetNameForLanguageType (lldb::LanguageType language) -{ - return Language::GetNameForLanguageType(language); +SBLanguageRuntime::GetNameForLanguageType(lldb::LanguageType language) { + return Language::GetNameForLanguageType(language); } diff --git a/lldb/source/API/SBLaunchInfo.cpp b/lldb/source/API/SBLaunchInfo.cpp index 54bed8799b8..5f5afccee68 100644 --- a/lldb/source/API/SBLaunchInfo.cpp +++ b/lldb/source/API/SBLaunchInfo.cpp @@ -16,279 +16,175 @@ using namespace lldb; using namespace lldb_private; -SBLaunchInfo::SBLaunchInfo (const char **argv) : - m_opaque_sp(new ProcessLaunchInfo()) -{ - m_opaque_sp->GetFlags().Reset (eLaunchFlagDebug | eLaunchFlagDisableASLR); - if (argv && argv[0]) - m_opaque_sp->GetArguments().SetArguments(argv); +SBLaunchInfo::SBLaunchInfo(const char **argv) + : m_opaque_sp(new ProcessLaunchInfo()) { + m_opaque_sp->GetFlags().Reset(eLaunchFlagDebug | eLaunchFlagDisableASLR); + if (argv && argv[0]) + m_opaque_sp->GetArguments().SetArguments(argv); } -SBLaunchInfo::~SBLaunchInfo() -{ -} +SBLaunchInfo::~SBLaunchInfo() {} -lldb_private::ProcessLaunchInfo & -SBLaunchInfo::ref () -{ - return *m_opaque_sp; -} +lldb_private::ProcessLaunchInfo &SBLaunchInfo::ref() { return *m_opaque_sp; } -const lldb_private::ProcessLaunchInfo & -SBLaunchInfo::ref () const -{ - return *m_opaque_sp; +const lldb_private::ProcessLaunchInfo &SBLaunchInfo::ref() const { + return *m_opaque_sp; } -lldb::pid_t -SBLaunchInfo::GetProcessID() -{ - return m_opaque_sp->GetProcessID(); -} +lldb::pid_t SBLaunchInfo::GetProcessID() { return m_opaque_sp->GetProcessID(); } -uint32_t -SBLaunchInfo::GetUserID() -{ - return m_opaque_sp->GetUserID(); -} +uint32_t SBLaunchInfo::GetUserID() { return m_opaque_sp->GetUserID(); } -uint32_t -SBLaunchInfo::GetGroupID() -{ - return m_opaque_sp->GetGroupID(); -} +uint32_t SBLaunchInfo::GetGroupID() { return m_opaque_sp->GetGroupID(); } -bool -SBLaunchInfo::UserIDIsValid () -{ - return m_opaque_sp->UserIDIsValid(); -} +bool SBLaunchInfo::UserIDIsValid() { return m_opaque_sp->UserIDIsValid(); } -bool -SBLaunchInfo::GroupIDIsValid () -{ - return m_opaque_sp->GroupIDIsValid(); +bool SBLaunchInfo::GroupIDIsValid() { return m_opaque_sp->GroupIDIsValid(); } + +void SBLaunchInfo::SetUserID(uint32_t uid) { m_opaque_sp->SetUserID(uid); } + +void SBLaunchInfo::SetGroupID(uint32_t gid) { m_opaque_sp->SetGroupID(gid); } + +SBFileSpec SBLaunchInfo::GetExecutableFile() { + return SBFileSpec(m_opaque_sp->GetExecutableFile()); } -void -SBLaunchInfo::SetUserID (uint32_t uid) -{ - m_opaque_sp->SetUserID (uid); +void SBLaunchInfo::SetExecutableFile(SBFileSpec exe_file, + bool add_as_first_arg) { + m_opaque_sp->SetExecutableFile(exe_file.ref(), add_as_first_arg); } -void -SBLaunchInfo::SetGroupID (uint32_t gid) -{ - m_opaque_sp->SetGroupID (gid); +SBListener SBLaunchInfo::GetListener() { + return SBListener(m_opaque_sp->GetListener()); } -SBFileSpec -SBLaunchInfo::GetExecutableFile () -{ - return SBFileSpec (m_opaque_sp->GetExecutableFile()); +void SBLaunchInfo::SetListener(SBListener &listener) { + m_opaque_sp->SetListener(listener.GetSP()); } -void -SBLaunchInfo::SetExecutableFile (SBFileSpec exe_file, bool add_as_first_arg) -{ - m_opaque_sp->SetExecutableFile(exe_file.ref(), add_as_first_arg); +uint32_t SBLaunchInfo::GetNumArguments() { + return m_opaque_sp->GetArguments().GetArgumentCount(); } -SBListener -SBLaunchInfo::GetListener () -{ - return SBListener(m_opaque_sp->GetListener()); +const char *SBLaunchInfo::GetArgumentAtIndex(uint32_t idx) { + return m_opaque_sp->GetArguments().GetArgumentAtIndex(idx); } -void -SBLaunchInfo::SetListener (SBListener &listener) -{ - m_opaque_sp->SetListener(listener.GetSP()); +void SBLaunchInfo::SetArguments(const char **argv, bool append) { + if (append) { + if (argv) + m_opaque_sp->GetArguments().AppendArguments(argv); + } else { + if (argv) + m_opaque_sp->GetArguments().SetArguments(argv); + else + m_opaque_sp->GetArguments().Clear(); + } } -uint32_t -SBLaunchInfo::GetNumArguments () -{ - return m_opaque_sp->GetArguments().GetArgumentCount(); +uint32_t SBLaunchInfo::GetNumEnvironmentEntries() { + return m_opaque_sp->GetEnvironmentEntries().GetArgumentCount(); } -const char * -SBLaunchInfo::GetArgumentAtIndex (uint32_t idx) -{ - return m_opaque_sp->GetArguments().GetArgumentAtIndex(idx); +const char *SBLaunchInfo::GetEnvironmentEntryAtIndex(uint32_t idx) { + return m_opaque_sp->GetEnvironmentEntries().GetArgumentAtIndex(idx); } -void -SBLaunchInfo::SetArguments (const char **argv, bool append) -{ - if (append) - { - if (argv) - m_opaque_sp->GetArguments().AppendArguments(argv); - } - else - { - if (argv) - m_opaque_sp->GetArguments().SetArguments(argv); - else - m_opaque_sp->GetArguments().Clear(); - } -} - -uint32_t -SBLaunchInfo::GetNumEnvironmentEntries () -{ - return m_opaque_sp->GetEnvironmentEntries().GetArgumentCount(); -} - -const char * -SBLaunchInfo::GetEnvironmentEntryAtIndex (uint32_t idx) -{ - return m_opaque_sp->GetEnvironmentEntries().GetArgumentAtIndex(idx); -} - -void -SBLaunchInfo::SetEnvironmentEntries (const char **envp, bool append) -{ - if (append) - { - if (envp) - m_opaque_sp->GetEnvironmentEntries().AppendArguments(envp); - } +void SBLaunchInfo::SetEnvironmentEntries(const char **envp, bool append) { + if (append) { + if (envp) + m_opaque_sp->GetEnvironmentEntries().AppendArguments(envp); + } else { + if (envp) + m_opaque_sp->GetEnvironmentEntries().SetArguments(envp); else - { - if (envp) - m_opaque_sp->GetEnvironmentEntries().SetArguments(envp); - else - m_opaque_sp->GetEnvironmentEntries().Clear(); - } + m_opaque_sp->GetEnvironmentEntries().Clear(); + } } -void -SBLaunchInfo::Clear () -{ - m_opaque_sp->Clear(); -} +void SBLaunchInfo::Clear() { m_opaque_sp->Clear(); } -const char * -SBLaunchInfo::GetWorkingDirectory () const -{ - return m_opaque_sp->GetWorkingDirectory().GetCString(); +const char *SBLaunchInfo::GetWorkingDirectory() const { + return m_opaque_sp->GetWorkingDirectory().GetCString(); } -void -SBLaunchInfo::SetWorkingDirectory (const char *working_dir) -{ - m_opaque_sp->SetWorkingDirectory(FileSpec{working_dir, false}); +void SBLaunchInfo::SetWorkingDirectory(const char *working_dir) { + m_opaque_sp->SetWorkingDirectory(FileSpec{working_dir, false}); } -uint32_t -SBLaunchInfo::GetLaunchFlags () -{ - return m_opaque_sp->GetFlags().Get(); +uint32_t SBLaunchInfo::GetLaunchFlags() { + return m_opaque_sp->GetFlags().Get(); } -void -SBLaunchInfo::SetLaunchFlags (uint32_t flags) -{ - m_opaque_sp->GetFlags().Reset(flags); +void SBLaunchInfo::SetLaunchFlags(uint32_t flags) { + m_opaque_sp->GetFlags().Reset(flags); } -const char * -SBLaunchInfo::GetProcessPluginName () -{ - return m_opaque_sp->GetProcessPluginName(); +const char *SBLaunchInfo::GetProcessPluginName() { + return m_opaque_sp->GetProcessPluginName(); } -void -SBLaunchInfo::SetProcessPluginName (const char *plugin_name) -{ - return m_opaque_sp->SetProcessPluginName (plugin_name); +void SBLaunchInfo::SetProcessPluginName(const char *plugin_name) { + return m_opaque_sp->SetProcessPluginName(plugin_name); } -const char * -SBLaunchInfo::GetShell () -{ - // Constify this string so that it is saved in the string pool. Otherwise - // it would be freed when this function goes out of scope. - ConstString shell(m_opaque_sp->GetShell().GetPath().c_str()); - return shell.AsCString(); +const char *SBLaunchInfo::GetShell() { + // Constify this string so that it is saved in the string pool. Otherwise + // it would be freed when this function goes out of scope. + ConstString shell(m_opaque_sp->GetShell().GetPath().c_str()); + return shell.AsCString(); } -void -SBLaunchInfo::SetShell (const char * path) -{ - m_opaque_sp->SetShell (FileSpec(path, false)); +void SBLaunchInfo::SetShell(const char *path) { + m_opaque_sp->SetShell(FileSpec(path, false)); } -bool -SBLaunchInfo::GetShellExpandArguments () -{ - return m_opaque_sp->GetShellExpandArguments(); +bool SBLaunchInfo::GetShellExpandArguments() { + return m_opaque_sp->GetShellExpandArguments(); } -void -SBLaunchInfo::SetShellExpandArguments (bool expand) -{ - m_opaque_sp->SetShellExpandArguments(expand); +void SBLaunchInfo::SetShellExpandArguments(bool expand) { + m_opaque_sp->SetShellExpandArguments(expand); } -uint32_t -SBLaunchInfo::GetResumeCount () -{ - return m_opaque_sp->GetResumeCount(); +uint32_t SBLaunchInfo::GetResumeCount() { + return m_opaque_sp->GetResumeCount(); } -void -SBLaunchInfo::SetResumeCount (uint32_t c) -{ - m_opaque_sp->SetResumeCount (c); +void SBLaunchInfo::SetResumeCount(uint32_t c) { + m_opaque_sp->SetResumeCount(c); } -bool -SBLaunchInfo::AddCloseFileAction (int fd) -{ - return m_opaque_sp->AppendCloseFileAction(fd); +bool SBLaunchInfo::AddCloseFileAction(int fd) { + return m_opaque_sp->AppendCloseFileAction(fd); } -bool -SBLaunchInfo::AddDuplicateFileAction (int fd, int dup_fd) -{ - return m_opaque_sp->AppendDuplicateFileAction(fd, dup_fd); +bool SBLaunchInfo::AddDuplicateFileAction(int fd, int dup_fd) { + return m_opaque_sp->AppendDuplicateFileAction(fd, dup_fd); } -bool -SBLaunchInfo::AddOpenFileAction (int fd, const char *path, bool read, bool write) -{ - return m_opaque_sp->AppendOpenFileAction(fd, FileSpec{path, false}, read, write); +bool SBLaunchInfo::AddOpenFileAction(int fd, const char *path, bool read, + bool write) { + return m_opaque_sp->AppendOpenFileAction(fd, FileSpec{path, false}, read, + write); } -bool -SBLaunchInfo::AddSuppressFileAction (int fd, bool read, bool write) -{ - return m_opaque_sp->AppendSuppressFileAction(fd, read, write); +bool SBLaunchInfo::AddSuppressFileAction(int fd, bool read, bool write) { + return m_opaque_sp->AppendSuppressFileAction(fd, read, write); } -void -SBLaunchInfo::SetLaunchEventData (const char *data) -{ - m_opaque_sp->SetLaunchEventData (data); +void SBLaunchInfo::SetLaunchEventData(const char *data) { + m_opaque_sp->SetLaunchEventData(data); } -const char * -SBLaunchInfo::GetLaunchEventData () const -{ - return m_opaque_sp->GetLaunchEventData (); +const char *SBLaunchInfo::GetLaunchEventData() const { + return m_opaque_sp->GetLaunchEventData(); } -void -SBLaunchInfo::SetDetachOnError (bool enable) -{ - m_opaque_sp->SetDetachOnError (enable); +void SBLaunchInfo::SetDetachOnError(bool enable) { + m_opaque_sp->SetDetachOnError(enable); } -bool -SBLaunchInfo::GetDetachOnError () const -{ - return m_opaque_sp->GetDetachOnError (); +bool SBLaunchInfo::GetDetachOnError() const { + return m_opaque_sp->GetDetachOnError(); } diff --git a/lldb/source/API/SBLineEntry.cpp b/lldb/source/API/SBLineEntry.cpp index 833eea3e35c..3469cecfb7a 100644 --- a/lldb/source/API/SBLineEntry.cpp +++ b/lldb/source/API/SBLineEntry.cpp @@ -11,244 +11,179 @@ #include "lldb/API/SBLineEntry.h" #include "lldb/API/SBStream.h" -#include "lldb/Core/StreamString.h" #include "lldb/Core/Log.h" +#include "lldb/Core/StreamString.h" #include "lldb/Symbol/LineEntry.h" using namespace lldb; using namespace lldb_private; +SBLineEntry::SBLineEntry() : m_opaque_ap() {} -SBLineEntry::SBLineEntry () : - m_opaque_ap () -{ +SBLineEntry::SBLineEntry(const SBLineEntry &rhs) : m_opaque_ap() { + if (rhs.IsValid()) + ref() = rhs.ref(); } -SBLineEntry::SBLineEntry (const SBLineEntry &rhs) : - m_opaque_ap () -{ - if (rhs.IsValid()) - ref() = rhs.ref(); -} - -SBLineEntry::SBLineEntry (const lldb_private::LineEntry *lldb_object_ptr) : - m_opaque_ap () -{ - if (lldb_object_ptr) - ref() = *lldb_object_ptr; -} - -const SBLineEntry & -SBLineEntry::operator = (const SBLineEntry &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - ref() = rhs.ref(); - else - m_opaque_ap.reset(); - } - return *this; -} - -void -SBLineEntry::SetLineEntry (const lldb_private::LineEntry &lldb_object_ref) -{ - ref() = lldb_object_ref; +SBLineEntry::SBLineEntry(const lldb_private::LineEntry *lldb_object_ptr) + : m_opaque_ap() { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; } +const SBLineEntry &SBLineEntry::operator=(const SBLineEntry &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + ref() = rhs.ref(); + else + m_opaque_ap.reset(); + } + return *this; +} -SBLineEntry::~SBLineEntry () -{ +void SBLineEntry::SetLineEntry(const lldb_private::LineEntry &lldb_object_ref) { + ref() = lldb_object_ref; } +SBLineEntry::~SBLineEntry() {} -SBAddress -SBLineEntry::GetStartAddress () const -{ - SBAddress sb_address; - if (m_opaque_ap.get()) - sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); +SBAddress SBLineEntry::GetStartAddress() const { + SBAddress sb_address; + if (m_opaque_ap.get()) + sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - StreamString sstr; - const Address *addr = sb_address.get(); - if (addr) - addr->Dump (&sstr, NULL, Address::DumpStyleModuleWithFileAddress, Address::DumpStyleInvalid, 4); - log->Printf ("SBLineEntry(%p)::GetStartAddress () => SBAddress (%p): %s", - static_cast(m_opaque_ap.get()), - static_cast(sb_address.get()), sstr.GetData()); - } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + StreamString sstr; + const Address *addr = sb_address.get(); + if (addr) + addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, + Address::DumpStyleInvalid, 4); + log->Printf("SBLineEntry(%p)::GetStartAddress () => SBAddress (%p): %s", + static_cast(m_opaque_ap.get()), + static_cast(sb_address.get()), sstr.GetData()); + } - return sb_address; + return sb_address; } -SBAddress -SBLineEntry::GetEndAddress () const -{ - SBAddress sb_address; - if (m_opaque_ap.get()) - { - sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); - sb_address.OffsetAddress(m_opaque_ap->range.GetByteSize()); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - StreamString sstr; - const Address *addr = sb_address.get(); - if (addr) - addr->Dump (&sstr, NULL, Address::DumpStyleModuleWithFileAddress, Address::DumpStyleInvalid, 4); - log->Printf ("SBLineEntry(%p)::GetEndAddress () => SBAddress (%p): %s", - static_cast(m_opaque_ap.get()), - static_cast(sb_address.get()), sstr.GetData()); - } - return sb_address; +SBAddress SBLineEntry::GetEndAddress() const { + SBAddress sb_address; + if (m_opaque_ap.get()) { + sb_address.SetAddress(&m_opaque_ap->range.GetBaseAddress()); + sb_address.OffsetAddress(m_opaque_ap->range.GetByteSize()); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + StreamString sstr; + const Address *addr = sb_address.get(); + if (addr) + addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, + Address::DumpStyleInvalid, 4); + log->Printf("SBLineEntry(%p)::GetEndAddress () => SBAddress (%p): %s", + static_cast(m_opaque_ap.get()), + static_cast(sb_address.get()), sstr.GetData()); + } + return sb_address; } -bool -SBLineEntry::IsValid () const -{ - return m_opaque_ap.get() && m_opaque_ap->IsValid(); +bool SBLineEntry::IsValid() const { + return m_opaque_ap.get() && m_opaque_ap->IsValid(); } +SBFileSpec SBLineEntry::GetFileSpec() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBFileSpec -SBLineEntry::GetFileSpec () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBFileSpec sb_file_spec; - if (m_opaque_ap.get() && m_opaque_ap->file) - sb_file_spec.SetFileSpec(m_opaque_ap->file); + SBFileSpec sb_file_spec; + if (m_opaque_ap.get() && m_opaque_ap->file) + sb_file_spec.SetFileSpec(m_opaque_ap->file); - if (log) - { - SBStream sstr; - sb_file_spec.GetDescription (sstr); - log->Printf ("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", - static_cast(m_opaque_ap.get()), - static_cast(sb_file_spec.get()), - sstr.GetData()); - } - - return sb_file_spec; -} + if (log) { + SBStream sstr; + sb_file_spec.GetDescription(sstr); + log->Printf("SBLineEntry(%p)::GetFileSpec () => SBFileSpec(%p): %s", + static_cast(m_opaque_ap.get()), + static_cast(sb_file_spec.get()), sstr.GetData()); + } -uint32_t -SBLineEntry::GetLine () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t line = 0; - if (m_opaque_ap.get()) - line = m_opaque_ap->line; + return sb_file_spec; +} - if (log) - log->Printf ("SBLineEntry(%p)::GetLine () => %u", - static_cast(m_opaque_ap.get()), line); +uint32_t SBLineEntry::GetLine() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - return line; -} + uint32_t line = 0; + if (m_opaque_ap.get()) + line = m_opaque_ap->line; + if (log) + log->Printf("SBLineEntry(%p)::GetLine () => %u", + static_cast(m_opaque_ap.get()), line); -uint32_t -SBLineEntry::GetColumn () const -{ - if (m_opaque_ap.get()) - return m_opaque_ap->column; - return 0; -} - -void -SBLineEntry::SetFileSpec (lldb::SBFileSpec filespec) -{ - if (filespec.IsValid()) - ref().file = filespec.ref(); - else - ref().file.Clear(); -} -void -SBLineEntry::SetLine (uint32_t line) -{ - ref().line = line; + return line; } -void -SBLineEntry::SetColumn (uint32_t column) -{ - ref().line = column; +uint32_t SBLineEntry::GetColumn() const { + if (m_opaque_ap.get()) + return m_opaque_ap->column; + return 0; } +void SBLineEntry::SetFileSpec(lldb::SBFileSpec filespec) { + if (filespec.IsValid()) + ref().file = filespec.ref(); + else + ref().file.Clear(); +} +void SBLineEntry::SetLine(uint32_t line) { ref().line = line; } +void SBLineEntry::SetColumn(uint32_t column) { ref().line = column; } -bool -SBLineEntry::operator == (const SBLineEntry &rhs) const -{ - lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); - lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); +bool SBLineEntry::operator==(const SBLineEntry &rhs) const { + lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); + lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); - if (lhs_ptr && rhs_ptr) - return lldb_private::LineEntry::Compare (*lhs_ptr, *rhs_ptr) == 0; + if (lhs_ptr && rhs_ptr) + return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) == 0; - return lhs_ptr == rhs_ptr; + return lhs_ptr == rhs_ptr; } -bool -SBLineEntry::operator != (const SBLineEntry &rhs) const -{ - lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); - lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); +bool SBLineEntry::operator!=(const SBLineEntry &rhs) const { + lldb_private::LineEntry *lhs_ptr = m_opaque_ap.get(); + lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_ap.get(); - if (lhs_ptr && rhs_ptr) - return lldb_private::LineEntry::Compare (*lhs_ptr, *rhs_ptr) != 0; + if (lhs_ptr && rhs_ptr) + return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) != 0; - return lhs_ptr != rhs_ptr; + return lhs_ptr != rhs_ptr; } -const lldb_private::LineEntry * -SBLineEntry::operator->() const -{ - return m_opaque_ap.get(); +const lldb_private::LineEntry *SBLineEntry::operator->() const { + return m_opaque_ap.get(); } -lldb_private::LineEntry & -SBLineEntry::ref() -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new lldb_private::LineEntry ()); - return *m_opaque_ap; +lldb_private::LineEntry &SBLineEntry::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new lldb_private::LineEntry()); + return *m_opaque_ap; } -const lldb_private::LineEntry & -SBLineEntry::ref() const -{ - return *m_opaque_ap; -} +const lldb_private::LineEntry &SBLineEntry::ref() const { return *m_opaque_ap; } -bool -SBLineEntry::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBLineEntry::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - if (m_opaque_ap.get()) - { - char file_path[PATH_MAX*2]; - m_opaque_ap->file.GetPath (file_path, sizeof (file_path)); - strm.Printf ("%s:%u", file_path, GetLine()); - if (GetColumn() > 0) - strm.Printf (":%u", GetColumn()); - } - else - strm.PutCString ("No value"); + if (m_opaque_ap.get()) { + char file_path[PATH_MAX * 2]; + m_opaque_ap->file.GetPath(file_path, sizeof(file_path)); + strm.Printf("%s:%u", file_path, GetLine()); + if (GetColumn() > 0) + strm.Printf(":%u", GetColumn()); + } else + strm.PutCString("No value"); - return true; + return true; } -lldb_private::LineEntry * -SBLineEntry::get () -{ - return m_opaque_ap.get(); -} +lldb_private::LineEntry *SBLineEntry::get() { return m_opaque_ap.get(); } diff --git a/lldb/source/API/SBListener.cpp b/lldb/source/API/SBListener.cpp index 28abf3b2a79..cbbfd8eb83f 100644 --- a/lldb/source/API/SBListener.cpp +++ b/lldb/source/API/SBListener.cpp @@ -18,390 +18,293 @@ #include "lldb/Core/Log.h" #include "lldb/Core/StreamString.h" - using namespace lldb; using namespace lldb_private; +SBListener::SBListener() : m_opaque_sp(), m_unused_ptr(NULL) {} -SBListener::SBListener () : - m_opaque_sp (), - m_unused_ptr (NULL) -{ -} - -SBListener::SBListener (const char *name) : - m_opaque_sp (Listener::MakeListener(name)), - m_unused_ptr (nullptr) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBListener::SBListener(const char *name) + : m_opaque_sp(Listener::MakeListener(name)), m_unused_ptr(nullptr) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBListener::SBListener (name=\"%s\") => SBListener(%p)", - name, static_cast(m_opaque_sp.get())); + if (log) + log->Printf("SBListener::SBListener (name=\"%s\") => SBListener(%p)", name, + static_cast(m_opaque_sp.get())); } +SBListener::SBListener(const SBListener &rhs) + : m_opaque_sp(rhs.m_opaque_sp), m_unused_ptr(nullptr) {} -SBListener::SBListener (const SBListener &rhs) : - m_opaque_sp (rhs.m_opaque_sp), - m_unused_ptr (nullptr) -{ +const lldb::SBListener &SBListener::operator=(const lldb::SBListener &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + m_unused_ptr = nullptr; + } + return *this; } -const lldb::SBListener & -SBListener::operator = (const lldb::SBListener &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - m_unused_ptr = nullptr; - } - return *this; -} +SBListener::SBListener(const lldb::ListenerSP &listener_sp) + : m_opaque_sp(listener_sp), m_unused_ptr(nullptr) {} -SBListener::SBListener (const lldb::ListenerSP &listener_sp) : - m_opaque_sp (listener_sp), - m_unused_ptr (nullptr) -{ -} +SBListener::~SBListener() {} -SBListener::~SBListener () -{ -} +bool SBListener::IsValid() const { return m_opaque_sp != nullptr; } -bool -SBListener::IsValid() const -{ - return m_opaque_sp != nullptr; +void SBListener::AddEvent(const SBEvent &event) { + EventSP &event_sp = event.GetSP(); + if (event_sp) + m_opaque_sp->AddEvent(event_sp); } -void -SBListener::AddEvent (const SBEvent &event) -{ - EventSP &event_sp = event.GetSP (); - if (event_sp) - m_opaque_sp->AddEvent (event_sp); +void SBListener::Clear() { + if (m_opaque_sp) + m_opaque_sp->Clear(); } -void -SBListener::Clear () -{ - if (m_opaque_sp) - m_opaque_sp->Clear (); +uint32_t SBListener::StartListeningForEventClass(SBDebugger &debugger, + const char *broadcaster_class, + uint32_t event_mask) { + if (m_opaque_sp) { + Debugger *lldb_debugger = debugger.get(); + if (!lldb_debugger) + return 0; + BroadcastEventSpec event_spec(ConstString(broadcaster_class), event_mask); + return m_opaque_sp->StartListeningForEventSpec( + lldb_debugger->GetBroadcasterManager(), event_spec); + } else + return 0; } -uint32_t -SBListener::StartListeningForEventClass (SBDebugger &debugger, - const char *broadcaster_class, - uint32_t event_mask) -{ - if (m_opaque_sp) - { - Debugger *lldb_debugger = debugger.get(); - if (!lldb_debugger) - return 0; - BroadcastEventSpec event_spec (ConstString (broadcaster_class), event_mask); - return m_opaque_sp->StartListeningForEventSpec (lldb_debugger->GetBroadcasterManager(), event_spec); - } - else - return 0; -} - -bool -SBListener::StopListeningForEventClass (SBDebugger &debugger, - const char *broadcaster_class, - uint32_t event_mask) -{ - if (m_opaque_sp) - { - Debugger *lldb_debugger = debugger.get(); - if (!lldb_debugger) - return false; - BroadcastEventSpec event_spec (ConstString (broadcaster_class), event_mask); - return m_opaque_sp->StopListeningForEventSpec (lldb_debugger->GetBroadcasterManager(), event_spec); - } - else - return false; +bool SBListener::StopListeningForEventClass(SBDebugger &debugger, + const char *broadcaster_class, + uint32_t event_mask) { + if (m_opaque_sp) { + Debugger *lldb_debugger = debugger.get(); + if (!lldb_debugger) + return false; + BroadcastEventSpec event_spec(ConstString(broadcaster_class), event_mask); + return m_opaque_sp->StopListeningForEventSpec( + lldb_debugger->GetBroadcasterManager(), event_spec); + } else + return false; } -uint32_t -SBListener::StartListeningForEvents (const SBBroadcaster& broadcaster, uint32_t event_mask) -{ - uint32_t acquired_event_mask = 0; - if (m_opaque_sp && broadcaster.IsValid()) - { - acquired_event_mask = m_opaque_sp->StartListeningForEvents (broadcaster.get(), event_mask); - } - - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API); - if (log) - { - StreamString sstr_requested; - StreamString sstr_acquired; - - Broadcaster *lldb_broadcaster = broadcaster.get(); - if (lldb_broadcaster) - { - const bool got_requested_names = lldb_broadcaster->GetEventNames (sstr_requested, event_mask, false); - const bool got_acquired_names = lldb_broadcaster->GetEventNames (sstr_acquired, acquired_event_mask, false); - log->Printf ("SBListener(%p)::StartListeneingForEvents (SBBroadcaster(%p): %s, event_mask=0x%8.8x%s%s%s) => 0x%8.8x%s%s%s", - static_cast(m_opaque_sp.get()), - static_cast(lldb_broadcaster), - lldb_broadcaster->GetBroadcasterName().GetCString(), - event_mask, - got_requested_names ? " (" : "", - sstr_requested.GetData(), - got_requested_names ? ")" : "", - acquired_event_mask, - got_acquired_names ? " (" : "", - sstr_acquired.GetData(), - got_acquired_names ? ")" : ""); - } - else - { - log->Printf ("SBListener(%p)::StartListeneingForEvents (SBBroadcaster(%p), event_mask=0x%8.8x) => 0x%8.8x", - static_cast(m_opaque_sp.get()), - static_cast(lldb_broadcaster), event_mask, - acquired_event_mask); - } +uint32_t SBListener::StartListeningForEvents(const SBBroadcaster &broadcaster, + uint32_t event_mask) { + uint32_t acquired_event_mask = 0; + if (m_opaque_sp && broadcaster.IsValid()) { + acquired_event_mask = + m_opaque_sp->StartListeningForEvents(broadcaster.get(), event_mask); + } + + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); + if (log) { + StreamString sstr_requested; + StreamString sstr_acquired; + + Broadcaster *lldb_broadcaster = broadcaster.get(); + if (lldb_broadcaster) { + const bool got_requested_names = + lldb_broadcaster->GetEventNames(sstr_requested, event_mask, false); + const bool got_acquired_names = lldb_broadcaster->GetEventNames( + sstr_acquired, acquired_event_mask, false); + log->Printf("SBListener(%p)::StartListeneingForEvents " + "(SBBroadcaster(%p): %s, event_mask=0x%8.8x%s%s%s) => " + "0x%8.8x%s%s%s", + static_cast(m_opaque_sp.get()), + static_cast(lldb_broadcaster), + lldb_broadcaster->GetBroadcasterName().GetCString(), + event_mask, got_requested_names ? " (" : "", + sstr_requested.GetData(), got_requested_names ? ")" : "", + acquired_event_mask, got_acquired_names ? " (" : "", + sstr_acquired.GetData(), got_acquired_names ? ")" : ""); + } else { + log->Printf("SBListener(%p)::StartListeneingForEvents " + "(SBBroadcaster(%p), event_mask=0x%8.8x) => 0x%8.8x", + static_cast(m_opaque_sp.get()), + static_cast(lldb_broadcaster), event_mask, + acquired_event_mask); } + } - return acquired_event_mask; + return acquired_event_mask; } -bool -SBListener::StopListeningForEvents (const SBBroadcaster& broadcaster, uint32_t event_mask) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - return m_opaque_sp->StopListeningForEvents (broadcaster.get(), event_mask); - } - return false; +bool SBListener::StopListeningForEvents(const SBBroadcaster &broadcaster, + uint32_t event_mask) { + if (m_opaque_sp && broadcaster.IsValid()) { + return m_opaque_sp->StopListeningForEvents(broadcaster.get(), event_mask); + } + return false; } -bool -SBListener::WaitForEvent (uint32_t timeout_secs, SBEvent &event) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (timeout_secs == UINT32_MAX) - { - log->Printf ("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, SBEvent(%p))...", - static_cast(m_opaque_sp.get()), - static_cast(event.get())); - } - else - { - log->Printf ("SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p))...", - static_cast(m_opaque_sp.get()), timeout_secs, - static_cast(event.get())); - } +bool SBListener::WaitForEvent(uint32_t timeout_secs, SBEvent &event) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (timeout_secs == UINT32_MAX) { + log->Printf("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, " + "SBEvent(%p))...", + static_cast(m_opaque_sp.get()), + static_cast(event.get())); + } else { + log->Printf( + "SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p))...", + static_cast(m_opaque_sp.get()), timeout_secs, + static_cast(event.get())); } - bool success = false; - - if (m_opaque_sp) - { - std::chrono::microseconds timeout = std::chrono::microseconds(0); - if (timeout_secs != UINT32_MAX) - { - assert (timeout_secs != 0); // Take this out after all calls with timeout set to zero have been removed.... - timeout = std::chrono::seconds(timeout_secs); - } - EventSP event_sp; - if (m_opaque_sp->WaitForEvent(timeout, event_sp)) - { - event.reset (event_sp); - success = true; - } + } + bool success = false; + + if (m_opaque_sp) { + std::chrono::microseconds timeout = std::chrono::microseconds(0); + if (timeout_secs != UINT32_MAX) { + assert(timeout_secs != 0); // Take this out after all calls with timeout + // set to zero have been removed.... + timeout = std::chrono::seconds(timeout_secs); } - - if (log) - { - if (timeout_secs == UINT32_MAX) - { - log->Printf ("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, SBEvent(%p)) => %i", - static_cast(m_opaque_sp.get()), - static_cast(event.get()), success); - } - else - { - log->Printf ("SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p)) => %i", - static_cast(m_opaque_sp.get()), timeout_secs, - static_cast(event.get()), success); - } + EventSP event_sp; + if (m_opaque_sp->WaitForEvent(timeout, event_sp)) { + event.reset(event_sp); + success = true; + } + } + + if (log) { + if (timeout_secs == UINT32_MAX) { + log->Printf("SBListener(%p)::WaitForEvent (timeout_secs=INFINITE, " + "SBEvent(%p)) => %i", + static_cast(m_opaque_sp.get()), + static_cast(event.get()), success); + } else { + log->Printf( + "SBListener(%p)::WaitForEvent (timeout_secs=%d, SBEvent(%p)) => %i", + static_cast(m_opaque_sp.get()), timeout_secs, + static_cast(event.get()), success); } - if (!success) - event.reset (NULL); - return success; + } + if (!success) + event.reset(NULL); + return success; } -bool -SBListener::WaitForEventForBroadcaster -( - uint32_t num_seconds, - const SBBroadcaster &broadcaster, - SBEvent &event -) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - std::chrono::microseconds timeout = std::chrono::microseconds(0); - if (num_seconds != UINT32_MAX) - timeout = std::chrono::seconds(num_seconds); - EventSP event_sp; - if (m_opaque_sp->WaitForEventForBroadcaster(timeout, broadcaster.get(), event_sp)) - { - event.reset (event_sp); - return true; - } - +bool SBListener::WaitForEventForBroadcaster(uint32_t num_seconds, + const SBBroadcaster &broadcaster, + SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + std::chrono::microseconds timeout = std::chrono::microseconds(0); + if (num_seconds != UINT32_MAX) + timeout = std::chrono::seconds(num_seconds); + EventSP event_sp; + if (m_opaque_sp->WaitForEventForBroadcaster(timeout, broadcaster.get(), + event_sp)) { + event.reset(event_sp); + return true; } - event.reset (NULL); - return false; + } + event.reset(NULL); + return false; } -bool -SBListener::WaitForEventForBroadcasterWithType -( - uint32_t num_seconds, - const SBBroadcaster &broadcaster, - uint32_t event_type_mask, - SBEvent &event -) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - std::chrono::microseconds timeout = std::chrono::microseconds(0); - if (num_seconds != UINT32_MAX) - timeout = std::chrono::seconds(num_seconds); - EventSP event_sp; - if (m_opaque_sp->WaitForEventForBroadcasterWithType(timeout, broadcaster.get(), event_type_mask, event_sp)) - { - event.reset (event_sp); - return true; - } +bool SBListener::WaitForEventForBroadcasterWithType( + uint32_t num_seconds, const SBBroadcaster &broadcaster, + uint32_t event_type_mask, SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + std::chrono::microseconds timeout = std::chrono::microseconds(0); + if (num_seconds != UINT32_MAX) + timeout = std::chrono::seconds(num_seconds); + EventSP event_sp; + if (m_opaque_sp->WaitForEventForBroadcasterWithType( + timeout, broadcaster.get(), event_type_mask, event_sp)) { + event.reset(event_sp); + return true; } - event.reset (NULL); - return false; + } + event.reset(NULL); + return false; } -bool -SBListener::PeekAtNextEvent (SBEvent &event) -{ - if (m_opaque_sp) - { - event.reset (m_opaque_sp->PeekAtNextEvent ()); - return event.IsValid(); - } - event.reset (NULL); - return false; +bool SBListener::PeekAtNextEvent(SBEvent &event) { + if (m_opaque_sp) { + event.reset(m_opaque_sp->PeekAtNextEvent()); + return event.IsValid(); + } + event.reset(NULL); + return false; } -bool -SBListener::PeekAtNextEventForBroadcaster (const SBBroadcaster &broadcaster, SBEvent &event) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - event.reset (m_opaque_sp->PeekAtNextEventForBroadcaster (broadcaster.get())); - return event.IsValid(); - } - event.reset (NULL); - return false; +bool SBListener::PeekAtNextEventForBroadcaster(const SBBroadcaster &broadcaster, + SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + event.reset(m_opaque_sp->PeekAtNextEventForBroadcaster(broadcaster.get())); + return event.IsValid(); + } + event.reset(NULL); + return false; } -bool -SBListener::PeekAtNextEventForBroadcasterWithType (const SBBroadcaster &broadcaster, uint32_t event_type_mask, - SBEvent &event) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - event.reset(m_opaque_sp->PeekAtNextEventForBroadcasterWithType (broadcaster.get(), event_type_mask)); - return event.IsValid(); - } - event.reset (NULL); - return false; +bool SBListener::PeekAtNextEventForBroadcasterWithType( + const SBBroadcaster &broadcaster, uint32_t event_type_mask, + SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + event.reset(m_opaque_sp->PeekAtNextEventForBroadcasterWithType( + broadcaster.get(), event_type_mask)); + return event.IsValid(); + } + event.reset(NULL); + return false; } -bool -SBListener::GetNextEvent (SBEvent &event) -{ - if (m_opaque_sp) - { - EventSP event_sp; - if (m_opaque_sp->GetNextEvent (event_sp)) - { - event.reset (event_sp); - return true; - } +bool SBListener::GetNextEvent(SBEvent &event) { + if (m_opaque_sp) { + EventSP event_sp; + if (m_opaque_sp->GetNextEvent(event_sp)) { + event.reset(event_sp); + return true; } - event.reset (NULL); - return false; + } + event.reset(NULL); + return false; } -bool -SBListener::GetNextEventForBroadcaster (const SBBroadcaster &broadcaster, SBEvent &event) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - EventSP event_sp; - if (m_opaque_sp->GetNextEventForBroadcaster (broadcaster.get(), event_sp)) - { - event.reset (event_sp); - return true; - } +bool SBListener::GetNextEventForBroadcaster(const SBBroadcaster &broadcaster, + SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + EventSP event_sp; + if (m_opaque_sp->GetNextEventForBroadcaster(broadcaster.get(), event_sp)) { + event.reset(event_sp); + return true; } - event.reset (NULL); - return false; + } + event.reset(NULL); + return false; } -bool -SBListener::GetNextEventForBroadcasterWithType -( - const SBBroadcaster &broadcaster, - uint32_t event_type_mask, - SBEvent &event -) -{ - if (m_opaque_sp && broadcaster.IsValid()) - { - EventSP event_sp; - if (m_opaque_sp->GetNextEventForBroadcasterWithType (broadcaster.get(), - event_type_mask, - event_sp)) - { - event.reset (event_sp); - return true; - } +bool SBListener::GetNextEventForBroadcasterWithType( + const SBBroadcaster &broadcaster, uint32_t event_type_mask, + SBEvent &event) { + if (m_opaque_sp && broadcaster.IsValid()) { + EventSP event_sp; + if (m_opaque_sp->GetNextEventForBroadcasterWithType( + broadcaster.get(), event_type_mask, event_sp)) { + event.reset(event_sp); + return true; } - event.reset (NULL); - return false; + } + event.reset(NULL); + return false; } -bool -SBListener::HandleBroadcastEvent (const SBEvent &event) -{ - if (m_opaque_sp) - return m_opaque_sp->HandleBroadcastEvent (event.GetSP()); - return false; +bool SBListener::HandleBroadcastEvent(const SBEvent &event) { + if (m_opaque_sp) + return m_opaque_sp->HandleBroadcastEvent(event.GetSP()); + return false; } -Listener * -SBListener::operator->() const -{ - return m_opaque_sp.get(); -} +Listener *SBListener::operator->() const { return m_opaque_sp.get(); } -Listener * -SBListener::get() const -{ - return m_opaque_sp.get(); -} +Listener *SBListener::get() const { return m_opaque_sp.get(); } -void -SBListener::reset(ListenerSP listener_sp) -{ - m_opaque_sp = listener_sp; - m_unused_ptr = nullptr; +void SBListener::reset(ListenerSP listener_sp) { + m_opaque_sp = listener_sp; + m_unused_ptr = nullptr; } - - diff --git a/lldb/source/API/SBMemoryRegionInfo.cpp b/lldb/source/API/SBMemoryRegionInfo.cpp index 1e4dd769644..3e7227650f7 100644 --- a/lldb/source/API/SBMemoryRegionInfo.cpp +++ b/lldb/source/API/SBMemoryRegionInfo.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// +#include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBDefines.h" #include "lldb/API/SBError.h" -#include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBStream.h" #include "lldb/Core/StreamString.h" #include "lldb/Target/MemoryRegionInfo.h" @@ -17,115 +17,82 @@ using namespace lldb; using namespace lldb_private; +SBMemoryRegionInfo::SBMemoryRegionInfo() + : m_opaque_ap(new MemoryRegionInfo()) {} -SBMemoryRegionInfo::SBMemoryRegionInfo () : - m_opaque_ap (new MemoryRegionInfo()) -{ +SBMemoryRegionInfo::SBMemoryRegionInfo(const MemoryRegionInfo *lldb_object_ptr) + : m_opaque_ap(new MemoryRegionInfo()) { + if (lldb_object_ptr) + ref() = *lldb_object_ptr; } -SBMemoryRegionInfo::SBMemoryRegionInfo (const MemoryRegionInfo *lldb_object_ptr) : - m_opaque_ap (new MemoryRegionInfo()) -{ - if (lldb_object_ptr) - ref() = *lldb_object_ptr; +SBMemoryRegionInfo::SBMemoryRegionInfo(const SBMemoryRegionInfo &rhs) + : m_opaque_ap(new MemoryRegionInfo()) { + ref() = rhs.ref(); } -SBMemoryRegionInfo::SBMemoryRegionInfo(const SBMemoryRegionInfo &rhs) : - m_opaque_ap (new MemoryRegionInfo()) -{ +const SBMemoryRegionInfo &SBMemoryRegionInfo:: +operator=(const SBMemoryRegionInfo &rhs) { + if (this != &rhs) { ref() = rhs.ref(); + } + return *this; } -const SBMemoryRegionInfo & -SBMemoryRegionInfo::operator = (const SBMemoryRegionInfo &rhs) -{ - if (this != &rhs) - { - ref() = rhs.ref(); - } - return *this; -} - -SBMemoryRegionInfo::~SBMemoryRegionInfo () -{ -} +SBMemoryRegionInfo::~SBMemoryRegionInfo() {} -void -SBMemoryRegionInfo::Clear() -{ - m_opaque_ap->Clear(); -} +void SBMemoryRegionInfo::Clear() { m_opaque_ap->Clear(); } -bool -SBMemoryRegionInfo::operator == (const SBMemoryRegionInfo &rhs) const -{ - return ref() == rhs.ref(); +bool SBMemoryRegionInfo::operator==(const SBMemoryRegionInfo &rhs) const { + return ref() == rhs.ref(); } -bool -SBMemoryRegionInfo::operator != (const SBMemoryRegionInfo &rhs) const -{ - return ref() != rhs.ref(); +bool SBMemoryRegionInfo::operator!=(const SBMemoryRegionInfo &rhs) const { + return ref() != rhs.ref(); } -MemoryRegionInfo & -SBMemoryRegionInfo::ref() -{ - return *m_opaque_ap; -} +MemoryRegionInfo &SBMemoryRegionInfo::ref() { return *m_opaque_ap; } -const MemoryRegionInfo & -SBMemoryRegionInfo::ref() const -{ - return *m_opaque_ap; -} +const MemoryRegionInfo &SBMemoryRegionInfo::ref() const { return *m_opaque_ap; } -lldb::addr_t -SBMemoryRegionInfo::GetRegionBase () { - return m_opaque_ap->GetRange().GetRangeBase(); +lldb::addr_t SBMemoryRegionInfo::GetRegionBase() { + return m_opaque_ap->GetRange().GetRangeBase(); } -lldb::addr_t -SBMemoryRegionInfo::GetRegionEnd () { - return m_opaque_ap->GetRange().GetRangeEnd(); +lldb::addr_t SBMemoryRegionInfo::GetRegionEnd() { + return m_opaque_ap->GetRange().GetRangeEnd(); } -bool -SBMemoryRegionInfo::IsReadable () { - return m_opaque_ap->GetReadable() == MemoryRegionInfo::eYes; +bool SBMemoryRegionInfo::IsReadable() { + return m_opaque_ap->GetReadable() == MemoryRegionInfo::eYes; } -bool -SBMemoryRegionInfo::IsWritable () { - return m_opaque_ap->GetWritable() == MemoryRegionInfo::eYes; +bool SBMemoryRegionInfo::IsWritable() { + return m_opaque_ap->GetWritable() == MemoryRegionInfo::eYes; } -bool -SBMemoryRegionInfo::IsExecutable () { - return m_opaque_ap->GetExecutable() == MemoryRegionInfo::eYes; +bool SBMemoryRegionInfo::IsExecutable() { + return m_opaque_ap->GetExecutable() == MemoryRegionInfo::eYes; } -bool -SBMemoryRegionInfo::IsMapped () { - return m_opaque_ap->GetMapped() == MemoryRegionInfo::eYes; +bool SBMemoryRegionInfo::IsMapped() { + return m_opaque_ap->GetMapped() == MemoryRegionInfo::eYes; } -const char * -SBMemoryRegionInfo::GetName () { - return m_opaque_ap->GetName().AsCString(); +const char *SBMemoryRegionInfo::GetName() { + return m_opaque_ap->GetName().AsCString(); } -bool -SBMemoryRegionInfo::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - const addr_t load_addr = m_opaque_ap->GetRange().base; +bool SBMemoryRegionInfo::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + const addr_t load_addr = m_opaque_ap->GetRange().base; - strm.Printf ("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 " ", load_addr, load_addr + m_opaque_ap->GetRange().size); - strm.Printf (m_opaque_ap->GetReadable() ? "R" : "-"); - strm.Printf (m_opaque_ap->GetWritable() ? "W" : "-"); - strm.Printf (m_opaque_ap->GetExecutable() ? "X" : "-"); - strm.Printf ("]"); + strm.Printf("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 " ", load_addr, + load_addr + m_opaque_ap->GetRange().size); + strm.Printf(m_opaque_ap->GetReadable() ? "R" : "-"); + strm.Printf(m_opaque_ap->GetWritable() ? "W" : "-"); + strm.Printf(m_opaque_ap->GetExecutable() ? "X" : "-"); + strm.Printf("]"); - return true; + return true; } diff --git a/lldb/source/API/SBMemoryRegionInfoList.cpp b/lldb/source/API/SBMemoryRegionInfoList.cpp index b2e974785a5..f7ce81af52d 100644 --- a/lldb/source/API/SBMemoryRegionInfoList.cpp +++ b/lldb/source/API/SBMemoryRegionInfoList.cpp @@ -18,145 +18,100 @@ using namespace lldb; using namespace lldb_private; -class MemoryRegionInfoListImpl -{ +class MemoryRegionInfoListImpl { public: - MemoryRegionInfoListImpl () : - m_regions() - { - } - - MemoryRegionInfoListImpl (const MemoryRegionInfoListImpl& rhs) : - m_regions(rhs.m_regions) - { - } - - MemoryRegionInfoListImpl& - operator = (const MemoryRegionInfoListImpl& rhs) - { - if (this == &rhs) - return *this; - m_regions = rhs.m_regions; - return *this; - } - - uint32_t - GetSize () - { - return m_regions.size(); - } - - void - Append (const lldb::SBMemoryRegionInfo& sb_region) - { - m_regions.push_back(sb_region); - } - - void - Append (const MemoryRegionInfoListImpl& list) - { - for (auto val : list.m_regions) - Append (val); - } - - void - Clear () - { - m_regions.clear(); - } - - bool - GetMemoryRegionInfoAtIndex (uint32_t index, SBMemoryRegionInfo ®ion_info) - { - if (index >= GetSize()) - return false; - region_info = m_regions[index]; - return true; - } + MemoryRegionInfoListImpl() : m_regions() {} + + MemoryRegionInfoListImpl(const MemoryRegionInfoListImpl &rhs) + : m_regions(rhs.m_regions) {} + + MemoryRegionInfoListImpl &operator=(const MemoryRegionInfoListImpl &rhs) { + if (this == &rhs) + return *this; + m_regions = rhs.m_regions; + return *this; + } + + uint32_t GetSize() { return m_regions.size(); } + + void Append(const lldb::SBMemoryRegionInfo &sb_region) { + m_regions.push_back(sb_region); + } + + void Append(const MemoryRegionInfoListImpl &list) { + for (auto val : list.m_regions) + Append(val); + } + + void Clear() { m_regions.clear(); } + + bool GetMemoryRegionInfoAtIndex(uint32_t index, + SBMemoryRegionInfo ®ion_info) { + if (index >= GetSize()) + return false; + region_info = m_regions[index]; + return true; + } private: - std::vector m_regions; + std::vector m_regions; }; -SBMemoryRegionInfoList::SBMemoryRegionInfoList () : - m_opaque_ap (new MemoryRegionInfoListImpl()) -{ -} +SBMemoryRegionInfoList::SBMemoryRegionInfoList() + : m_opaque_ap(new MemoryRegionInfoListImpl()) {} -SBMemoryRegionInfoList::SBMemoryRegionInfoList (const SBMemoryRegionInfoList& rhs) : - m_opaque_ap (new MemoryRegionInfoListImpl(*rhs.m_opaque_ap)) -{ -} +SBMemoryRegionInfoList::SBMemoryRegionInfoList( + const SBMemoryRegionInfoList &rhs) + : m_opaque_ap(new MemoryRegionInfoListImpl(*rhs.m_opaque_ap)) {} -SBMemoryRegionInfoList::~SBMemoryRegionInfoList () -{ -} +SBMemoryRegionInfoList::~SBMemoryRegionInfoList() {} -const SBMemoryRegionInfoList & -SBMemoryRegionInfoList::operator = (const SBMemoryRegionInfoList &rhs) -{ - if (this != &rhs) - { - *m_opaque_ap = *rhs.m_opaque_ap; - } - return *this; +const SBMemoryRegionInfoList &SBMemoryRegionInfoList:: +operator=(const SBMemoryRegionInfoList &rhs) { + if (this != &rhs) { + *m_opaque_ap = *rhs.m_opaque_ap; + } + return *this; } -uint32_t -SBMemoryRegionInfoList::GetSize() const -{ - return m_opaque_ap->GetSize(); +uint32_t SBMemoryRegionInfoList::GetSize() const { + return m_opaque_ap->GetSize(); } +bool SBMemoryRegionInfoList::GetMemoryRegionAtIndex( + uint32_t idx, SBMemoryRegionInfo ®ion_info) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -bool -SBMemoryRegionInfoList::GetMemoryRegionAtIndex (uint32_t idx, SBMemoryRegionInfo ®ion_info) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + bool result = m_opaque_ap->GetMemoryRegionInfoAtIndex(idx, region_info); - bool result = m_opaque_ap->GetMemoryRegionInfoAtIndex(idx, region_info); + if (log) { + SBStream sstr; + region_info.GetDescription(sstr); + log->Printf("SBMemoryRegionInfoList::GetMemoryRegionAtIndex (this.ap=%p, " + "idx=%d) => SBMemoryRegionInfo (this.ap=%p, '%s')", + static_cast(m_opaque_ap.get()), idx, + static_cast(region_info.m_opaque_ap.get()), + sstr.GetData()); + } - if (log) - { - SBStream sstr; - region_info.GetDescription (sstr); - log->Printf ("SBMemoryRegionInfoList::GetMemoryRegionAtIndex (this.ap=%p, idx=%d) => SBMemoryRegionInfo (this.ap=%p, '%s')", - static_cast(m_opaque_ap.get()), idx, - static_cast(region_info.m_opaque_ap.get()), sstr.GetData()); - } - - return result; + return result; } -void -SBMemoryRegionInfoList::Clear() -{ - - m_opaque_ap->Clear(); -} +void SBMemoryRegionInfoList::Clear() { m_opaque_ap->Clear(); } -void -SBMemoryRegionInfoList::Append(SBMemoryRegionInfo &sb_region) -{ - m_opaque_ap->Append(sb_region); +void SBMemoryRegionInfoList::Append(SBMemoryRegionInfo &sb_region) { + m_opaque_ap->Append(sb_region); } -void -SBMemoryRegionInfoList::Append(SBMemoryRegionInfoList &sb_region_list) -{ - m_opaque_ap->Append(*sb_region_list); +void SBMemoryRegionInfoList::Append(SBMemoryRegionInfoList &sb_region_list) { + m_opaque_ap->Append(*sb_region_list); } -const MemoryRegionInfoListImpl * -SBMemoryRegionInfoList::operator->() const -{ - return m_opaque_ap.get(); +const MemoryRegionInfoListImpl *SBMemoryRegionInfoList::operator->() const { + return m_opaque_ap.get(); } -const MemoryRegionInfoListImpl& -SBMemoryRegionInfoList::operator*() const -{ - assert (m_opaque_ap.get()); - return *m_opaque_ap.get(); +const MemoryRegionInfoListImpl &SBMemoryRegionInfoList::operator*() const { + assert(m_opaque_ap.get()); + return *m_opaque_ap.get(); } - diff --git a/lldb/source/API/SBModule.cpp b/lldb/source/API/SBModule.cpp index bf015f7f2e5..89643033a1d 100644 --- a/lldb/source/API/SBModule.cpp +++ b/lldb/source/API/SBModule.cpp @@ -14,8 +14,8 @@ #include "lldb/API/SBProcess.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBSymbolContextList.h" -#include "lldb/Core/Module.h" #include "lldb/Core/Log.h" +#include "lldb/Core/Module.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/ValueObjectList.h" @@ -31,699 +31,537 @@ using namespace lldb; using namespace lldb_private; +SBModule::SBModule() : m_opaque_sp() {} -SBModule::SBModule () : - m_opaque_sp () -{ -} - -SBModule::SBModule (const lldb::ModuleSP& module_sp) : - m_opaque_sp (module_sp) -{ -} +SBModule::SBModule(const lldb::ModuleSP &module_sp) : m_opaque_sp(module_sp) {} -SBModule::SBModule(const SBModuleSpec &module_spec) : - m_opaque_sp () -{ - ModuleSP module_sp; - Error error = ModuleList::GetSharedModule (*module_spec.m_opaque_ap, - module_sp, - NULL, - NULL, - NULL); - if (module_sp) - SetSP(module_sp); +SBModule::SBModule(const SBModuleSpec &module_spec) : m_opaque_sp() { + ModuleSP module_sp; + Error error = ModuleList::GetSharedModule(*module_spec.m_opaque_ap, module_sp, + NULL, NULL, NULL); + if (module_sp) + SetSP(module_sp); } -SBModule::SBModule(const SBModule &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBModule::SBModule(const SBModule &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} -SBModule::SBModule (lldb::SBProcess &process, lldb::addr_t header_addr) : - m_opaque_sp () -{ - ProcessSP process_sp (process.GetSP()); - if (process_sp) - { - m_opaque_sp = process_sp->ReadModuleFromMemory (FileSpec(), header_addr); - if (m_opaque_sp) - { - Target &target = process_sp->GetTarget(); - bool changed = false; - m_opaque_sp->SetLoadAddress(target, 0, true, changed); - target.GetImages().Append(m_opaque_sp); - } +SBModule::SBModule(lldb::SBProcess &process, lldb::addr_t header_addr) + : m_opaque_sp() { + ProcessSP process_sp(process.GetSP()); + if (process_sp) { + m_opaque_sp = process_sp->ReadModuleFromMemory(FileSpec(), header_addr); + if (m_opaque_sp) { + Target &target = process_sp->GetTarget(); + bool changed = false; + m_opaque_sp->SetLoadAddress(target, 0, true, changed); + target.GetImages().Append(m_opaque_sp); } + } } -const SBModule & -SBModule::operator = (const SBModule &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBModule &SBModule::operator=(const SBModule &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -SBModule::~SBModule () -{ -} +SBModule::~SBModule() {} -bool -SBModule::IsValid () const -{ - return m_opaque_sp.get() != NULL; -} +bool SBModule::IsValid() const { return m_opaque_sp.get() != NULL; } -void -SBModule::Clear() -{ - m_opaque_sp.reset(); -} +void SBModule::Clear() { m_opaque_sp.reset(); } -SBFileSpec -SBModule::GetFileSpec () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBFileSpec SBModule::GetFileSpec() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBFileSpec file_spec; - ModuleSP module_sp (GetSP ()); - if (module_sp) - file_spec.SetFileSpec(module_sp->GetFileSpec()); + SBFileSpec file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + file_spec.SetFileSpec(module_sp->GetFileSpec()); - if (log) - log->Printf ("SBModule(%p)::GetFileSpec () => SBFileSpec(%p)", - static_cast(module_sp.get()), - static_cast(file_spec.get())); + if (log) + log->Printf("SBModule(%p)::GetFileSpec () => SBFileSpec(%p)", + static_cast(module_sp.get()), + static_cast(file_spec.get())); - return file_spec; + return file_spec; } -lldb::SBFileSpec -SBModule::GetPlatformFileSpec () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +lldb::SBFileSpec SBModule::GetPlatformFileSpec() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBFileSpec file_spec; - ModuleSP module_sp (GetSP ()); - if (module_sp) - file_spec.SetFileSpec(module_sp->GetPlatformFileSpec()); + SBFileSpec file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + file_spec.SetFileSpec(module_sp->GetPlatformFileSpec()); - if (log) - log->Printf ("SBModule(%p)::GetPlatformFileSpec () => SBFileSpec(%p)", - static_cast(module_sp.get()), - static_cast(file_spec.get())); + if (log) + log->Printf("SBModule(%p)::GetPlatformFileSpec () => SBFileSpec(%p)", + static_cast(module_sp.get()), + static_cast(file_spec.get())); - return file_spec; + return file_spec; } -bool -SBModule::SetPlatformFileSpec (const lldb::SBFileSpec &platform_file) -{ - bool result = false; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBModule::SetPlatformFileSpec(const lldb::SBFileSpec &platform_file) { + bool result = false; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - module_sp->SetPlatformFileSpec(*platform_file); - result = true; - } + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->SetPlatformFileSpec(*platform_file); + result = true; + } - if (log) - log->Printf ("SBModule(%p)::SetPlatformFileSpec (SBFileSpec(%p (%s)) => %i", - static_cast(module_sp.get()), - static_cast(platform_file.get()), - platform_file->GetPath().c_str(), result); - return result; -} - -lldb::SBFileSpec -SBModule::GetRemoteInstallFileSpec () -{ - SBFileSpec sb_file_spec; - ModuleSP module_sp (GetSP ()); - if (module_sp) - sb_file_spec.SetFileSpec (module_sp->GetRemoteInstallFileSpec()); - return sb_file_spec; -} - -bool -SBModule::SetRemoteInstallFileSpec (lldb::SBFileSpec &file) -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - module_sp->SetRemoteInstallFileSpec(file.ref()); - return true; - } - return false; + if (log) + log->Printf("SBModule(%p)::SetPlatformFileSpec (SBFileSpec(%p (%s)) => %i", + static_cast(module_sp.get()), + static_cast(platform_file.get()), + platform_file->GetPath().c_str(), result); + return result; } - -const uint8_t * -SBModule::GetUUIDBytes () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - const uint8_t *uuid_bytes = NULL; - ModuleSP module_sp (GetSP ()); - if (module_sp) - uuid_bytes = (const uint8_t *)module_sp->GetUUID().GetBytes(); - - if (log) - { - if (uuid_bytes) - { - StreamString s; - module_sp->GetUUID().Dump (&s); - log->Printf ("SBModule(%p)::GetUUIDBytes () => %s", - static_cast(module_sp.get()), s.GetData()); - } - else - log->Printf ("SBModule(%p)::GetUUIDBytes () => NULL", - static_cast(module_sp.get())); - } - return uuid_bytes; +lldb::SBFileSpec SBModule::GetRemoteInstallFileSpec() { + SBFileSpec sb_file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) + sb_file_spec.SetFileSpec(module_sp->GetRemoteInstallFileSpec()); + return sb_file_spec; } - -const char * -SBModule::GetUUIDString () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - const char *uuid_cstr = NULL; - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - // We are going to return a "const char *" value through the public - // API, so we need to constify it so it gets added permanently the - // string pool and then we don't need to worry about the lifetime of the - // string as it will never go away once it has been put into the ConstString - // string pool - uuid_cstr = ConstString(module_sp->GetUUID().GetAsString()).GetCString(); - } - - if (uuid_cstr && uuid_cstr[0]) - { - if (log) - log->Printf ("SBModule(%p)::GetUUIDString () => %s", static_cast(module_sp.get()), uuid_cstr); - return uuid_cstr; - } - +bool SBModule::SetRemoteInstallFileSpec(lldb::SBFileSpec &file) { + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->SetRemoteInstallFileSpec(file.ref()); + return true; + } + return false; +} + +const uint8_t *SBModule::GetUUIDBytes() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + const uint8_t *uuid_bytes = NULL; + ModuleSP module_sp(GetSP()); + if (module_sp) + uuid_bytes = (const uint8_t *)module_sp->GetUUID().GetBytes(); + + if (log) { + if (uuid_bytes) { + StreamString s; + module_sp->GetUUID().Dump(&s); + log->Printf("SBModule(%p)::GetUUIDBytes () => %s", + static_cast(module_sp.get()), s.GetData()); + } else + log->Printf("SBModule(%p)::GetUUIDBytes () => NULL", + static_cast(module_sp.get())); + } + return uuid_bytes; +} + +const char *SBModule::GetUUIDString() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + const char *uuid_cstr = NULL; + ModuleSP module_sp(GetSP()); + if (module_sp) { + // We are going to return a "const char *" value through the public + // API, so we need to constify it so it gets added permanently the + // string pool and then we don't need to worry about the lifetime of the + // string as it will never go away once it has been put into the ConstString + // string pool + uuid_cstr = ConstString(module_sp->GetUUID().GetAsString()).GetCString(); + } + + if (uuid_cstr && uuid_cstr[0]) { if (log) - log->Printf ("SBModule(%p)::GetUUIDString () => NULL", static_cast(module_sp.get())); - return NULL; -} - + log->Printf("SBModule(%p)::GetUUIDString () => %s", + static_cast(module_sp.get()), uuid_cstr); + return uuid_cstr; + } -bool -SBModule::operator == (const SBModule &rhs) const -{ - if (m_opaque_sp) - return m_opaque_sp.get() == rhs.m_opaque_sp.get(); - return false; + if (log) + log->Printf("SBModule(%p)::GetUUIDString () => NULL", + static_cast(module_sp.get())); + return NULL; } -bool -SBModule::operator != (const SBModule &rhs) const -{ - if (m_opaque_sp) - return m_opaque_sp.get() != rhs.m_opaque_sp.get(); - return false; +bool SBModule::operator==(const SBModule &rhs) const { + if (m_opaque_sp) + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); + return false; } -ModuleSP -SBModule::GetSP () const -{ - return m_opaque_sp; +bool SBModule::operator!=(const SBModule &rhs) const { + if (m_opaque_sp) + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); + return false; } -void -SBModule::SetSP (const ModuleSP &module_sp) -{ - m_opaque_sp = module_sp; -} +ModuleSP SBModule::GetSP() const { return m_opaque_sp; } -SBAddress -SBModule::ResolveFileAddress (lldb::addr_t vm_addr) -{ - lldb::SBAddress sb_addr; - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - Address addr; - if (module_sp->ResolveFileAddress (vm_addr, addr)) - sb_addr.ref() = addr; - } - return sb_addr; +void SBModule::SetSP(const ModuleSP &module_sp) { m_opaque_sp = module_sp; } + +SBAddress SBModule::ResolveFileAddress(lldb::addr_t vm_addr) { + lldb::SBAddress sb_addr; + ModuleSP module_sp(GetSP()); + if (module_sp) { + Address addr; + if (module_sp->ResolveFileAddress(vm_addr, addr)) + sb_addr.ref() = addr; + } + return sb_addr; } SBSymbolContext -SBModule::ResolveSymbolContextForAddress (const SBAddress& addr, uint32_t resolve_scope) -{ - SBSymbolContext sb_sc; - ModuleSP module_sp (GetSP ()); - if (module_sp && addr.IsValid()) - module_sp->ResolveSymbolContextForAddress (addr.ref(), resolve_scope, *sb_sc); - return sb_sc; -} - -bool -SBModule::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - module_sp->GetDescription (&strm); - } - else - strm.PutCString ("No value"); - - return true; +SBModule::ResolveSymbolContextForAddress(const SBAddress &addr, + uint32_t resolve_scope) { + SBSymbolContext sb_sc; + ModuleSP module_sp(GetSP()); + if (module_sp && addr.IsValid()) + module_sp->ResolveSymbolContextForAddress(addr.ref(), resolve_scope, + *sb_sc); + return sb_sc; +} + +bool SBModule::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + + ModuleSP module_sp(GetSP()); + if (module_sp) { + module_sp->GetDescription(&strm); + } else + strm.PutCString("No value"); + + return true; +} + +uint32_t SBModule::GetNumCompileUnits() { + ModuleSP module_sp(GetSP()); + if (module_sp) { + return module_sp->GetNumCompileUnits(); + } + return 0; +} + +SBCompileUnit SBModule::GetCompileUnitAtIndex(uint32_t index) { + SBCompileUnit sb_cu; + ModuleSP module_sp(GetSP()); + if (module_sp) { + CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(index); + sb_cu.reset(cu_sp.get()); + } + return sb_cu; +} + +static Symtab *GetUnifiedSymbolTable(const lldb::ModuleSP &module_sp) { + if (module_sp) { + SymbolVendor *symbols = module_sp->GetSymbolVendor(); + if (symbols) + return symbols->GetSymtab(); + } + return NULL; +} + +size_t SBModule::GetNumSymbols() { + ModuleSP module_sp(GetSP()); + if (module_sp) { + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) + return symtab->GetNumSymbols(); + } + return 0; } -uint32_t -SBModule::GetNumCompileUnits() -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - return module_sp->GetNumCompileUnits (); - } - return 0; +SBSymbol SBModule::GetSymbolAtIndex(size_t idx) { + SBSymbol sb_symbol; + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) + sb_symbol.SetSymbol(symtab->SymbolAtIndex(idx)); + return sb_symbol; } -SBCompileUnit -SBModule::GetCompileUnitAtIndex (uint32_t index) -{ - SBCompileUnit sb_cu; - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex (index); - sb_cu.reset(cu_sp.get()); - } - return sb_cu; +lldb::SBSymbol SBModule::FindSymbol(const char *name, + lldb::SymbolType symbol_type) { + SBSymbol sb_symbol; + if (name && name[0]) { + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) + sb_symbol.SetSymbol(symtab->FindFirstSymbolWithNameAndType( + ConstString(name), symbol_type, Symtab::eDebugAny, + Symtab::eVisibilityAny)); + } + return sb_symbol; } -static Symtab * -GetUnifiedSymbolTable (const lldb::ModuleSP& module_sp) -{ - if (module_sp) - { - SymbolVendor *symbols = module_sp->GetSymbolVendor(); - if (symbols) - return symbols->GetSymtab(); +lldb::SBSymbolContextList SBModule::FindSymbols(const char *name, + lldb::SymbolType symbol_type) { + SBSymbolContextList sb_sc_list; + if (name && name[0]) { + ModuleSP module_sp(GetSP()); + Symtab *symtab = GetUnifiedSymbolTable(module_sp); + if (symtab) { + std::vector matching_symbol_indexes; + const size_t num_matches = symtab->FindAllSymbolsWithNameAndType( + ConstString(name), symbol_type, matching_symbol_indexes); + if (num_matches) { + SymbolContext sc; + sc.module_sp = module_sp; + SymbolContextList &sc_list = *sb_sc_list; + for (size_t i = 0; i < num_matches; ++i) { + sc.symbol = symtab->SymbolAtIndex(matching_symbol_indexes[i]); + if (sc.symbol) + sc_list.Append(sc); + } + } } - return NULL; -} - -size_t -SBModule::GetNumSymbols () -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - Symtab *symtab = GetUnifiedSymbolTable (module_sp); - if (symtab) - return symtab->GetNumSymbols(); + } + return sb_sc_list; +} + +size_t SBModule::GetNumSections() { + ModuleSP module_sp(GetSP()); + if (module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolVendor(); + SectionList *section_list = module_sp->GetSectionList(); + if (section_list) + return section_list->GetSize(); + } + return 0; +} + +SBSection SBModule::GetSectionAtIndex(size_t idx) { + SBSection sb_section; + ModuleSP module_sp(GetSP()); + if (module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolVendor(); + SectionList *section_list = module_sp->GetSectionList(); + + if (section_list) + sb_section.SetSP(section_list->GetSectionAtIndex(idx)); + } + return sb_section; +} + +lldb::SBSymbolContextList SBModule::FindFunctions(const char *name, + uint32_t name_type_mask) { + lldb::SBSymbolContextList sb_sc_list; + ModuleSP module_sp(GetSP()); + if (name && module_sp) { + const bool append = true; + const bool symbols_ok = true; + const bool inlines_ok = true; + module_sp->FindFunctions(ConstString(name), NULL, name_type_mask, + symbols_ok, inlines_ok, append, *sb_sc_list); + } + return sb_sc_list; +} + +SBValueList SBModule::FindGlobalVariables(SBTarget &target, const char *name, + uint32_t max_matches) { + SBValueList sb_value_list; + ModuleSP module_sp(GetSP()); + if (name && module_sp) { + VariableList variable_list; + const uint32_t match_count = module_sp->FindGlobalVariables( + ConstString(name), NULL, false, max_matches, variable_list); + + if (match_count > 0) { + for (uint32_t i = 0; i < match_count; ++i) { + lldb::ValueObjectSP valobj_sp; + TargetSP target_sp(target.GetSP()); + valobj_sp = ValueObjectVariable::Create( + target_sp.get(), variable_list.GetVariableAtIndex(i)); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } } - return 0; + } + + return sb_value_list; } -SBSymbol -SBModule::GetSymbolAtIndex (size_t idx) -{ - SBSymbol sb_symbol; - ModuleSP module_sp (GetSP ()); - Symtab *symtab = GetUnifiedSymbolTable (module_sp); - if (symtab) - sb_symbol.SetSymbol(symtab->SymbolAtIndex (idx)); - return sb_symbol; -} - -lldb::SBSymbol -SBModule::FindSymbol (const char *name, - lldb::SymbolType symbol_type) -{ - SBSymbol sb_symbol; - if (name && name[0]) - { - ModuleSP module_sp (GetSP ()); - Symtab *symtab = GetUnifiedSymbolTable (module_sp); - if (symtab) - sb_symbol.SetSymbol(symtab->FindFirstSymbolWithNameAndType(ConstString(name), symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny)); - } - return sb_symbol; -} - - -lldb::SBSymbolContextList -SBModule::FindSymbols (const char *name, lldb::SymbolType symbol_type) -{ - SBSymbolContextList sb_sc_list; - if (name && name[0]) - { - ModuleSP module_sp (GetSP ()); - Symtab *symtab = GetUnifiedSymbolTable (module_sp); - if (symtab) - { - std::vector matching_symbol_indexes; - const size_t num_matches = symtab->FindAllSymbolsWithNameAndType(ConstString(name), symbol_type, matching_symbol_indexes); - if (num_matches) - { - SymbolContext sc; - sc.module_sp = module_sp; - SymbolContextList &sc_list = *sb_sc_list; - for (size_t i=0; iSymbolAtIndex (matching_symbol_indexes[i]); - if (sc.symbol) - sc_list.Append(sc); - } - } - } - } - return sb_sc_list; - +lldb::SBValue SBModule::FindFirstGlobalVariable(lldb::SBTarget &target, + const char *name) { + SBValueList sb_value_list(FindGlobalVariables(target, name, 1)); + if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0) + return sb_value_list.GetValueAtIndex(0); + return SBValue(); } +lldb::SBType SBModule::FindFirstType(const char *name_cstr) { + SBType sb_type; + ModuleSP module_sp(GetSP()); + if (name_cstr && module_sp) { + SymbolContext sc; + const bool exact_match = false; + ConstString name(name_cstr); + sb_type = SBType(module_sp->FindFirstType(sc, name, exact_match)); -size_t -SBModule::GetNumSections () -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - // Give the symbol vendor a chance to add to the unified section list. - module_sp->GetSymbolVendor(); - SectionList *section_list = module_sp->GetSectionList(); - if (section_list) - return section_list->GetSize(); + if (!sb_type.IsValid()) { + TypeSystem *type_system = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (type_system) + sb_type = SBType(type_system->GetBuiltinTypeByName(name)); } - return 0; -} + } + return sb_type; +} + +lldb::SBType SBModule::GetBasicType(lldb::BasicType type) { + ModuleSP module_sp(GetSP()); + if (module_sp) { + TypeSystem *type_system = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (type_system) + return SBType(type_system->GetBasicTypeFromAST(type)); + } + return SBType(); +} + +lldb::SBTypeList SBModule::FindTypes(const char *type) { + SBTypeList retval; + + ModuleSP module_sp(GetSP()); + if (type && module_sp) { + SymbolContext sc; + TypeList type_list; + const bool exact_match = false; + ConstString name(type); + llvm::DenseSet searched_symbol_files; + const uint32_t num_matches = module_sp->FindTypes( + sc, name, exact_match, UINT32_MAX, searched_symbol_files, type_list); + + if (num_matches > 0) { + for (size_t idx = 0; idx < num_matches; idx++) { + TypeSP type_sp(type_list.GetTypeAtIndex(idx)); + if (type_sp) + retval.Append(SBType(type_sp)); + } + } else { + TypeSystem *type_system = + module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (type_system) { + CompilerType compiler_type = type_system->GetBuiltinTypeByName(name); + if (compiler_type) + retval.Append(SBType(compiler_type)); + } + } + } -SBSection -SBModule::GetSectionAtIndex (size_t idx) -{ - SBSection sb_section; - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - // Give the symbol vendor a chance to add to the unified section list. - module_sp->GetSymbolVendor(); - SectionList *section_list = module_sp->GetSectionList (); + return retval; +} - if (section_list) - sb_section.SetSP(section_list->GetSectionAtIndex (idx)); - } - return sb_section; -} - -lldb::SBSymbolContextList -SBModule::FindFunctions (const char *name, - uint32_t name_type_mask) -{ - lldb::SBSymbolContextList sb_sc_list; - ModuleSP module_sp (GetSP ()); - if (name && module_sp) - { - const bool append = true; - const bool symbols_ok = true; - const bool inlines_ok = true; - module_sp->FindFunctions (ConstString(name), - NULL, - name_type_mask, - symbols_ok, - inlines_ok, - append, - *sb_sc_list); +lldb::SBType SBModule::GetTypeByID(lldb::user_id_t uid) { + ModuleSP module_sp(GetSP()); + if (module_sp) { + SymbolVendor *vendor = module_sp->GetSymbolVendor(); + if (vendor) { + Type *type_ptr = vendor->ResolveTypeUID(uid); + if (type_ptr) + return SBType(type_ptr->shared_from_this()); } - return sb_sc_list; -} - - -SBValueList -SBModule::FindGlobalVariables (SBTarget &target, const char *name, uint32_t max_matches) -{ - SBValueList sb_value_list; - ModuleSP module_sp (GetSP ()); - if (name && module_sp) - { - VariableList variable_list; - const uint32_t match_count = module_sp->FindGlobalVariables (ConstString (name), - NULL, - false, - max_matches, - variable_list); - - if (match_count > 0) - { - for (uint32_t i=0; i 0) - return sb_value_list.GetValueAtIndex(0); - return SBValue(); -} - -lldb::SBType -SBModule::FindFirstType (const char *name_cstr) -{ - SBType sb_type; - ModuleSP module_sp (GetSP ()); - if (name_cstr && module_sp) - { - SymbolContext sc; - const bool exact_match = false; - ConstString name(name_cstr); - - sb_type = SBType (module_sp->FindFirstType(sc, name, exact_match)); - - if (!sb_type.IsValid()) - { - TypeSystem *type_system = module_sp->GetTypeSystemForLanguage(eLanguageTypeC); - if (type_system) - sb_type = SBType (type_system->GetBuiltinTypeByName(name)); - } - } - return sb_type; -} - -lldb::SBType -SBModule::GetBasicType(lldb::BasicType type) -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - TypeSystem *type_system = module_sp->GetTypeSystemForLanguage(eLanguageTypeC); - if (type_system) - return SBType (type_system->GetBasicTypeFromAST(type)); - } - return SBType(); + } + return SBType(); } -lldb::SBTypeList -SBModule::FindTypes (const char *type) -{ - SBTypeList retval; - - ModuleSP module_sp (GetSP ()); - if (type && module_sp) - { - SymbolContext sc; - TypeList type_list; - const bool exact_match = false; - ConstString name(type); - llvm::DenseSet searched_symbol_files; - const uint32_t num_matches = module_sp->FindTypes (sc, - name, - exact_match, - UINT32_MAX, - searched_symbol_files, - type_list); - - if (num_matches > 0) - { - for (size_t idx = 0; idx < num_matches; idx++) - { - TypeSP type_sp (type_list.GetTypeAtIndex(idx)); - if (type_sp) - retval.Append(SBType(type_sp)); - } - } - else - { - TypeSystem *type_system = module_sp->GetTypeSystemForLanguage(eLanguageTypeC); - if (type_system) - { - CompilerType compiler_type = type_system->GetBuiltinTypeByName(name); - if (compiler_type) - retval.Append(SBType(compiler_type)); - } - } - } +lldb::SBTypeList SBModule::GetTypes(uint32_t type_mask) { + SBTypeList sb_type_list; - return retval; -} - -lldb::SBType -SBModule::GetTypeByID (lldb::user_id_t uid) -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - SymbolVendor* vendor = module_sp->GetSymbolVendor(); - if (vendor) - { - Type *type_ptr = vendor->ResolveTypeUID(uid); - if (type_ptr) - return SBType(type_ptr->shared_from_this()); - } + ModuleSP module_sp(GetSP()); + if (module_sp) { + SymbolVendor *vendor = module_sp->GetSymbolVendor(); + if (vendor) { + TypeList type_list; + vendor->GetTypes(NULL, type_mask, type_list); + sb_type_list.m_opaque_ap->Append(type_list); } - return SBType(); -} - -lldb::SBTypeList -SBModule::GetTypes (uint32_t type_mask) -{ - SBTypeList sb_type_list; - - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - SymbolVendor* vendor = module_sp->GetSymbolVendor(); - if (vendor) - { - TypeList type_list; - vendor->GetTypes (NULL, type_mask, type_list); - sb_type_list.m_opaque_ap->Append(type_list); - } + } + return sb_type_list; +} + +SBSection SBModule::FindSection(const char *sect_name) { + SBSection sb_section; + + ModuleSP module_sp(GetSP()); + if (sect_name && module_sp) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolVendor(); + SectionList *section_list = module_sp->GetSectionList(); + if (section_list) { + ConstString const_sect_name(sect_name); + SectionSP section_sp(section_list->FindSectionByName(const_sect_name)); + if (section_sp) { + sb_section.SetSP(section_sp); + } } - return sb_type_list; -} - -SBSection -SBModule::FindSection (const char *sect_name) -{ - SBSection sb_section; - - ModuleSP module_sp (GetSP ()); - if (sect_name && module_sp) - { - // Give the symbol vendor a chance to add to the unified section list. - module_sp->GetSymbolVendor(); - SectionList *section_list = module_sp->GetSectionList(); - if (section_list) - { - ConstString const_sect_name(sect_name); - SectionSP section_sp (section_list->FindSectionByName(const_sect_name)); - if (section_sp) - { - sb_section.SetSP (section_sp); - } - } + } + return sb_section; +} + +lldb::ByteOrder SBModule::GetByteOrder() { + ModuleSP module_sp(GetSP()); + if (module_sp) + return module_sp->GetArchitecture().GetByteOrder(); + return eByteOrderInvalid; +} + +const char *SBModule::GetTriple() { + ModuleSP module_sp(GetSP()); + if (module_sp) { + std::string triple(module_sp->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since + // the const strings put the string into the string pool once and + // the strings never comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); + } + return NULL; +} + +uint32_t SBModule::GetAddressByteSize() { + ModuleSP module_sp(GetSP()); + if (module_sp) + return module_sp->GetArchitecture().GetAddressByteSize(); + return sizeof(void *); +} + +uint32_t SBModule::GetVersion(uint32_t *versions, uint32_t num_versions) { + ModuleSP module_sp(GetSP()); + if (module_sp) + return module_sp->GetVersion(versions, num_versions); + else { + if (versions && num_versions) { + for (uint32_t i = 0; i < num_versions; ++i) + versions[i] = UINT32_MAX; } - return sb_section; -} - -lldb::ByteOrder -SBModule::GetByteOrder () -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - return module_sp->GetArchitecture().GetByteOrder(); - return eByteOrderInvalid; -} - -const char * -SBModule::GetTriple () -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - std::string triple (module_sp->GetArchitecture().GetTriple().str()); - // Unique the string so we don't run into ownership issues since - // the const strings put the string into the string pool once and - // the strings never comes out - ConstString const_triple (triple.c_str()); - return const_triple.GetCString(); - } - return NULL; -} - -uint32_t -SBModule::GetAddressByteSize() -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - return module_sp->GetArchitecture().GetAddressByteSize(); - return sizeof(void*); -} - - -uint32_t -SBModule::GetVersion (uint32_t *versions, uint32_t num_versions) -{ - ModuleSP module_sp (GetSP ()); - if (module_sp) - return module_sp->GetVersion(versions, num_versions); - else - { - if (versions && num_versions) - { - for (uint32_t i=0; iGetSymbolVendor(); - if (symbol_vendor_ptr) - sb_file_spec.SetFileSpec(symbol_vendor_ptr->GetMainFileSpec()); - } - return sb_file_spec; -} - -lldb::SBAddress -SBModule::GetObjectFileHeaderAddress() const -{ - lldb::SBAddress sb_addr; - ModuleSP module_sp (GetSP ()); - if (module_sp) - { - ObjectFile *objfile_ptr = module_sp->GetObjectFile(); - if (objfile_ptr) - sb_addr.ref() = objfile_ptr->GetHeaderAddress(); - } - return sb_addr; + return 0; + } +} + +lldb::SBFileSpec SBModule::GetSymbolFileSpec() const { + lldb::SBFileSpec sb_file_spec; + ModuleSP module_sp(GetSP()); + if (module_sp) { + SymbolVendor *symbol_vendor_ptr = module_sp->GetSymbolVendor(); + if (symbol_vendor_ptr) + sb_file_spec.SetFileSpec(symbol_vendor_ptr->GetMainFileSpec()); + } + return sb_file_spec; +} + +lldb::SBAddress SBModule::GetObjectFileHeaderAddress() const { + lldb::SBAddress sb_addr; + ModuleSP module_sp(GetSP()); + if (module_sp) { + ObjectFile *objfile_ptr = module_sp->GetObjectFile(); + if (objfile_ptr) + sb_addr.ref() = objfile_ptr->GetHeaderAddress(); + } + return sb_addr; } diff --git a/lldb/source/API/SBModuleSpec.cpp b/lldb/source/API/SBModuleSpec.cpp index 17c83abb4f2..b82b822859b 100644 --- a/lldb/source/API/SBModuleSpec.cpp +++ b/lldb/source/API/SBModuleSpec.cpp @@ -18,213 +18,140 @@ using namespace lldb; using namespace lldb_private; +SBModuleSpec::SBModuleSpec() : m_opaque_ap(new lldb_private::ModuleSpec()) {} -SBModuleSpec::SBModuleSpec () : - m_opaque_ap (new lldb_private::ModuleSpec()) -{ -} +SBModuleSpec::SBModuleSpec(const SBModuleSpec &rhs) + : m_opaque_ap(new lldb_private::ModuleSpec(*rhs.m_opaque_ap)) {} -SBModuleSpec::SBModuleSpec(const SBModuleSpec &rhs) : - m_opaque_ap (new lldb_private::ModuleSpec(*rhs.m_opaque_ap)) -{ +const SBModuleSpec &SBModuleSpec::operator=(const SBModuleSpec &rhs) { + if (this != &rhs) + *m_opaque_ap = *(rhs.m_opaque_ap); + return *this; } -const SBModuleSpec & -SBModuleSpec::operator = (const SBModuleSpec &rhs) -{ - if (this != &rhs) - *m_opaque_ap = *(rhs.m_opaque_ap); - return *this; -} +SBModuleSpec::~SBModuleSpec() {} -SBModuleSpec::~SBModuleSpec () -{ -} +bool SBModuleSpec::IsValid() const { return m_opaque_ap->operator bool(); } -bool -SBModuleSpec::IsValid () const -{ - return m_opaque_ap->operator bool(); -} +void SBModuleSpec::Clear() { m_opaque_ap->Clear(); } -void -SBModuleSpec::Clear() -{ - m_opaque_ap->Clear(); +SBFileSpec SBModuleSpec::GetFileSpec() { + SBFileSpec sb_spec(m_opaque_ap->GetFileSpec()); + return sb_spec; } -SBFileSpec -SBModuleSpec::GetFileSpec () -{ - SBFileSpec sb_spec(m_opaque_ap->GetFileSpec()); - return sb_spec; +void SBModuleSpec::SetFileSpec(const lldb::SBFileSpec &sb_spec) { + m_opaque_ap->GetFileSpec() = *sb_spec; } -void -SBModuleSpec::SetFileSpec (const lldb::SBFileSpec &sb_spec) -{ - m_opaque_ap->GetFileSpec() = *sb_spec; +lldb::SBFileSpec SBModuleSpec::GetPlatformFileSpec() { + return SBFileSpec(m_opaque_ap->GetPlatformFileSpec()); } -lldb::SBFileSpec -SBModuleSpec::GetPlatformFileSpec () -{ - return SBFileSpec(m_opaque_ap->GetPlatformFileSpec()); +void SBModuleSpec::SetPlatformFileSpec(const lldb::SBFileSpec &sb_spec) { + m_opaque_ap->GetPlatformFileSpec() = *sb_spec; } -void -SBModuleSpec::SetPlatformFileSpec (const lldb::SBFileSpec &sb_spec) -{ - m_opaque_ap->GetPlatformFileSpec() = *sb_spec; +lldb::SBFileSpec SBModuleSpec::GetSymbolFileSpec() { + return SBFileSpec(m_opaque_ap->GetSymbolFileSpec()); } -lldb::SBFileSpec -SBModuleSpec::GetSymbolFileSpec () -{ - return SBFileSpec(m_opaque_ap->GetSymbolFileSpec()); +void SBModuleSpec::SetSymbolFileSpec(const lldb::SBFileSpec &sb_spec) { + m_opaque_ap->GetSymbolFileSpec() = *sb_spec; } -void -SBModuleSpec::SetSymbolFileSpec (const lldb::SBFileSpec &sb_spec) -{ - m_opaque_ap->GetSymbolFileSpec() = *sb_spec; +const char *SBModuleSpec::GetObjectName() { + return m_opaque_ap->GetObjectName().GetCString(); } -const char * -SBModuleSpec::GetObjectName () -{ - return m_opaque_ap->GetObjectName().GetCString(); +void SBModuleSpec::SetObjectName(const char *name) { + m_opaque_ap->GetObjectName().SetCString(name); } -void -SBModuleSpec::SetObjectName (const char *name) -{ - m_opaque_ap->GetObjectName().SetCString(name); +const char *SBModuleSpec::GetTriple() { + std::string triple(m_opaque_ap->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since + // the const strings put the string into the string pool once and + // the strings never comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); } -const char * -SBModuleSpec::GetTriple () -{ - std::string triple (m_opaque_ap->GetArchitecture().GetTriple().str()); - // Unique the string so we don't run into ownership issues since - // the const strings put the string into the string pool once and - // the strings never comes out - ConstString const_triple (triple.c_str()); - return const_triple.GetCString(); +void SBModuleSpec::SetTriple(const char *triple) { + m_opaque_ap->GetArchitecture().SetTriple(triple); } -void -SBModuleSpec::SetTriple (const char *triple) -{ - m_opaque_ap->GetArchitecture().SetTriple(triple); +const uint8_t *SBModuleSpec::GetUUIDBytes() { + return (const uint8_t *)m_opaque_ap->GetUUID().GetBytes(); } -const uint8_t * -SBModuleSpec::GetUUIDBytes () -{ - return (const uint8_t *)m_opaque_ap->GetUUID().GetBytes(); +size_t SBModuleSpec::GetUUIDLength() { + return m_opaque_ap->GetUUID().GetByteSize(); } -size_t -SBModuleSpec::GetUUIDLength () -{ - return m_opaque_ap->GetUUID().GetByteSize(); +bool SBModuleSpec::SetUUIDBytes(const uint8_t *uuid, size_t uuid_len) { + return m_opaque_ap->GetUUID().SetBytes(uuid, uuid_len); } -bool -SBModuleSpec::SetUUIDBytes (const uint8_t *uuid, size_t uuid_len) -{ - return m_opaque_ap->GetUUID().SetBytes(uuid, uuid_len); +bool SBModuleSpec::GetDescription(lldb::SBStream &description) { + m_opaque_ap->Dump(description.ref()); + return true; } -bool -SBModuleSpec::GetDescription (lldb::SBStream &description) -{ - m_opaque_ap->Dump (description.ref()); - return true; -} +SBModuleSpecList::SBModuleSpecList() : m_opaque_ap(new ModuleSpecList()) {} -SBModuleSpecList::SBModuleSpecList() : - m_opaque_ap(new ModuleSpecList()) -{ - -} +SBModuleSpecList::SBModuleSpecList(const SBModuleSpecList &rhs) + : m_opaque_ap(new ModuleSpecList(*rhs.m_opaque_ap)) {} -SBModuleSpecList::SBModuleSpecList (const SBModuleSpecList &rhs) : - m_opaque_ap(new ModuleSpecList(*rhs.m_opaque_ap)) -{ - +SBModuleSpecList &SBModuleSpecList::operator=(const SBModuleSpecList &rhs) { + if (this != &rhs) + *m_opaque_ap = *rhs.m_opaque_ap; + return *this; } -SBModuleSpecList & -SBModuleSpecList::operator = (const SBModuleSpecList &rhs) -{ - if (this != &rhs) - *m_opaque_ap = *rhs.m_opaque_ap; - return *this; -} +SBModuleSpecList::~SBModuleSpecList() {} -SBModuleSpecList::~SBModuleSpecList() -{ - +SBModuleSpecList SBModuleSpecList::GetModuleSpecifications(const char *path) { + SBModuleSpecList specs; + FileSpec file_spec(path, true); + Host::ResolveExecutableInBundle(file_spec); + ObjectFile::GetModuleSpecifications(file_spec, 0, 0, *specs.m_opaque_ap); + return specs; } -SBModuleSpecList -SBModuleSpecList::GetModuleSpecifications (const char *path) -{ - SBModuleSpecList specs; - FileSpec file_spec(path, true); - Host::ResolveExecutableInBundle(file_spec); - ObjectFile::GetModuleSpecifications(file_spec, 0, 0, *specs.m_opaque_ap); - return specs; +void SBModuleSpecList::Append(const SBModuleSpec &spec) { + m_opaque_ap->Append(*spec.m_opaque_ap); } -void -SBModuleSpecList::Append (const SBModuleSpec &spec) -{ - m_opaque_ap->Append (*spec.m_opaque_ap); +void SBModuleSpecList::Append(const SBModuleSpecList &spec_list) { + m_opaque_ap->Append(*spec_list.m_opaque_ap); } -void -SBModuleSpecList::Append (const SBModuleSpecList &spec_list) -{ - m_opaque_ap->Append (*spec_list.m_opaque_ap); -} +size_t SBModuleSpecList::GetSize() { return m_opaque_ap->GetSize(); } -size_t -SBModuleSpecList::GetSize() -{ - return m_opaque_ap->GetSize(); +SBModuleSpec SBModuleSpecList::GetSpecAtIndex(size_t i) { + SBModuleSpec sb_module_spec; + m_opaque_ap->GetModuleSpecAtIndex(i, *sb_module_spec.m_opaque_ap); + return sb_module_spec; } SBModuleSpec -SBModuleSpecList::GetSpecAtIndex (size_t i) -{ - SBModuleSpec sb_module_spec; - m_opaque_ap->GetModuleSpecAtIndex(i, *sb_module_spec.m_opaque_ap); - return sb_module_spec; +SBModuleSpecList::FindFirstMatchingSpec(const SBModuleSpec &match_spec) { + SBModuleSpec sb_module_spec; + m_opaque_ap->FindMatchingModuleSpec(*match_spec.m_opaque_ap, + *sb_module_spec.m_opaque_ap); + return sb_module_spec; } -SBModuleSpec -SBModuleSpecList::FindFirstMatchingSpec (const SBModuleSpec &match_spec) -{ - SBModuleSpec sb_module_spec; - m_opaque_ap->FindMatchingModuleSpec(*match_spec.m_opaque_ap, *sb_module_spec.m_opaque_ap); - return sb_module_spec; +SBModuleSpecList +SBModuleSpecList::FindMatchingSpecs(const SBModuleSpec &match_spec) { + SBModuleSpecList specs; + m_opaque_ap->FindMatchingModuleSpecs(*match_spec.m_opaque_ap, + *specs.m_opaque_ap); + return specs; } -SBModuleSpecList -SBModuleSpecList::FindMatchingSpecs (const SBModuleSpec &match_spec) -{ - SBModuleSpecList specs; - m_opaque_ap->FindMatchingModuleSpecs(*match_spec.m_opaque_ap, *specs.m_opaque_ap); - return specs; - -} - -bool -SBModuleSpecList::GetDescription (lldb::SBStream &description) -{ - m_opaque_ap->Dump (description.ref()); - return true; +bool SBModuleSpecList::GetDescription(lldb::SBStream &description) { + m_opaque_ap->Dump(description.ref()); + return true; } diff --git a/lldb/source/API/SBPlatform.cpp b/lldb/source/API/SBPlatform.cpp index b8dc01ba781..10b7219eb35 100644 --- a/lldb/source/API/SBPlatform.cpp +++ b/lldb/source/API/SBPlatform.cpp @@ -16,8 +16,8 @@ #include "lldb/Core/Error.h" #include "lldb/Host/File.h" #include "lldb/Interpreter/Args.h" -#include "lldb/Target/Target.h" #include "lldb/Target/Platform.h" +#include "lldb/Target/Target.h" #include @@ -28,622 +28,454 @@ using namespace lldb_private; // PlatformConnectOptions //---------------------------------------------------------------------- struct PlatformConnectOptions { - PlatformConnectOptions(const char *url = NULL) : - m_url(), - m_rsync_options(), - m_rsync_remote_path_prefix(), - m_rsync_enabled(false), - m_rsync_omit_hostname_from_remote_path(false), - m_local_cache_directory () - { - if (url && url[0]) - m_url = url; - } - - ~PlatformConnectOptions() - { - } + PlatformConnectOptions(const char *url = NULL) + : m_url(), m_rsync_options(), m_rsync_remote_path_prefix(), + m_rsync_enabled(false), m_rsync_omit_hostname_from_remote_path(false), + m_local_cache_directory() { + if (url && url[0]) + m_url = url; + } - std::string m_url; - std::string m_rsync_options; - std::string m_rsync_remote_path_prefix; - bool m_rsync_enabled; - bool m_rsync_omit_hostname_from_remote_path; - ConstString m_local_cache_directory; + ~PlatformConnectOptions() {} + + std::string m_url; + std::string m_rsync_options; + std::string m_rsync_remote_path_prefix; + bool m_rsync_enabled; + bool m_rsync_omit_hostname_from_remote_path; + ConstString m_local_cache_directory; }; //---------------------------------------------------------------------- // PlatformShellCommand //---------------------------------------------------------------------- struct PlatformShellCommand { - PlatformShellCommand(const char *shell_command = NULL) : - m_command(), - m_working_dir(), - m_status(0), - m_signo(0), - m_timeout_sec(UINT32_MAX) - { - if (shell_command && shell_command[0]) - m_command = shell_command; - } - - ~PlatformShellCommand() - { - } - - std::string m_command; - std::string m_working_dir; - std::string m_output; - int m_status; - int m_signo; - uint32_t m_timeout_sec; + PlatformShellCommand(const char *shell_command = NULL) + : m_command(), m_working_dir(), m_status(0), m_signo(0), + m_timeout_sec(UINT32_MAX) { + if (shell_command && shell_command[0]) + m_command = shell_command; + } + + ~PlatformShellCommand() {} + + std::string m_command; + std::string m_working_dir; + std::string m_output; + int m_status; + int m_signo; + uint32_t m_timeout_sec; }; //---------------------------------------------------------------------- // SBPlatformConnectOptions //---------------------------------------------------------------------- -SBPlatformConnectOptions::SBPlatformConnectOptions (const char *url) : - m_opaque_ptr(new PlatformConnectOptions(url)) -{ - +SBPlatformConnectOptions::SBPlatformConnectOptions(const char *url) + : m_opaque_ptr(new PlatformConnectOptions(url)) {} + +SBPlatformConnectOptions::SBPlatformConnectOptions( + const SBPlatformConnectOptions &rhs) + : m_opaque_ptr(new PlatformConnectOptions()) { + *m_opaque_ptr = *rhs.m_opaque_ptr; } -SBPlatformConnectOptions::SBPlatformConnectOptions(const SBPlatformConnectOptions &rhs) : - m_opaque_ptr(new PlatformConnectOptions()) -{ - *m_opaque_ptr = *rhs.m_opaque_ptr; +SBPlatformConnectOptions::~SBPlatformConnectOptions() { delete m_opaque_ptr; } + +void SBPlatformConnectOptions::operator=(const SBPlatformConnectOptions &rhs) { + *m_opaque_ptr = *rhs.m_opaque_ptr; } - -SBPlatformConnectOptions::~SBPlatformConnectOptions () -{ - delete m_opaque_ptr; + +const char *SBPlatformConnectOptions::GetURL() { + if (m_opaque_ptr->m_url.empty()) + return NULL; + return m_opaque_ptr->m_url.c_str(); } -void -SBPlatformConnectOptions::operator=(const SBPlatformConnectOptions &rhs) -{ - *m_opaque_ptr = *rhs.m_opaque_ptr; +void SBPlatformConnectOptions::SetURL(const char *url) { + if (url && url[0]) + m_opaque_ptr->m_url = url; + else + m_opaque_ptr->m_url.clear(); } -const char * -SBPlatformConnectOptions::GetURL() -{ - if (m_opaque_ptr->m_url.empty()) - return NULL; - return m_opaque_ptr->m_url.c_str(); +bool SBPlatformConnectOptions::GetRsyncEnabled() { + return m_opaque_ptr->m_rsync_enabled; } - -void -SBPlatformConnectOptions::SetURL(const char *url) -{ - if (url && url[0]) - m_opaque_ptr->m_url = url; - else - m_opaque_ptr->m_url.clear(); -} - -bool -SBPlatformConnectOptions::GetRsyncEnabled() -{ - return m_opaque_ptr->m_rsync_enabled; -} - -void -SBPlatformConnectOptions::EnableRsync (const char *options, - const char *remote_path_prefix, - bool omit_hostname_from_remote_path) -{ - m_opaque_ptr->m_rsync_enabled = true; - m_opaque_ptr->m_rsync_omit_hostname_from_remote_path = omit_hostname_from_remote_path; - if (remote_path_prefix && remote_path_prefix[0]) - m_opaque_ptr->m_rsync_remote_path_prefix = remote_path_prefix; - else - m_opaque_ptr->m_rsync_remote_path_prefix.clear(); - if (options && options[0]) - m_opaque_ptr->m_rsync_options = options; - else - m_opaque_ptr->m_rsync_options.clear(); +void SBPlatformConnectOptions::EnableRsync( + const char *options, const char *remote_path_prefix, + bool omit_hostname_from_remote_path) { + m_opaque_ptr->m_rsync_enabled = true; + m_opaque_ptr->m_rsync_omit_hostname_from_remote_path = + omit_hostname_from_remote_path; + if (remote_path_prefix && remote_path_prefix[0]) + m_opaque_ptr->m_rsync_remote_path_prefix = remote_path_prefix; + else + m_opaque_ptr->m_rsync_remote_path_prefix.clear(); + if (options && options[0]) + m_opaque_ptr->m_rsync_options = options; + else + m_opaque_ptr->m_rsync_options.clear(); } -void -SBPlatformConnectOptions::DisableRsync () -{ - m_opaque_ptr->m_rsync_enabled = false; +void SBPlatformConnectOptions::DisableRsync() { + m_opaque_ptr->m_rsync_enabled = false; } - -const char * -SBPlatformConnectOptions::GetLocalCacheDirectory() -{ - return m_opaque_ptr->m_local_cache_directory.GetCString(); + +const char *SBPlatformConnectOptions::GetLocalCacheDirectory() { + return m_opaque_ptr->m_local_cache_directory.GetCString(); } - -void -SBPlatformConnectOptions::SetLocalCacheDirectory(const char *path) -{ - if (path && path[0]) - m_opaque_ptr->m_local_cache_directory.SetCString(path); - else - m_opaque_ptr->m_local_cache_directory = ConstString(); + +void SBPlatformConnectOptions::SetLocalCacheDirectory(const char *path) { + if (path && path[0]) + m_opaque_ptr->m_local_cache_directory.SetCString(path); + else + m_opaque_ptr->m_local_cache_directory = ConstString(); } //---------------------------------------------------------------------- // SBPlatformShellCommand //---------------------------------------------------------------------- -SBPlatformShellCommand::SBPlatformShellCommand (const char *shell_command) : - m_opaque_ptr(new PlatformShellCommand(shell_command)) -{ -} +SBPlatformShellCommand::SBPlatformShellCommand(const char *shell_command) + : m_opaque_ptr(new PlatformShellCommand(shell_command)) {} -SBPlatformShellCommand::SBPlatformShellCommand (const SBPlatformShellCommand &rhs) : - m_opaque_ptr(new PlatformShellCommand()) -{ - *m_opaque_ptr = *rhs.m_opaque_ptr; +SBPlatformShellCommand::SBPlatformShellCommand( + const SBPlatformShellCommand &rhs) + : m_opaque_ptr(new PlatformShellCommand()) { + *m_opaque_ptr = *rhs.m_opaque_ptr; } -SBPlatformShellCommand::~SBPlatformShellCommand() -{ - delete m_opaque_ptr; -} +SBPlatformShellCommand::~SBPlatformShellCommand() { delete m_opaque_ptr; } -void -SBPlatformShellCommand::Clear() -{ - m_opaque_ptr->m_output = std::string(); - m_opaque_ptr->m_status = 0; - m_opaque_ptr->m_signo = 0; +void SBPlatformShellCommand::Clear() { + m_opaque_ptr->m_output = std::string(); + m_opaque_ptr->m_status = 0; + m_opaque_ptr->m_signo = 0; } -const char * -SBPlatformShellCommand::GetCommand() -{ - if (m_opaque_ptr->m_command.empty()) - return NULL; - return m_opaque_ptr->m_command.c_str(); +const char *SBPlatformShellCommand::GetCommand() { + if (m_opaque_ptr->m_command.empty()) + return NULL; + return m_opaque_ptr->m_command.c_str(); } -void -SBPlatformShellCommand::SetCommand(const char *shell_command) -{ - if (shell_command && shell_command[0]) - m_opaque_ptr->m_command = shell_command; - else - m_opaque_ptr->m_command.clear(); +void SBPlatformShellCommand::SetCommand(const char *shell_command) { + if (shell_command && shell_command[0]) + m_opaque_ptr->m_command = shell_command; + else + m_opaque_ptr->m_command.clear(); } -const char * -SBPlatformShellCommand::GetWorkingDirectory () -{ - if (m_opaque_ptr->m_working_dir.empty()) - return NULL; - return m_opaque_ptr->m_working_dir.c_str(); +const char *SBPlatformShellCommand::GetWorkingDirectory() { + if (m_opaque_ptr->m_working_dir.empty()) + return NULL; + return m_opaque_ptr->m_working_dir.c_str(); } -void -SBPlatformShellCommand::SetWorkingDirectory (const char *path) -{ - if (path && path[0]) - m_opaque_ptr->m_working_dir = path; - else - m_opaque_ptr->m_working_dir.clear(); +void SBPlatformShellCommand::SetWorkingDirectory(const char *path) { + if (path && path[0]) + m_opaque_ptr->m_working_dir = path; + else + m_opaque_ptr->m_working_dir.clear(); } -uint32_t -SBPlatformShellCommand::GetTimeoutSeconds () -{ - return m_opaque_ptr->m_timeout_sec; +uint32_t SBPlatformShellCommand::GetTimeoutSeconds() { + return m_opaque_ptr->m_timeout_sec; } -void -SBPlatformShellCommand::SetTimeoutSeconds (uint32_t sec) -{ - m_opaque_ptr->m_timeout_sec = sec; +void SBPlatformShellCommand::SetTimeoutSeconds(uint32_t sec) { + m_opaque_ptr->m_timeout_sec = sec; } -int -SBPlatformShellCommand::GetSignal () -{ - return m_opaque_ptr->m_signo; -} +int SBPlatformShellCommand::GetSignal() { return m_opaque_ptr->m_signo; } -int -SBPlatformShellCommand::GetStatus () -{ - return m_opaque_ptr->m_status; -} +int SBPlatformShellCommand::GetStatus() { return m_opaque_ptr->m_status; } -const char * -SBPlatformShellCommand::GetOutput () -{ - if (m_opaque_ptr->m_output.empty()) - return NULL; - return m_opaque_ptr->m_output.c_str(); +const char *SBPlatformShellCommand::GetOutput() { + if (m_opaque_ptr->m_output.empty()) + return NULL; + return m_opaque_ptr->m_output.c_str(); } //---------------------------------------------------------------------- // SBPlatform //---------------------------------------------------------------------- -SBPlatform::SBPlatform () : - m_opaque_sp () -{ - -} +SBPlatform::SBPlatform() : m_opaque_sp() {} -SBPlatform::SBPlatform (const char *platform_name) : - m_opaque_sp () -{ - Error error; - if (platform_name && platform_name[0]) - m_opaque_sp = Platform::Create (ConstString(platform_name), error); +SBPlatform::SBPlatform(const char *platform_name) : m_opaque_sp() { + Error error; + if (platform_name && platform_name[0]) + m_opaque_sp = Platform::Create(ConstString(platform_name), error); } -SBPlatform::~SBPlatform() -{ -} +SBPlatform::~SBPlatform() {} -bool -SBPlatform::IsValid () const -{ - return m_opaque_sp.get() != NULL; +bool SBPlatform::IsValid() const { return m_opaque_sp.get() != NULL; } + +void SBPlatform::Clear() { m_opaque_sp.reset(); } + +const char *SBPlatform::GetName() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return platform_sp->GetName().GetCString(); + return NULL; } -void -SBPlatform::Clear () -{ - m_opaque_sp.reset(); +lldb::PlatformSP SBPlatform::GetSP() const { return m_opaque_sp; } + +void SBPlatform::SetSP(const lldb::PlatformSP &platform_sp) { + m_opaque_sp = platform_sp; } -const char * -SBPlatform::GetName () -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - return platform_sp->GetName().GetCString(); - return NULL; +const char *SBPlatform::GetWorkingDirectory() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return platform_sp->GetWorkingDirectory().GetCString(); + return NULL; } -lldb::PlatformSP -SBPlatform::GetSP () const -{ - return m_opaque_sp; +bool SBPlatform::SetWorkingDirectory(const char *path) { + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + if (path) + platform_sp->SetWorkingDirectory(FileSpec{path, false}); + else + platform_sp->SetWorkingDirectory(FileSpec{}); + return true; + } + return false; +} + +SBError SBPlatform::ConnectRemote(SBPlatformConnectOptions &connect_options) { + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp && connect_options.GetURL()) { + Args args; + args.AppendArgument(connect_options.GetURL()); + sb_error.ref() = platform_sp->ConnectRemote(args); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; } -void -SBPlatform::SetSP (const lldb::PlatformSP& platform_sp) -{ - m_opaque_sp = platform_sp; +void SBPlatform::DisconnectRemote() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) + platform_sp->DisconnectRemote(); } -const char * -SBPlatform::GetWorkingDirectory() -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - return platform_sp->GetWorkingDirectory().GetCString(); - return NULL; +bool SBPlatform::IsConnected() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) + platform_sp->IsConnected(); + return false; } -bool -SBPlatform::SetWorkingDirectory(const char *path) -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - if (path) - platform_sp->SetWorkingDirectory(FileSpec{path, false}); - else - platform_sp->SetWorkingDirectory(FileSpec{}); - return true; - } - return false; -} - -SBError -SBPlatform::ConnectRemote (SBPlatformConnectOptions &connect_options) -{ - SBError sb_error; - PlatformSP platform_sp(GetSP()); - if (platform_sp && connect_options.GetURL()) - { - Args args; - args.AppendArgument(connect_options.GetURL()); - sb_error.ref() = platform_sp->ConnectRemote(args); +const char *SBPlatform::GetTriple() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + ArchSpec arch(platform_sp->GetSystemArchitecture()); + if (arch.IsValid()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(arch.GetTriple().getTriple().c_str()).GetCString(); } - else - { - sb_error.SetErrorString("invalid platform"); + } + return NULL; +} + +const char *SBPlatform::GetOSBuild() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + std::string s; + if (platform_sp->GetOSBuildString(s)) { + if (!s.empty()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(s.c_str()).GetCString(); + } } - return sb_error; -} - -void -SBPlatform::DisconnectRemote () -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - platform_sp->DisconnectRemote(); -} - -bool -SBPlatform::IsConnected() -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - platform_sp->IsConnected(); - return false; -} - -const char * -SBPlatform::GetTriple() -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - ArchSpec arch(platform_sp->GetSystemArchitecture()); - if (arch.IsValid()) - { - // Const-ify the string so we don't need to worry about the lifetime of the string - return ConstString(arch.GetTriple().getTriple().c_str()).GetCString(); - } + } + return NULL; +} + +const char *SBPlatform::GetOSDescription() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + std::string s; + if (platform_sp->GetOSKernelDescription(s)) { + if (!s.empty()) { + // Const-ify the string so we don't need to worry about the lifetime of + // the string + return ConstString(s.c_str()).GetCString(); + } } - return NULL; + } + return NULL; } -const char * -SBPlatform::GetOSBuild() -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - std::string s; - if (platform_sp->GetOSBuildString(s)) - { - if (!s.empty()) - { - // Const-ify the string so we don't need to worry about the lifetime of the string - return ConstString(s.c_str()).GetCString(); - } - } - } - return NULL; +const char *SBPlatform::GetHostname() { + PlatformSP platform_sp(GetSP()); + if (platform_sp) + return platform_sp->GetHostname(); + return NULL; } -const char * -SBPlatform::GetOSDescription() -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - std::string s; - if (platform_sp->GetOSKernelDescription(s)) - { - if (!s.empty()) - { - // Const-ify the string so we don't need to worry about the lifetime of the string - return ConstString(s.c_str()).GetCString(); - } - } - } - return NULL; +uint32_t SBPlatform::GetOSMajorVersion() { + uint32_t major, minor, update; + PlatformSP platform_sp(GetSP()); + if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) + return major; + return UINT32_MAX; } -const char * -SBPlatform::GetHostname () -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - return platform_sp->GetHostname(); - return NULL; +uint32_t SBPlatform::GetOSMinorVersion() { + uint32_t major, minor, update; + PlatformSP platform_sp(GetSP()); + if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) + return minor; + return UINT32_MAX; } -uint32_t -SBPlatform::GetOSMajorVersion () -{ - uint32_t major, minor, update; - PlatformSP platform_sp(GetSP()); - if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) - return major; - return UINT32_MAX; - -} - -uint32_t -SBPlatform::GetOSMinorVersion () -{ - uint32_t major, minor, update; - PlatformSP platform_sp(GetSP()); - if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) - return minor; - return UINT32_MAX; -} - -uint32_t -SBPlatform::GetOSUpdateVersion () -{ - uint32_t major, minor, update; - PlatformSP platform_sp(GetSP()); - if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) - return update; - return UINT32_MAX; -} - -SBError -SBPlatform::Get (SBFileSpec &src, - SBFileSpec &dst) -{ - SBError sb_error; - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - sb_error.ref() = platform_sp->GetFile(src.ref(), dst.ref()); - } - else - { - sb_error.SetErrorString("invalid platform"); - } - return sb_error; -} - -SBError -SBPlatform::Put (SBFileSpec &src, - SBFileSpec &dst) -{ - return ExecuteConnected( - [&](const lldb::PlatformSP& platform_sp) - { - if (src.Exists()) - { - uint32_t permissions = src.ref().GetPermissions(); - if (permissions == 0) - { - if (src.ref().GetFileType() == FileSpec::eFileTypeDirectory) - permissions = eFilePermissionsDirectoryDefault; - else - permissions = eFilePermissionsFileDefault; - } - - return platform_sp->PutFile(src.ref(), dst.ref(), permissions); - } - - Error error; - error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", src.ref().GetPath().c_str()); - return error; - }); -} - -SBError -SBPlatform::Install (SBFileSpec &src, - SBFileSpec &dst) -{ - return ExecuteConnected( - [&](const lldb::PlatformSP& platform_sp) - { - if (src.Exists()) - return platform_sp->Install(src.ref(), dst.ref()); - - Error error; - error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", src.ref().GetPath().c_str()); - return error; - }); -} - - -SBError -SBPlatform::Run (SBPlatformShellCommand &shell_command) -{ - return ExecuteConnected( - [&](const lldb::PlatformSP& platform_sp) - { - const char *command = shell_command.GetCommand(); - if (!command) - return Error("invalid shell command (empty)"); - - const char *working_dir = shell_command.GetWorkingDirectory(); - if (working_dir == NULL) - { - working_dir = platform_sp->GetWorkingDirectory().GetCString(); - if (working_dir) - shell_command.SetWorkingDirectory(working_dir); - } - return platform_sp->RunShellCommand(command, - FileSpec{working_dir, false}, - &shell_command.m_opaque_ptr->m_status, - &shell_command.m_opaque_ptr->m_signo, - &shell_command.m_opaque_ptr->m_output, - shell_command.m_opaque_ptr->m_timeout_sec); - }); -} - -SBError -SBPlatform::Launch (SBLaunchInfo &launch_info) -{ - return ExecuteConnected( - [&](const lldb::PlatformSP& platform_sp) - { - return platform_sp->LaunchProcess(launch_info.ref()); - }); -} - -SBError -SBPlatform::Kill (const lldb::pid_t pid) -{ - return ExecuteConnected( - [&](const lldb::PlatformSP& platform_sp) - { - return platform_sp->KillProcess(pid); - }); -} - -SBError -SBPlatform::ExecuteConnected (const std::function& func) -{ - SBError sb_error; - const auto platform_sp(GetSP()); - if (platform_sp) - { - if (platform_sp->IsConnected()) - sb_error.ref() = func(platform_sp); - else - sb_error.SetErrorString("not connected"); - } - else - sb_error.SetErrorString("invalid platform"); +uint32_t SBPlatform::GetOSUpdateVersion() { + uint32_t major, minor, update; + PlatformSP platform_sp(GetSP()); + if (platform_sp && platform_sp->GetOSVersion(major, minor, update)) + return update; + return UINT32_MAX; +} +SBError SBPlatform::Get(SBFileSpec &src, SBFileSpec &dst) { + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = platform_sp->GetFile(src.ref(), dst.ref()); + } else { + sb_error.SetErrorString("invalid platform"); + } return sb_error; } -SBError -SBPlatform::MakeDirectory (const char *path, uint32_t file_permissions) -{ - SBError sb_error; - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - sb_error.ref() = platform_sp->MakeDirectory(FileSpec{path, false}, file_permissions); - } - else - { - sb_error.SetErrorString("invalid platform"); - } - return sb_error; -} - -uint32_t -SBPlatform::GetFilePermissions (const char *path) -{ - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - uint32_t file_permissions = 0; - platform_sp->GetFilePermissions(FileSpec{path, false}, file_permissions); - return file_permissions; +SBError SBPlatform::Put(SBFileSpec &src, SBFileSpec &dst) { + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + if (src.Exists()) { + uint32_t permissions = src.ref().GetPermissions(); + if (permissions == 0) { + if (src.ref().GetFileType() == FileSpec::eFileTypeDirectory) + permissions = eFilePermissionsDirectoryDefault; + else + permissions = eFilePermissionsFileDefault; + } + + return platform_sp->PutFile(src.ref(), dst.ref(), permissions); } - return 0; - -} - -SBError -SBPlatform::SetFilePermissions (const char *path, uint32_t file_permissions) -{ - SBError sb_error; - PlatformSP platform_sp(GetSP()); - if (platform_sp) - { - sb_error.ref() = platform_sp->SetFilePermissions(FileSpec{path, false}, file_permissions); + + Error error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + }); +} + +SBError SBPlatform::Install(SBFileSpec &src, SBFileSpec &dst) { + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + if (src.Exists()) + return platform_sp->Install(src.ref(), dst.ref()); + + Error error; + error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", + src.ref().GetPath().c_str()); + return error; + }); +} + +SBError SBPlatform::Run(SBPlatformShellCommand &shell_command) { + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + const char *command = shell_command.GetCommand(); + if (!command) + return Error("invalid shell command (empty)"); + + const char *working_dir = shell_command.GetWorkingDirectory(); + if (working_dir == NULL) { + working_dir = platform_sp->GetWorkingDirectory().GetCString(); + if (working_dir) + shell_command.SetWorkingDirectory(working_dir); } + return platform_sp->RunShellCommand( + command, FileSpec{working_dir, false}, + &shell_command.m_opaque_ptr->m_status, + &shell_command.m_opaque_ptr->m_signo, + &shell_command.m_opaque_ptr->m_output, + shell_command.m_opaque_ptr->m_timeout_sec); + }); +} + +SBError SBPlatform::Launch(SBLaunchInfo &launch_info) { + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + return platform_sp->LaunchProcess(launch_info.ref()); + }); +} + +SBError SBPlatform::Kill(const lldb::pid_t pid) { + return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { + return platform_sp->KillProcess(pid); + }); +} + +SBError SBPlatform::ExecuteConnected( + const std::function &func) { + SBError sb_error; + const auto platform_sp(GetSP()); + if (platform_sp) { + if (platform_sp->IsConnected()) + sb_error.ref() = func(platform_sp); else - { - sb_error.SetErrorString("invalid platform"); - } - return sb_error; - + sb_error.SetErrorString("not connected"); + } else + sb_error.SetErrorString("invalid platform"); + + return sb_error; +} + +SBError SBPlatform::MakeDirectory(const char *path, uint32_t file_permissions) { + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = + platform_sp->MakeDirectory(FileSpec{path, false}, file_permissions); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; +} + +uint32_t SBPlatform::GetFilePermissions(const char *path) { + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + uint32_t file_permissions = 0; + platform_sp->GetFilePermissions(FileSpec{path, false}, file_permissions); + return file_permissions; + } + return 0; +} + +SBError SBPlatform::SetFilePermissions(const char *path, + uint32_t file_permissions) { + SBError sb_error; + PlatformSP platform_sp(GetSP()); + if (platform_sp) { + sb_error.ref() = platform_sp->SetFilePermissions(FileSpec{path, false}, + file_permissions); + } else { + sb_error.SetErrorString("invalid platform"); + } + return sb_error; } -SBUnixSignals -SBPlatform::GetUnixSignals() const -{ - if (auto platform_sp = GetSP()) - return SBUnixSignals{platform_sp}; +SBUnixSignals SBPlatform::GetUnixSignals() const { + if (auto platform_sp = GetSP()) + return SBUnixSignals{platform_sp}; - return {}; + return {}; } diff --git a/lldb/source/API/SBProcess.cpp b/lldb/source/API/SBProcess.cpp index 9b8ac8461ac..59dd5693327 100644 --- a/lldb/source/API/SBProcess.cpp +++ b/lldb/source/API/SBProcess.cpp @@ -15,7 +15,6 @@ #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" -#include "lldb/Interpreter/Args.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" @@ -23,6 +22,7 @@ #include "lldb/Core/State.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" +#include "lldb/Interpreter/Args.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" @@ -39,1539 +39,1300 @@ #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBMemoryRegionInfoList.h" +#include "lldb/API/SBStream.h" +#include "lldb/API/SBStringList.h" #include "lldb/API/SBStructuredData.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBThreadCollection.h" -#include "lldb/API/SBStream.h" -#include "lldb/API/SBStringList.h" #include "lldb/API/SBUnixSignals.h" using namespace lldb; using namespace lldb_private; - -SBProcess::SBProcess () : - m_opaque_wp() -{ -} - +SBProcess::SBProcess() : m_opaque_wp() {} //---------------------------------------------------------------------- // SBProcess constructor //---------------------------------------------------------------------- -SBProcess::SBProcess (const SBProcess& rhs) : - m_opaque_wp (rhs.m_opaque_wp) -{ -} - +SBProcess::SBProcess(const SBProcess &rhs) : m_opaque_wp(rhs.m_opaque_wp) {} -SBProcess::SBProcess (const lldb::ProcessSP &process_sp) : - m_opaque_wp (process_sp) -{ -} +SBProcess::SBProcess(const lldb::ProcessSP &process_sp) + : m_opaque_wp(process_sp) {} -const SBProcess& -SBProcess::operator = (const SBProcess& rhs) -{ - if (this != &rhs) - m_opaque_wp = rhs.m_opaque_wp; - return *this; +const SBProcess &SBProcess::operator=(const SBProcess &rhs) { + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -SBProcess::~SBProcess() -{ -} - -const char * -SBProcess::GetBroadcasterClassName () -{ - return Process::GetStaticBroadcasterClass().AsCString(); -} - -const char * -SBProcess::GetPluginName () -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - return process_sp->GetPluginName().GetCString(); - } - return ""; -} - -const char * -SBProcess::GetShortPluginName () -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - return process_sp->GetPluginName().GetCString(); - } - return ""; -} - - -lldb::ProcessSP -SBProcess::GetSP() const -{ - return m_opaque_wp.lock(); -} - -void -SBProcess::SetSP (const ProcessSP &process_sp) -{ - m_opaque_wp = process_sp; -} - -void -SBProcess::Clear () -{ - m_opaque_wp.reset(); -} - - -bool -SBProcess::IsValid() const -{ - ProcessSP process_sp(m_opaque_wp.lock()); - return ((bool) process_sp && process_sp->IsValid()); -} - -bool -SBProcess::RemoteLaunch (char const **argv, - char const **envp, - const char *stdin_path, - const char *stdout_path, - const char *stderr_path, - const char *working_directory, - uint32_t launch_flags, - bool stop_at_entry, - lldb::SBError& error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::RemoteLaunch (argv=%p, envp=%p, stdin=%s, stdout=%s, stderr=%s, working-dir=%s, launch_flags=0x%x, stop_at_entry=%i, &error (%p))...", - static_cast(m_opaque_wp.lock().get()), - static_cast(argv), static_cast(envp), - stdin_path ? stdin_path : "NULL", - stdout_path ? stdout_path : "NULL", - stderr_path ? stderr_path : "NULL", - working_directory ? working_directory : "NULL", - launch_flags, stop_at_entry, - static_cast(error.get())); - - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - if (process_sp->GetState() == eStateConnected) - { - if (stop_at_entry) - launch_flags |= eLaunchFlagStopAtEntry; - ProcessLaunchInfo launch_info(FileSpec{stdin_path, false}, - FileSpec{stdout_path, false}, - FileSpec{stderr_path, false}, - FileSpec{working_directory, false}, - launch_flags); - Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); - if (exe_module) - launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); - if (argv) - launch_info.GetArguments().AppendArguments (argv); - if (envp) - launch_info.GetEnvironmentEntries ().SetArguments (envp); - error.SetError (process_sp->Launch (launch_info)); - } - else - { - error.SetErrorString ("must be in eStateConnected to call RemoteLaunch"); - } - } - else - { - error.SetErrorString ("unable to attach pid"); - } - - if (log) { - SBStream sstr; - error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::RemoteLaunch (...) => SBError (%p): %s", - static_cast(process_sp.get()), - static_cast(error.get()), sstr.GetData()); - } - - return error.Success(); -} - -bool -SBProcess::RemoteAttachToProcessWithID (lldb::pid_t pid, lldb::SBError& error) -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - if (process_sp->GetState() == eStateConnected) - { - ProcessAttachInfo attach_info; - attach_info.SetProcessID (pid); - error.SetError (process_sp->Attach (attach_info)); - } - else - { - error.SetErrorString ("must be in eStateConnected to call RemoteAttachToProcessWithID"); - } - } - else - { - error.SetErrorString ("unable to attach pid"); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) { - SBStream sstr; - error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::RemoteAttachToProcessWithID (%" PRIu64 ") => SBError (%p): %s", - static_cast(process_sp.get()), pid, - static_cast(error.get()), sstr.GetData()); - } - - return error.Success(); -} - - -uint32_t -SBProcess::GetNumThreads () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t num_threads = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - - const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - num_threads = process_sp->GetThreadList().GetSize(can_update); - } - - if (log) - log->Printf ("SBProcess(%p)::GetNumThreads () => %d", - static_cast(process_sp.get()), num_threads); - - return num_threads; -} - -SBThread -SBProcess::GetSelectedThread () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBThread sb_thread; - ThreadSP thread_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - thread_sp = process_sp->GetThreadList().GetSelectedThread(); - sb_thread.SetThread (thread_sp); - } - - if (log) - log->Printf ("SBProcess(%p)::GetSelectedThread () => SBThread(%p)", - static_cast(process_sp.get()), - static_cast(thread_sp.get())); - - return sb_thread; -} - -SBThread -SBProcess::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBThread sb_thread; - ThreadSP thread_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - thread_sp = process_sp->CreateOSPluginThread(tid, context); - sb_thread.SetThread (thread_sp); - } - - if (log) - log->Printf ("SBProcess(%p)::CreateOSPluginThread (tid=0x%" PRIx64 ", context=0x%" PRIx64 ") => SBThread(%p)", - static_cast(process_sp.get()), tid, context, - static_cast(thread_sp.get())); - - return sb_thread; -} - -SBTarget -SBProcess::GetTarget() const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBTarget sb_target; - TargetSP target_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - target_sp = process_sp->GetTarget().shared_from_this(); - sb_target.SetSP (target_sp); - } - - if (log) - log->Printf ("SBProcess(%p)::GetTarget () => SBTarget(%p)", - static_cast(process_sp.get()), - static_cast(target_sp.get())); - - return sb_target; -} - - -size_t -SBProcess::PutSTDIN (const char *src, size_t src_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - size_t ret_val = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Error error; - ret_val = process_sp->PutSTDIN (src, src_len, error); - } - - if (log) - log->Printf("SBProcess(%p)::PutSTDIN (src=\"%s\", src_len=%" PRIu64 ") => %" PRIu64, - static_cast(process_sp.get()), src, - static_cast(src_len), - static_cast(ret_val)); - - return ret_val; -} - -size_t -SBProcess::GetSTDOUT (char *dst, size_t dst_len) const -{ - size_t bytes_read = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Error error; - bytes_read = process_sp->GetSTDOUT (dst, dst_len, error); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetSTDOUT (dst=\"%.*s\", dst_len=%" PRIu64 ") => %" PRIu64, - static_cast(process_sp.get()), - static_cast(bytes_read), dst, - static_cast(dst_len), - static_cast(bytes_read)); - - return bytes_read; -} - -size_t -SBProcess::GetSTDERR (char *dst, size_t dst_len) const -{ - size_t bytes_read = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Error error; - bytes_read = process_sp->GetSTDERR (dst, dst_len, error); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetSTDERR (dst=\"%.*s\", dst_len=%" PRIu64 ") => %" PRIu64, - static_cast(process_sp.get()), - static_cast(bytes_read), dst, - static_cast(dst_len), - static_cast(bytes_read)); - - return bytes_read; -} - -size_t -SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const -{ - size_t bytes_read = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Error error; - bytes_read = process_sp->GetAsyncProfileData (dst, dst_len, error); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetAsyncProfileData (dst=\"%.*s\", dst_len=%" PRIu64 ") => %" PRIu64, - static_cast(process_sp.get()), - static_cast(bytes_read), dst, - static_cast(dst_len), - static_cast(bytes_read)); - - return bytes_read; -} - -void -SBProcess::ReportEventState (const SBEvent &event, FILE *out) const -{ - if (out == NULL) - return; - - ProcessSP process_sp(GetSP()); - if (process_sp) - { - const StateType event_state = SBProcess::GetStateFromEvent (event); - char message[1024]; - int message_len = ::snprintf (message, - sizeof (message), - "Process %" PRIu64 " %s\n", - process_sp->GetID(), - SBDebugger::StateAsCString (event_state)); - - if (message_len > 0) - ::fwrite (message, 1, message_len, out); - } -} - -void -SBProcess::AppendEventStateReport (const SBEvent &event, SBCommandReturnObject &result) -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - const StateType event_state = SBProcess::GetStateFromEvent (event); - char message[1024]; - ::snprintf (message, - sizeof (message), - "Process %" PRIu64 " %s\n", - process_sp->GetID(), - SBDebugger::StateAsCString (event_state)); - - result.AppendMessage (message); - } -} - -bool -SBProcess::SetSelectedThread (const SBThread &thread) -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - return process_sp->GetThreadList().SetSelectedThreadByID (thread.GetThreadID()); - } - return false; -} - -bool -SBProcess::SetSelectedThreadByID (lldb::tid_t tid) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - bool ret_val = false; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - ret_val = process_sp->GetThreadList().SetSelectedThreadByID (tid); - } - - if (log) - log->Printf ("SBProcess(%p)::SetSelectedThreadByID (tid=0x%4.4" PRIx64 ") => %s", - static_cast(process_sp.get()), tid, - (ret_val ? "true" : "false")); - - return ret_val; -} - -bool -SBProcess::SetSelectedThreadByIndexID (uint32_t index_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - bool ret_val = false; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - ret_val = process_sp->GetThreadList().SetSelectedThreadByIndexID (index_id); - } - - if (log) - log->Printf ("SBProcess(%p)::SetSelectedThreadByID (tid=0x%x) => %s", - static_cast(process_sp.get()), index_id, - (ret_val ? "true" : "false")); - - return ret_val; -} - -SBThread -SBProcess::GetThreadAtIndex (size_t index) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBThread sb_thread; - ThreadSP thread_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - thread_sp = process_sp->GetThreadList().GetThreadAtIndex(index, can_update); - sb_thread.SetThread (thread_sp); - } - - if (log) - log->Printf ("SBProcess(%p)::GetThreadAtIndex (index=%d) => SBThread(%p)", - static_cast(process_sp.get()), - static_cast(index), - static_cast(thread_sp.get())); - - return sb_thread; -} - -uint32_t -SBProcess::GetNumQueues () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t num_queues = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - num_queues = process_sp->GetQueueList().GetSize(); - } - } - - if (log) - log->Printf ("SBProcess(%p)::GetNumQueues () => %d", - static_cast(process_sp.get()), num_queues); - - return num_queues; -} - -SBQueue -SBProcess::GetQueueAtIndex (size_t index) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBQueue sb_queue; - QueueSP queue_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - queue_sp = process_sp->GetQueueList().GetQueueAtIndex(index); - sb_queue.SetQueue (queue_sp); - } - } - - if (log) - log->Printf ("SBProcess(%p)::GetQueueAtIndex (index=%d) => SBQueue(%p)", - static_cast(process_sp.get()), - static_cast(index), - static_cast(queue_sp.get())); - - return sb_queue; -} - - -uint32_t -SBProcess::GetStopID(bool include_expression_stops) -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - if (include_expression_stops) - return process_sp->GetStopID(); - else - return process_sp->GetLastNaturalStopID(); - } - return 0; -} - -SBEvent -SBProcess::GetStopEventForStopID(uint32_t stop_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBEvent sb_event; - EventSP event_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - event_sp = process_sp->GetStopEventForStopID(stop_id); - sb_event.reset(event_sp); - } - - if (log) - log->Printf ("SBProcess(%p)::GetStopEventForStopID (stop_id=%" PRIu32 ") => SBEvent(%p)", - static_cast(process_sp.get()), - stop_id, - static_cast(event_sp.get())); - - return sb_event; -} - -StateType -SBProcess::GetState () -{ - - StateType ret_val = eStateInvalid; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - ret_val = process_sp->GetState(); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetState () => %s", - static_cast(process_sp.get()), - lldb_private::StateAsCString (ret_val)); - - return ret_val; -} - - -int -SBProcess::GetExitStatus () -{ - int exit_status = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - exit_status = process_sp->GetExitStatus (); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetExitStatus () => %i (0x%8.8x)", - static_cast(process_sp.get()), exit_status, - exit_status); - - return exit_status; -} - -const char * -SBProcess::GetExitDescription () -{ - const char *exit_desc = NULL; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - exit_desc = process_sp->GetExitDescription (); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetExitDescription () => %s", - static_cast(process_sp.get()), exit_desc); - return exit_desc; -} - -lldb::pid_t -SBProcess::GetProcessID () -{ - lldb::pid_t ret_val = LLDB_INVALID_PROCESS_ID; - ProcessSP process_sp(GetSP()); - if (process_sp) - ret_val = process_sp->GetID(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetProcessID () => %" PRIu64, - static_cast(process_sp.get()), ret_val); - - return ret_val; -} - -uint32_t -SBProcess::GetUniqueID() -{ - uint32_t ret_val = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - ret_val = process_sp->GetUniqueID(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetUniqueID () => %" PRIu32, - static_cast(process_sp.get()), ret_val); - return ret_val; -} - -ByteOrder -SBProcess::GetByteOrder () const -{ - ByteOrder byteOrder = eByteOrderInvalid; - ProcessSP process_sp(GetSP()); - if (process_sp) - byteOrder = process_sp->GetTarget().GetArchitecture().GetByteOrder(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetByteOrder () => %d", - static_cast(process_sp.get()), byteOrder); - - return byteOrder; -} - -uint32_t -SBProcess::GetAddressByteSize () const -{ - uint32_t size = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - size = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetAddressByteSize () => %d", - static_cast(process_sp.get()), size); - - return size; -} - -SBError -SBProcess::Continue () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBError sb_error; - ProcessSP process_sp(GetSP()); - - if (log) - log->Printf ("SBProcess(%p)::Continue ()...", - static_cast(process_sp.get())); - - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - - if (process_sp->GetTarget().GetDebugger().GetAsyncExecution ()) - sb_error.ref() = process_sp->Resume (); - else - sb_error.ref() = process_sp->ResumeSynchronous (NULL); - } - else - sb_error.SetErrorString ("SBProcess is invalid"); - - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::Continue () => SBError (%p): %s", - static_cast(process_sp.get()), - static_cast(sb_error.get()), sstr.GetData()); - } - - return sb_error; -} - - -SBError -SBProcess::Destroy () -{ - SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError(process_sp->Destroy(false)); - } - else - sb_error.SetErrorString ("SBProcess is invalid"); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::Destroy () => SBError (%p): %s", - static_cast(process_sp.get()), - static_cast(sb_error.get()), sstr.GetData()); - } - - return sb_error; -} - - -SBError -SBProcess::Stop () -{ - SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError (process_sp->Halt()); - } - else - sb_error.SetErrorString ("SBProcess is invalid"); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::Stop () => SBError (%p): %s", - static_cast(process_sp.get()), - static_cast(sb_error.get()), sstr.GetData()); - } - - return sb_error; -} - -SBError -SBProcess::Kill () -{ - SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError (process_sp->Destroy(true)); +SBProcess::~SBProcess() {} + +const char *SBProcess::GetBroadcasterClassName() { + return Process::GetStaticBroadcasterClass().AsCString(); +} + +const char *SBProcess::GetPluginName() { + ProcessSP process_sp(GetSP()); + if (process_sp) { + return process_sp->GetPluginName().GetCString(); + } + return ""; +} + +const char *SBProcess::GetShortPluginName() { + ProcessSP process_sp(GetSP()); + if (process_sp) { + return process_sp->GetPluginName().GetCString(); + } + return ""; +} + +lldb::ProcessSP SBProcess::GetSP() const { return m_opaque_wp.lock(); } + +void SBProcess::SetSP(const ProcessSP &process_sp) { m_opaque_wp = process_sp; } + +void SBProcess::Clear() { m_opaque_wp.reset(); } + +bool SBProcess::IsValid() const { + ProcessSP process_sp(m_opaque_wp.lock()); + return ((bool)process_sp && process_sp->IsValid()); +} + +bool SBProcess::RemoteLaunch(char const **argv, char const **envp, + const char *stdin_path, const char *stdout_path, + const char *stderr_path, + const char *working_directory, + uint32_t launch_flags, bool stop_at_entry, + lldb::SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::RemoteLaunch (argv=%p, envp=%p, stdin=%s, " + "stdout=%s, stderr=%s, working-dir=%s, launch_flags=0x%x, " + "stop_at_entry=%i, &error (%p))...", + static_cast(m_opaque_wp.lock().get()), + static_cast(argv), static_cast(envp), + stdin_path ? stdin_path : "NULL", + stdout_path ? stdout_path : "NULL", + stderr_path ? stderr_path : "NULL", + working_directory ? working_directory : "NULL", launch_flags, + stop_at_entry, static_cast(error.get())); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + if (process_sp->GetState() == eStateConnected) { + if (stop_at_entry) + launch_flags |= eLaunchFlagStopAtEntry; + ProcessLaunchInfo launch_info( + FileSpec{stdin_path, false}, FileSpec{stdout_path, false}, + FileSpec{stderr_path, false}, FileSpec{working_directory, false}, + launch_flags); + Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + if (argv) + launch_info.GetArguments().AppendArguments(argv); + if (envp) + launch_info.GetEnvironmentEntries().SetArguments(envp); + error.SetError(process_sp->Launch(launch_info)); + } else { + error.SetErrorString("must be in eStateConnected to call RemoteLaunch"); + } + } else { + error.SetErrorString("unable to attach pid"); + } + + if (log) { + SBStream sstr; + error.GetDescription(sstr); + log->Printf("SBProcess(%p)::RemoteLaunch (...) => SBError (%p): %s", + static_cast(process_sp.get()), + static_cast(error.get()), sstr.GetData()); + } + + return error.Success(); +} + +bool SBProcess::RemoteAttachToProcessWithID(lldb::pid_t pid, + lldb::SBError &error) { + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + if (process_sp->GetState() == eStateConnected) { + ProcessAttachInfo attach_info; + attach_info.SetProcessID(pid); + error.SetError(process_sp->Attach(attach_info)); + } else { + error.SetErrorString( + "must be in eStateConnected to call RemoteAttachToProcessWithID"); + } + } else { + error.SetErrorString("unable to attach pid"); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + error.GetDescription(sstr); + log->Printf("SBProcess(%p)::RemoteAttachToProcessWithID (%" PRIu64 + ") => SBError (%p): %s", + static_cast(process_sp.get()), pid, + static_cast(error.get()), sstr.GetData()); + } + + return error.Success(); +} + +uint32_t SBProcess::GetNumThreads() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + uint32_t num_threads = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + num_threads = process_sp->GetThreadList().GetSize(can_update); + } + + if (log) + log->Printf("SBProcess(%p)::GetNumThreads () => %d", + static_cast(process_sp.get()), num_threads); + + return num_threads; +} + +SBThread SBProcess::GetSelectedThread() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().GetSelectedThread(); + sb_thread.SetThread(thread_sp); + } + + if (log) + log->Printf("SBProcess(%p)::GetSelectedThread () => SBThread(%p)", + static_cast(process_sp.get()), + static_cast(thread_sp.get())); + + return sb_thread; +} + +SBThread SBProcess::CreateOSPluginThread(lldb::tid_t tid, + lldb::addr_t context) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->CreateOSPluginThread(tid, context); + sb_thread.SetThread(thread_sp); + } + + if (log) + log->Printf("SBProcess(%p)::CreateOSPluginThread (tid=0x%" PRIx64 + ", context=0x%" PRIx64 ") => SBThread(%p)", + static_cast(process_sp.get()), tid, context, + static_cast(thread_sp.get())); + + return sb_thread; +} + +SBTarget SBProcess::GetTarget() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBTarget sb_target; + TargetSP target_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + target_sp = process_sp->GetTarget().shared_from_this(); + sb_target.SetSP(target_sp); + } + + if (log) + log->Printf("SBProcess(%p)::GetTarget () => SBTarget(%p)", + static_cast(process_sp.get()), + static_cast(target_sp.get())); + + return sb_target; +} + +size_t SBProcess::PutSTDIN(const char *src, size_t src_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + size_t ret_val = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Error error; + ret_val = process_sp->PutSTDIN(src, src_len, error); + } + + if (log) + log->Printf("SBProcess(%p)::PutSTDIN (src=\"%s\", src_len=%" PRIu64 + ") => %" PRIu64, + static_cast(process_sp.get()), src, + static_cast(src_len), static_cast(ret_val)); + + return ret_val; +} + +size_t SBProcess::GetSTDOUT(char *dst, size_t dst_len) const { + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Error error; + bytes_read = process_sp->GetSTDOUT(dst, dst_len, error); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::GetSTDOUT (dst=\"%.*s\", dst_len=%" PRIu64 + ") => %" PRIu64, + static_cast(process_sp.get()), static_cast(bytes_read), + dst, static_cast(dst_len), static_cast(bytes_read)); + + return bytes_read; +} + +size_t SBProcess::GetSTDERR(char *dst, size_t dst_len) const { + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Error error; + bytes_read = process_sp->GetSTDERR(dst, dst_len, error); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::GetSTDERR (dst=\"%.*s\", dst_len=%" PRIu64 + ") => %" PRIu64, + static_cast(process_sp.get()), static_cast(bytes_read), + dst, static_cast(dst_len), static_cast(bytes_read)); + + return bytes_read; +} + +size_t SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const { + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Error error; + bytes_read = process_sp->GetAsyncProfileData(dst, dst_len, error); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::GetAsyncProfileData (dst=\"%.*s\", dst_len=%" PRIu64 + ") => %" PRIu64, + static_cast(process_sp.get()), static_cast(bytes_read), + dst, static_cast(dst_len), static_cast(bytes_read)); + + return bytes_read; +} + +void SBProcess::ReportEventState(const SBEvent &event, FILE *out) const { + if (out == NULL) + return; + + ProcessSP process_sp(GetSP()); + if (process_sp) { + const StateType event_state = SBProcess::GetStateFromEvent(event); + char message[1024]; + int message_len = ::snprintf( + message, sizeof(message), "Process %" PRIu64 " %s\n", + process_sp->GetID(), SBDebugger::StateAsCString(event_state)); + + if (message_len > 0) + ::fwrite(message, 1, message_len, out); + } +} + +void SBProcess::AppendEventStateReport(const SBEvent &event, + SBCommandReturnObject &result) { + ProcessSP process_sp(GetSP()); + if (process_sp) { + const StateType event_state = SBProcess::GetStateFromEvent(event); + char message[1024]; + ::snprintf(message, sizeof(message), "Process %" PRIu64 " %s\n", + process_sp->GetID(), SBDebugger::StateAsCString(event_state)); + + result.AppendMessage(message); + } +} + +bool SBProcess::SetSelectedThread(const SBThread &thread) { + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + return process_sp->GetThreadList().SetSelectedThreadByID( + thread.GetThreadID()); + } + return false; +} + +bool SBProcess::SetSelectedThreadByID(lldb::tid_t tid) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + bool ret_val = false; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetThreadList().SetSelectedThreadByID(tid); + } + + if (log) + log->Printf("SBProcess(%p)::SetSelectedThreadByID (tid=0x%4.4" PRIx64 + ") => %s", + static_cast(process_sp.get()), tid, + (ret_val ? "true" : "false")); + + return ret_val; +} + +bool SBProcess::SetSelectedThreadByIndexID(uint32_t index_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + bool ret_val = false; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetThreadList().SetSelectedThreadByIndexID(index_id); + } + + if (log) + log->Printf("SBProcess(%p)::SetSelectedThreadByID (tid=0x%x) => %s", + static_cast(process_sp.get()), index_id, + (ret_val ? "true" : "false")); + + return ret_val; +} + +SBThread SBProcess::GetThreadAtIndex(size_t index) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().GetThreadAtIndex(index, can_update); + sb_thread.SetThread(thread_sp); + } + + if (log) + log->Printf("SBProcess(%p)::GetThreadAtIndex (index=%d) => SBThread(%p)", + static_cast(process_sp.get()), + static_cast(index), + static_cast(thread_sp.get())); + + return sb_thread; +} + +uint32_t SBProcess::GetNumQueues() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + uint32_t num_queues = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + num_queues = process_sp->GetQueueList().GetSize(); + } + } + + if (log) + log->Printf("SBProcess(%p)::GetNumQueues () => %d", + static_cast(process_sp.get()), num_queues); + + return num_queues; +} + +SBQueue SBProcess::GetQueueAtIndex(size_t index) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBQueue sb_queue; + QueueSP queue_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + queue_sp = process_sp->GetQueueList().GetQueueAtIndex(index); + sb_queue.SetQueue(queue_sp); } + } + + if (log) + log->Printf("SBProcess(%p)::GetQueueAtIndex (index=%d) => SBQueue(%p)", + static_cast(process_sp.get()), + static_cast(index), + static_cast(queue_sp.get())); + + return sb_queue; +} + +uint32_t SBProcess::GetStopID(bool include_expression_stops) { + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + if (include_expression_stops) + return process_sp->GetStopID(); else - sb_error.SetErrorString ("SBProcess is invalid"); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::Kill () => SBError (%p): %s", - static_cast(process_sp.get()), - static_cast(sb_error.get()), sstr.GetData()); - } + return process_sp->GetLastNaturalStopID(); + } + return 0; +} + +SBEvent SBProcess::GetStopEventForStopID(uint32_t stop_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBEvent sb_event; + EventSP event_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + event_sp = process_sp->GetStopEventForStopID(stop_id); + sb_event.reset(event_sp); + } + + if (log) + log->Printf("SBProcess(%p)::GetStopEventForStopID (stop_id=%" PRIu32 + ") => SBEvent(%p)", + static_cast(process_sp.get()), stop_id, + static_cast(event_sp.get())); + + return sb_event; +} + +StateType SBProcess::GetState() { + + StateType ret_val = eStateInvalid; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + ret_val = process_sp->GetState(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetState () => %s", + static_cast(process_sp.get()), + lldb_private::StateAsCString(ret_val)); + + return ret_val; +} + +int SBProcess::GetExitStatus() { + int exit_status = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + exit_status = process_sp->GetExitStatus(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetExitStatus () => %i (0x%8.8x)", + static_cast(process_sp.get()), exit_status, + exit_status); + + return exit_status; +} + +const char *SBProcess::GetExitDescription() { + const char *exit_desc = NULL; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + exit_desc = process_sp->GetExitDescription(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetExitDescription () => %s", + static_cast(process_sp.get()), exit_desc); + return exit_desc; +} + +lldb::pid_t SBProcess::GetProcessID() { + lldb::pid_t ret_val = LLDB_INVALID_PROCESS_ID; + ProcessSP process_sp(GetSP()); + if (process_sp) + ret_val = process_sp->GetID(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetProcessID () => %" PRIu64, + static_cast(process_sp.get()), ret_val); + + return ret_val; +} + +uint32_t SBProcess::GetUniqueID() { + uint32_t ret_val = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) + ret_val = process_sp->GetUniqueID(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetUniqueID () => %" PRIu32, + static_cast(process_sp.get()), ret_val); + return ret_val; +} + +ByteOrder SBProcess::GetByteOrder() const { + ByteOrder byteOrder = eByteOrderInvalid; + ProcessSP process_sp(GetSP()); + if (process_sp) + byteOrder = process_sp->GetTarget().GetArchitecture().GetByteOrder(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetByteOrder () => %d", + static_cast(process_sp.get()), byteOrder); + + return byteOrder; +} - return sb_error; -} +uint32_t SBProcess::GetAddressByteSize() const { + uint32_t size = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) + size = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); -SBError -SBProcess::Detach () -{ - // FIXME: This should come from a process default. - bool keep_stopped = false; - return Detach (keep_stopped); -} - -SBError -SBProcess::Detach (bool keep_stopped) -{ - SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError (process_sp->Detach(keep_stopped)); - } - else - sb_error.SetErrorString ("SBProcess is invalid"); - - return sb_error; -} + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetAddressByteSize () => %d", + static_cast(process_sp.get()), size); + + return size; +} + +SBError SBProcess::Continue() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBError sb_error; + ProcessSP process_sp(GetSP()); + + if (log) + log->Printf("SBProcess(%p)::Continue ()...", + static_cast(process_sp.get())); -SBError -SBProcess::Signal (int signo) -{ - SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError (process_sp->Signal (signo)); - } + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + + if (process_sp->GetTarget().GetDebugger().GetAsyncExecution()) + sb_error.ref() = process_sp->Resume(); else - sb_error.SetErrorString ("SBProcess is invalid"); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::Signal (signo=%i) => SBError (%p): %s", - static_cast(process_sp.get()), signo, - static_cast(sb_error.get()), sstr.GetData()); - } - return sb_error; -} + sb_error.ref() = process_sp->ResumeSynchronous(NULL); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::Continue () => SBError (%p): %s", + static_cast(process_sp.get()), + static_cast(sb_error.get()), sstr.GetData()); + } + + return sb_error; +} + +SBError SBProcess::Destroy() { + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Destroy(false)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::Destroy () => SBError (%p): %s", + static_cast(process_sp.get()), + static_cast(sb_error.get()), sstr.GetData()); + } + + return sb_error; +} + +SBError SBProcess::Stop() { + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Halt()); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::Stop () => SBError (%p): %s", + static_cast(process_sp.get()), + static_cast(sb_error.get()), sstr.GetData()); + } + + return sb_error; +} + +SBError SBProcess::Kill() { + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Destroy(true)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::Kill () => SBError (%p): %s", + static_cast(process_sp.get()), + static_cast(sb_error.get()), sstr.GetData()); + } + + return sb_error; +} + +SBError SBProcess::Detach() { + // FIXME: This should come from a process default. + bool keep_stopped = false; + return Detach(keep_stopped); +} + +SBError SBProcess::Detach(bool keep_stopped) { + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Detach(keep_stopped)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + + return sb_error; +} + +SBError SBProcess::Signal(int signo) { + SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->Signal(signo)); + } else + sb_error.SetErrorString("SBProcess is invalid"); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::Signal (signo=%i) => SBError (%p): %s", + static_cast(process_sp.get()), signo, + static_cast(sb_error.get()), sstr.GetData()); + } + return sb_error; +} + +SBUnixSignals SBProcess::GetUnixSignals() { + if (auto process_sp = GetSP()) + return SBUnixSignals{process_sp}; + + return {}; +} + +void SBProcess::SendAsyncInterrupt() { + ProcessSP process_sp(GetSP()); + if (process_sp) { + process_sp->SendAsyncInterrupt(); + } +} + +SBThread SBProcess::GetThreadByID(tid_t tid) { + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = process_sp->GetThreadList().FindThreadByID(tid, can_update); + sb_thread.SetThread(thread_sp); + } -SBUnixSignals -SBProcess::GetUnixSignals() -{ - if (auto process_sp = GetSP()) - return SBUnixSignals{process_sp}; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetThreadByID (tid=0x%4.4" PRIx64 + ") => SBThread (%p)", + static_cast(process_sp.get()), tid, + static_cast(thread_sp.get())); - return {}; + return sb_thread; } -void -SBProcess::SendAsyncInterrupt () -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - process_sp->SendAsyncInterrupt (); - } -} - -SBThread -SBProcess::GetThreadByID (tid_t tid) -{ - SBThread sb_thread; - ThreadSP thread_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - thread_sp = process_sp->GetThreadList().FindThreadByID (tid, can_update); - sb_thread.SetThread (thread_sp); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetThreadByID (tid=0x%4.4" PRIx64 ") => SBThread (%p)", - static_cast(process_sp.get()), tid, - static_cast(thread_sp.get())); - - return sb_thread; -} - -SBThread -SBProcess::GetThreadByIndexID (uint32_t index_id) -{ - SBThread sb_thread; - ThreadSP thread_sp; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - thread_sp = process_sp->GetThreadList().FindThreadByIndexID (index_id, can_update); - sb_thread.SetThread (thread_sp); - } +SBThread SBProcess::GetThreadByIndexID(uint32_t index_id) { + SBThread sb_thread; + ThreadSP thread_sp; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + thread_sp = + process_sp->GetThreadList().FindThreadByIndexID(index_id, can_update); + sb_thread.SetThread(thread_sp); + } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetThreadByID (tid=0x%x) => SBThread (%p)", - static_cast(process_sp.get()), index_id, - static_cast(thread_sp.get())); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetThreadByID (tid=0x%x) => SBThread (%p)", + static_cast(process_sp.get()), index_id, + static_cast(thread_sp.get())); - return sb_thread; + return sb_thread; } -StateType -SBProcess::GetStateFromEvent (const SBEvent &event) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +StateType SBProcess::GetStateFromEvent(const SBEvent &event) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - StateType ret_val = Process::ProcessEventData::GetStateFromEvent (event.get()); + StateType ret_val = Process::ProcessEventData::GetStateFromEvent(event.get()); - if (log) - log->Printf ("SBProcess::GetStateFromEvent (event.sp=%p) => %s", - static_cast(event.get()), - lldb_private::StateAsCString (ret_val)); + if (log) + log->Printf("SBProcess::GetStateFromEvent (event.sp=%p) => %s", + static_cast(event.get()), + lldb_private::StateAsCString(ret_val)); - return ret_val; + return ret_val; } -bool -SBProcess::GetRestartedFromEvent (const SBEvent &event) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBProcess::GetRestartedFromEvent(const SBEvent &event) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - bool ret_val = Process::ProcessEventData::GetRestartedFromEvent (event.get()); + bool ret_val = Process::ProcessEventData::GetRestartedFromEvent(event.get()); - if (log) - log->Printf ("SBProcess::%s (event.sp=%p) => %d", __FUNCTION__, - static_cast(event.get()), ret_val); + if (log) + log->Printf("SBProcess::%s (event.sp=%p) => %d", __FUNCTION__, + static_cast(event.get()), ret_val); - return ret_val; + return ret_val; } -size_t -SBProcess::GetNumRestartedReasonsFromEvent (const lldb::SBEvent &event) -{ - return Process::ProcessEventData::GetNumRestartedReasons(event.get()); +size_t SBProcess::GetNumRestartedReasonsFromEvent(const lldb::SBEvent &event) { + return Process::ProcessEventData::GetNumRestartedReasons(event.get()); } const char * -SBProcess::GetRestartedReasonAtIndexFromEvent (const lldb::SBEvent &event, size_t idx) -{ - return Process::ProcessEventData::GetRestartedReasonAtIndex(event.get(), idx); -} - -SBProcess -SBProcess::GetProcessFromEvent (const SBEvent &event) -{ - ProcessSP process_sp = - Process::ProcessEventData::GetProcessFromEvent (event.get()); - if (!process_sp) - { - // StructuredData events also know the process they come from. - // Try that. - process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); - } - - return SBProcess(process_sp); -} - -bool -SBProcess::GetInterruptedFromEvent (const SBEvent &event) -{ - return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); -} - -lldb::SBStructuredData -SBProcess::GetStructuredDataFromEvent (const lldb::SBEvent &event) -{ - return SBStructuredData(event.GetSP()); -} - -bool -SBProcess::EventIsProcessEvent (const SBEvent &event) -{ - return (event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass()) && - !EventIsStructuredDataEvent (event); -} - -bool -SBProcess::EventIsStructuredDataEvent (const lldb::SBEvent &event) -{ - EventSP event_sp = event.GetSP(); - EventData *event_data = event_sp ? event_sp->GetData() : nullptr; - return event_data && - (event_data->GetFlavor() == EventDataStructuredData::GetFlavorString()); +SBProcess::GetRestartedReasonAtIndexFromEvent(const lldb::SBEvent &event, + size_t idx) { + return Process::ProcessEventData::GetRestartedReasonAtIndex(event.get(), idx); } -SBBroadcaster -SBProcess::GetBroadcaster () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBProcess SBProcess::GetProcessFromEvent(const SBEvent &event) { + ProcessSP process_sp = + Process::ProcessEventData::GetProcessFromEvent(event.get()); + if (!process_sp) { + // StructuredData events also know the process they come from. + // Try that. + process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); + } - ProcessSP process_sp(GetSP()); - - SBBroadcaster broadcaster(process_sp.get(), false); - - if (log) - log->Printf ("SBProcess(%p)::GetBroadcaster () => SBBroadcaster (%p)", - static_cast(process_sp.get()), - static_cast(broadcaster.get())); - - return broadcaster; + return SBProcess(process_sp); } -const char * -SBProcess::GetBroadcasterClass () -{ - return Process::GetStaticBroadcasterClass().AsCString(); +bool SBProcess::GetInterruptedFromEvent(const SBEvent &event) { + return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); } -size_t -SBProcess::ReadMemory (addr_t addr, void *dst, size_t dst_len, SBError &sb_error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - size_t bytes_read = 0; - - ProcessSP process_sp(GetSP()); - - if (log) - log->Printf ("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 ", dst=%p, dst_len=%" PRIu64 ", SBError (%p))...", - static_cast(process_sp.get()), addr, - static_cast(dst), static_cast(dst_len), - static_cast(sb_error.get())); - - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - bytes_read = process_sp->ReadMemory (addr, dst, dst_len, sb_error.ref()); - } - else - { - if (log) - log->Printf ("SBProcess(%p)::ReadMemory() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 ", dst=%p, dst_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, - static_cast(process_sp.get()), addr, - static_cast(dst), static_cast(dst_len), - static_cast(sb_error.get()), sstr.GetData(), - static_cast(bytes_read)); - } - - return bytes_read; -} - -size_t -SBProcess::ReadCStringFromMemory (addr_t addr, void *buf, size_t size, lldb::SBError &sb_error) -{ - size_t bytes_read = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - bytes_read = process_sp->ReadCStringFromMemory (addr, (char *)buf, size, sb_error.ref()); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::ReadCStringFromMemory() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return bytes_read; -} - -uint64_t -SBProcess::ReadUnsignedFromMemory (addr_t addr, uint32_t byte_size, lldb::SBError &sb_error) -{ - uint64_t value = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - value = process_sp->ReadUnsignedIntegerFromMemory (addr, byte_size, 0, sb_error.ref()); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::ReadUnsignedFromMemory() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return value; -} - -lldb::addr_t -SBProcess::ReadPointerFromMemory (addr_t addr, lldb::SBError &sb_error) -{ - lldb::addr_t ptr = LLDB_INVALID_ADDRESS; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - ptr = process_sp->ReadPointerFromMemory (addr, sb_error.ref()); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::ReadPointerFromMemory() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return ptr; -} - -size_t -SBProcess::WriteMemory (addr_t addr, const void *src, size_t src_len, SBError &sb_error) -{ - size_t bytes_written = 0; - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - ProcessSP process_sp(GetSP()); - - if (log) - log->Printf ("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 ", src=%p, src_len=%" PRIu64 ", SBError (%p))...", - static_cast(process_sp.get()), addr, - static_cast(src), - static_cast(src_len), - static_cast(sb_error.get())); - - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - bytes_written = process_sp->WriteMemory (addr, src, src_len, sb_error.ref()); - } - else - { - if (log) - log->Printf ("SBProcess(%p)::WriteMemory() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - - if (log) - { - SBStream sstr; - sb_error.GetDescription (sstr); - log->Printf ("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 ", src=%p, src_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, - static_cast(process_sp.get()), addr, - static_cast(src), - static_cast(src_len), - static_cast(sb_error.get()), sstr.GetData(), - static_cast(bytes_written)); - } - - return bytes_written; -} - -bool -SBProcess::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - - ProcessSP process_sp(GetSP()); - if (process_sp) - { - char path[PATH_MAX]; - GetTarget().GetExecutable().GetPath (path, sizeof(path)); - Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); - const char *exe_name = NULL; - if (exe_module) - exe_name = exe_module->GetFileSpec().GetFilename().AsCString(); - - strm.Printf ("SBProcess: pid = %" PRIu64 ", state = %s, threads = %d%s%s", - process_sp->GetID(), - lldb_private::StateAsCString (GetState()), - GetNumThreads(), - exe_name ? ", executable = " : "", - exe_name ? exe_name : ""); - } - else - strm.PutCString ("No value"); - - return true; -} - -uint32_t -SBProcess::GetNumSupportedHardwareWatchpoints (lldb::SBError &sb_error) const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t num = 0; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError(process_sp->GetWatchpointSupportInfo (num)); - if (log) - log->Printf ("SBProcess(%p)::GetNumSupportedHardwareWatchpoints () => %u", - static_cast(process_sp.get()), num); - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return num; -} - -uint32_t -SBProcess::LoadImage (lldb::SBFileSpec &sb_remote_image_spec, lldb::SBError &sb_error) -{ - return LoadImage(SBFileSpec(), sb_remote_image_spec, sb_error); -} - -uint32_t -SBProcess::LoadImage (const lldb::SBFileSpec &sb_local_image_spec, - const lldb::SBFileSpec &sb_remote_image_spec, - lldb::SBError &sb_error) -{ - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); - return platform_sp->LoadImage (process_sp.get(), - *sb_local_image_spec, - *sb_remote_image_spec, - sb_error.ref()); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::LoadImage() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - return LLDB_INVALID_IMAGE_TOKEN; -} - -lldb::SBError -SBProcess::UnloadImage (uint32_t image_token) -{ - lldb::SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); - sb_error.SetError (platform_sp->UnloadImage (process_sp.get(), image_token)); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::UnloadImage() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - sb_error.SetErrorString("invalid process"); - return sb_error; -} - -lldb::SBError -SBProcess::SendEventData (const char *event_data) -{ - lldb::SBError sb_error; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.SetError (process_sp->SendEventData (event_data)); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::SendEventData() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - sb_error.SetErrorString("invalid process"); - return sb_error; +lldb::SBStructuredData +SBProcess::GetStructuredDataFromEvent(const lldb::SBEvent &event) { + return SBStructuredData(event.GetSP()); +} + +bool SBProcess::EventIsProcessEvent(const SBEvent &event) { + return (event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass()) && + !EventIsStructuredDataEvent(event); +} + +bool SBProcess::EventIsStructuredDataEvent(const lldb::SBEvent &event) { + EventSP event_sp = event.GetSP(); + EventData *event_data = event_sp ? event_sp->GetData() : nullptr; + return event_data && (event_data->GetFlavor() == + EventDataStructuredData::GetFlavorString()); +} + +SBBroadcaster SBProcess::GetBroadcaster() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + ProcessSP process_sp(GetSP()); + + SBBroadcaster broadcaster(process_sp.get(), false); + + if (log) + log->Printf("SBProcess(%p)::GetBroadcaster () => SBBroadcaster (%p)", + static_cast(process_sp.get()), + static_cast(broadcaster.get())); + + return broadcaster; +} + +const char *SBProcess::GetBroadcasterClass() { + return Process::GetStaticBroadcasterClass().AsCString(); +} + +size_t SBProcess::ReadMemory(addr_t addr, void *dst, size_t dst_len, + SBError &sb_error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + size_t bytes_read = 0; + + ProcessSP process_sp(GetSP()); + + if (log) + log->Printf("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 + ", dst=%p, dst_len=%" PRIu64 ", SBError (%p))...", + static_cast(process_sp.get()), addr, + static_cast(dst), static_cast(dst_len), + static_cast(sb_error.get())); + + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_read = process_sp->ReadMemory(addr, dst, dst_len, sb_error.ref()); + } else { + if (log) + log->Printf("SBProcess(%p)::ReadMemory() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::ReadMemory (addr=0x%" PRIx64 + ", dst=%p, dst_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, + static_cast(process_sp.get()), addr, + static_cast(dst), static_cast(dst_len), + static_cast(sb_error.get()), sstr.GetData(), + static_cast(bytes_read)); + } + + return bytes_read; +} + +size_t SBProcess::ReadCStringFromMemory(addr_t addr, void *buf, size_t size, + lldb::SBError &sb_error) { + size_t bytes_read = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_read = process_sp->ReadCStringFromMemory(addr, (char *)buf, size, + sb_error.ref()); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::ReadCStringFromMemory() => error: process " + "is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return bytes_read; +} + +uint64_t SBProcess::ReadUnsignedFromMemory(addr_t addr, uint32_t byte_size, + lldb::SBError &sb_error) { + uint64_t value = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + value = process_sp->ReadUnsignedIntegerFromMemory(addr, byte_size, 0, + sb_error.ref()); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::ReadUnsignedFromMemory() => error: process " + "is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return value; +} + +lldb::addr_t SBProcess::ReadPointerFromMemory(addr_t addr, + lldb::SBError &sb_error) { + lldb::addr_t ptr = LLDB_INVALID_ADDRESS; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + ptr = process_sp->ReadPointerFromMemory(addr, sb_error.ref()); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::ReadPointerFromMemory() => error: process " + "is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return ptr; +} + +size_t SBProcess::WriteMemory(addr_t addr, const void *src, size_t src_len, + SBError &sb_error) { + size_t bytes_written = 0; + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + ProcessSP process_sp(GetSP()); + + if (log) + log->Printf("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 + ", src=%p, src_len=%" PRIu64 ", SBError (%p))...", + static_cast(process_sp.get()), addr, + static_cast(src), static_cast(src_len), + static_cast(sb_error.get())); + + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + bytes_written = + process_sp->WriteMemory(addr, src, src_len, sb_error.ref()); + } else { + if (log) + log->Printf("SBProcess(%p)::WriteMemory() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } + + if (log) { + SBStream sstr; + sb_error.GetDescription(sstr); + log->Printf("SBProcess(%p)::WriteMemory (addr=0x%" PRIx64 + ", src=%p, src_len=%" PRIu64 ", SBError (%p): %s) => %" PRIu64, + static_cast(process_sp.get()), addr, + static_cast(src), static_cast(src_len), + static_cast(sb_error.get()), sstr.GetData(), + static_cast(bytes_written)); + } + + return bytes_written; +} + +bool SBProcess::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + + ProcessSP process_sp(GetSP()); + if (process_sp) { + char path[PATH_MAX]; + GetTarget().GetExecutable().GetPath(path, sizeof(path)); + Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); + const char *exe_name = NULL; + if (exe_module) + exe_name = exe_module->GetFileSpec().GetFilename().AsCString(); + + strm.Printf("SBProcess: pid = %" PRIu64 ", state = %s, threads = %d%s%s", + process_sp->GetID(), lldb_private::StateAsCString(GetState()), + GetNumThreads(), exe_name ? ", executable = " : "", + exe_name ? exe_name : ""); + } else + strm.PutCString("No value"); + + return true; } uint32_t -SBProcess::GetNumExtendedBacktraceTypes () -{ - ProcessSP process_sp(GetSP()); - if (process_sp && process_sp->GetSystemRuntime()) - { - SystemRuntime *runtime = process_sp->GetSystemRuntime(); - return runtime->GetExtendedBacktraceTypes().size(); - } - return 0; -} +SBProcess::GetNumSupportedHardwareWatchpoints(lldb::SBError &sb_error) const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + uint32_t num = 0; + ProcessSP process_sp(GetSP()); + if (process_sp) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->GetWatchpointSupportInfo(num)); + if (log) + log->Printf("SBProcess(%p)::GetNumSupportedHardwareWatchpoints () => %u", + static_cast(process_sp.get()), num); + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return num; +} + +uint32_t SBProcess::LoadImage(lldb::SBFileSpec &sb_remote_image_spec, + lldb::SBError &sb_error) { + return LoadImage(SBFileSpec(), sb_remote_image_spec, sb_error); +} + +uint32_t SBProcess::LoadImage(const lldb::SBFileSpec &sb_local_image_spec, + const lldb::SBFileSpec &sb_remote_image_spec, + lldb::SBError &sb_error) { + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + return platform_sp->LoadImage(process_sp.get(), *sb_local_image_spec, + *sb_remote_image_spec, sb_error.ref()); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::LoadImage() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } + return LLDB_INVALID_IMAGE_TOKEN; +} + +lldb::SBError SBProcess::UnloadImage(uint32_t image_token) { + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); + sb_error.SetError( + platform_sp->UnloadImage(process_sp.get(), image_token)); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::UnloadImage() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else + sb_error.SetErrorString("invalid process"); + return sb_error; +} + +lldb::SBError SBProcess::SendEventData(const char *event_data) { + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.SetError(process_sp->SendEventData(event_data)); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::SendEventData() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else + sb_error.SetErrorString("invalid process"); + return sb_error; +} + +uint32_t SBProcess::GetNumExtendedBacktraceTypes() { + ProcessSP process_sp(GetSP()); + if (process_sp && process_sp->GetSystemRuntime()) { + SystemRuntime *runtime = process_sp->GetSystemRuntime(); + return runtime->GetExtendedBacktraceTypes().size(); + } + return 0; +} + +const char *SBProcess::GetExtendedBacktraceTypeAtIndex(uint32_t idx) { + ProcessSP process_sp(GetSP()); + if (process_sp && process_sp->GetSystemRuntime()) { + SystemRuntime *runtime = process_sp->GetSystemRuntime(); + const std::vector &names = + runtime->GetExtendedBacktraceTypes(); + if (idx < names.size()) { + return names[idx].AsCString(); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBProcess(%p)::GetExtendedBacktraceTypeAtIndex() => " + "error: requested extended backtrace name out of bounds", + static_cast(process_sp.get())); + } + } + return NULL; +} + +SBThreadCollection SBProcess::GetHistoryThreads(addr_t addr) { + ProcessSP process_sp(GetSP()); + SBThreadCollection threads; + if (process_sp) { + threads = SBThreadCollection(process_sp->GetHistoryThreads(addr)); + } + return threads; +} + +bool SBProcess::IsInstrumentationRuntimePresent( + InstrumentationRuntimeType type) { + ProcessSP process_sp(GetSP()); + if (!process_sp) + return false; -const char * -SBProcess::GetExtendedBacktraceTypeAtIndex (uint32_t idx) -{ - ProcessSP process_sp(GetSP()); - if (process_sp && process_sp->GetSystemRuntime()) - { - SystemRuntime *runtime = process_sp->GetSystemRuntime(); - const std::vector &names = runtime->GetExtendedBacktraceTypes(); - if (idx < names.size()) - { - return names[idx].AsCString(); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBProcess(%p)::GetExtendedBacktraceTypeAtIndex() => error: requested extended backtrace name out of bounds", - static_cast(process_sp.get())); - } - } - return NULL; -} + InstrumentationRuntimeSP runtime_sp = + process_sp->GetInstrumentationRuntime(type); -SBThreadCollection -SBProcess::GetHistoryThreads (addr_t addr) -{ - ProcessSP process_sp(GetSP()); - SBThreadCollection threads; - if (process_sp) - { - threads = SBThreadCollection(process_sp->GetHistoryThreads(addr)); - } - return threads; -} + if (!runtime_sp.get()) + return false; -bool -SBProcess::IsInstrumentationRuntimePresent(InstrumentationRuntimeType type) -{ - ProcessSP process_sp(GetSP()); - if (! process_sp) - return false; - - InstrumentationRuntimeSP runtime_sp = process_sp->GetInstrumentationRuntime(type); - - if (! runtime_sp.get()) - return false; - - return runtime_sp->IsActive(); + return runtime_sp->IsActive(); } -lldb::SBError -SBProcess::SaveCore(const char *file_name) -{ - lldb::SBError error; - ProcessSP process_sp(GetSP()); - if (!process_sp) - { - error.SetErrorString("SBProcess is invalid"); - return error; - } - - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); +lldb::SBError SBProcess::SaveCore(const char *file_name) { + lldb::SBError error; + ProcessSP process_sp(GetSP()); + if (!process_sp) { + error.SetErrorString("SBProcess is invalid"); + return error; + } - if (process_sp->GetState() != eStateStopped) - { - error.SetErrorString("the process is not stopped"); - return error; - } + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); - FileSpec core_file(file_name, false); - error.ref() = PluginManager::SaveCore(process_sp, core_file); + if (process_sp->GetState() != eStateStopped) { + error.SetErrorString("the process is not stopped"); return error; + } + + FileSpec core_file(file_name, false); + error.ref() = PluginManager::SaveCore(process_sp, core_file); + return error; } lldb::SBError -SBProcess::GetMemoryRegionInfo (lldb::addr_t load_addr, SBMemoryRegionInfo &sb_region_info) -{ - lldb::SBError sb_error; - ProcessSP process_sp(GetSP()); - MemoryRegionInfoSP region_info_sp = std::make_shared(); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - sb_error.ref() = process_sp->GetMemoryRegionInfo(load_addr, *region_info_sp); - if( sb_error.Success() ) { - sb_region_info.ref() = *region_info_sp; - } - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); - } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return sb_error; -} - -lldb::SBMemoryRegionInfoList -SBProcess::GetMemoryRegions() -{ - lldb::SBError sb_error; - lldb::SBMemoryRegionInfoList sb_region_list; - ProcessSP process_sp(GetSP()); - if (process_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process_sp->GetRunLock())) - { - std::lock_guard guard(process_sp->GetTarget().GetAPIMutex()); - std::vector region_list; - sb_error.ref() = process_sp->GetMemoryRegions(region_list); - if( sb_error.Success() ) { - std::vector::iterator end = region_list.end(); - for( std::vector::iterator it = region_list.begin(); it != end; it++ ) { - SBMemoryRegionInfo sb_region_info(it->get()); - sb_region_list.Append(sb_region_info); - } - } - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", - static_cast(process_sp.get())); - sb_error.SetErrorString("process is running"); +SBProcess::GetMemoryRegionInfo(lldb::addr_t load_addr, + SBMemoryRegionInfo &sb_region_info) { + lldb::SBError sb_error; + ProcessSP process_sp(GetSP()); + MemoryRegionInfoSP region_info_sp = + std::make_shared(); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + sb_error.ref() = + process_sp->GetMemoryRegionInfo(load_addr, *region_info_sp); + if (sb_error.Success()) { + sb_region_info.ref() = *region_info_sp; + } + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return sb_error; +} + +lldb::SBMemoryRegionInfoList SBProcess::GetMemoryRegions() { + lldb::SBError sb_error; + lldb::SBMemoryRegionInfoList sb_region_list; + ProcessSP process_sp(GetSP()); + if (process_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process_sp->GetRunLock())) { + std::lock_guard guard( + process_sp->GetTarget().GetAPIMutex()); + std::vector region_list; + sb_error.ref() = process_sp->GetMemoryRegions(region_list); + if (sb_error.Success()) { + std::vector::iterator end = region_list.end(); + for (std::vector::iterator it = region_list.begin(); + it != end; it++) { + SBMemoryRegionInfo sb_region_info(it->get()); + sb_region_list.Append(sb_region_info); } - } - else - { - sb_error.SetErrorString ("SBProcess is invalid"); - } - return sb_region_list; + } + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBProcess(%p)::GetMemoryRegionInfo() => error: process is running", + static_cast(process_sp.get())); + sb_error.SetErrorString("process is running"); + } + } else { + sb_error.SetErrorString("SBProcess is invalid"); + } + return sb_region_list; } diff --git a/lldb/source/API/SBQueue.cpp b/lldb/source/API/SBQueue.cpp index be4c5fda154..c6f53057a7a 100644 --- a/lldb/source/API/SBQueue.cpp +++ b/lldb/source/API/SBQueue.cpp @@ -12,8 +12,8 @@ #include "lldb/API/SBQueue.h" #include "lldb/API/SBProcess.h" -#include "lldb/API/SBThread.h" #include "lldb/API/SBQueueItem.h" +#include "lldb/API/SBThread.h" #include "lldb/Core/Log.h" #include "lldb/Target/Process.h" @@ -24,427 +24,324 @@ using namespace lldb; using namespace lldb_private; -namespace lldb_private -{ - - class QueueImpl - { - public: - QueueImpl () : - m_queue_wp(), - m_threads(), - m_thread_list_fetched(false), - m_pending_items(), - m_pending_items_fetched(false) - { - } - - QueueImpl (const lldb::QueueSP &queue_sp) : - m_queue_wp(), - m_threads(), - m_thread_list_fetched(false), - m_pending_items(), - m_pending_items_fetched(false) - { - m_queue_wp = queue_sp; - } - - QueueImpl (const QueueImpl &rhs) - { - if (&rhs == this) - return; - m_queue_wp = rhs.m_queue_wp; - m_threads = rhs.m_threads; - m_thread_list_fetched = rhs.m_thread_list_fetched; - m_pending_items = rhs.m_pending_items; - m_pending_items_fetched = rhs.m_pending_items_fetched; - } +namespace lldb_private { - ~QueueImpl () - { - } - - bool - IsValid () - { - return m_queue_wp.lock() != NULL; - } +class QueueImpl { +public: + QueueImpl() + : m_queue_wp(), m_threads(), m_thread_list_fetched(false), + m_pending_items(), m_pending_items_fetched(false) {} - void - Clear () - { - m_queue_wp.reset(); - m_thread_list_fetched = false; - m_threads.clear(); - m_pending_items_fetched = false; - m_pending_items.clear(); - } - - void - SetQueue (const lldb::QueueSP &queue_sp) - { - Clear(); - m_queue_wp = queue_sp; - } - - lldb::queue_id_t - GetQueueID () const - { - lldb::queue_id_t result = LLDB_INVALID_QUEUE_ID; - lldb::QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - { - result = queue_sp->GetID(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBQueue(%p)::GetQueueID () => 0x%" PRIx64, - static_cast(this), result); - return result; - } - - uint32_t - GetIndexID () const - { - uint32_t result = LLDB_INVALID_INDEX32; - lldb::QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - { - result = queue_sp->GetIndexID(); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBQueueImpl(%p)::GetIndexID () => %d", - static_cast(this), result); - return result; - } - - const char * - GetName () const - { - const char *name = NULL; - lldb::QueueSP queue_sp = m_queue_wp.lock (); - if (queue_sp.get()) - { - name = queue_sp->GetName(); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBQueueImpl(%p)::GetName () => %s", - static_cast(this), - name ? name : "NULL"); - - return name; - } - - void - FetchThreads () - { - if (m_thread_list_fetched == false) - { - lldb::QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock (&queue_sp->GetProcess()->GetRunLock())) - { - const std::vector thread_list(queue_sp->GetThreads()); - m_thread_list_fetched = true; - const uint32_t num_threads = thread_list.size(); - for (uint32_t idx = 0; idx < num_threads; ++idx) - { - ThreadSP thread_sp = thread_list[idx]; - if (thread_sp && thread_sp->IsValid()) - { - m_threads.push_back (thread_sp); - } - } - } - } - } - } - - void - FetchItems () - { - if (m_pending_items_fetched == false) - { - QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock (&queue_sp->GetProcess()->GetRunLock())) - { - const std::vector queue_items(queue_sp->GetPendingItems()); - m_pending_items_fetched = true; - const uint32_t num_pending_items = queue_items.size(); - for (uint32_t idx = 0; idx < num_pending_items; ++idx) - { - QueueItemSP item = queue_items[idx]; - if (item && item->IsValid()) - { - m_pending_items.push_back (item); - } - } - } - } - } - } - - uint32_t - GetNumThreads () - { - uint32_t result = 0; - - FetchThreads(); - if (m_thread_list_fetched) - { - result = m_threads.size(); - } - return result; - } - - lldb::SBThread - GetThreadAtIndex (uint32_t idx) - { - FetchThreads(); - - SBThread sb_thread; - QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp && idx < m_threads.size()) - { - ProcessSP process_sp = queue_sp->GetProcess(); - if (process_sp) - { - ThreadSP thread_sp = m_threads[idx].lock(); - if (thread_sp) - { - sb_thread.SetThread (thread_sp); - } - } - } - return sb_thread; - } + QueueImpl(const lldb::QueueSP &queue_sp) + : m_queue_wp(), m_threads(), m_thread_list_fetched(false), + m_pending_items(), m_pending_items_fetched(false) { + m_queue_wp = queue_sp; + } - uint32_t - GetNumPendingItems () - { - uint32_t result = 0; - - QueueSP queue_sp = m_queue_wp.lock(); - if (m_pending_items_fetched == false && queue_sp) - { - result = queue_sp->GetNumPendingWorkItems(); - } - else - { - result = m_pending_items.size(); - } - return result; - } + QueueImpl(const QueueImpl &rhs) { + if (&rhs == this) + return; + m_queue_wp = rhs.m_queue_wp; + m_threads = rhs.m_threads; + m_thread_list_fetched = rhs.m_thread_list_fetched; + m_pending_items = rhs.m_pending_items; + m_pending_items_fetched = rhs.m_pending_items_fetched; + } + + ~QueueImpl() {} + + bool IsValid() { return m_queue_wp.lock() != NULL; } + + void Clear() { + m_queue_wp.reset(); + m_thread_list_fetched = false; + m_threads.clear(); + m_pending_items_fetched = false; + m_pending_items.clear(); + } + + void SetQueue(const lldb::QueueSP &queue_sp) { + Clear(); + m_queue_wp = queue_sp; + } + + lldb::queue_id_t GetQueueID() const { + lldb::queue_id_t result = LLDB_INVALID_QUEUE_ID; + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result = queue_sp->GetID(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(%p)::GetQueueID () => 0x%" PRIx64, + static_cast(this), result); + return result; + } + + uint32_t GetIndexID() const { + uint32_t result = LLDB_INVALID_INDEX32; + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result = queue_sp->GetIndexID(); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueueImpl(%p)::GetIndexID () => %d", + static_cast(this), result); + return result; + } + + const char *GetName() const { + const char *name = NULL; + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp.get()) { + name = queue_sp->GetName(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueueImpl(%p)::GetName () => %s", + static_cast(this), name ? name : "NULL"); - lldb::SBQueueItem - GetPendingItemAtIndex (uint32_t idx) - { - SBQueueItem result; - FetchItems(); - if (m_pending_items_fetched && idx < m_pending_items.size()) - { - result.SetQueueItem (m_pending_items[idx]); + return name; + } + + void FetchThreads() { + if (m_thread_list_fetched == false) { + lldb::QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&queue_sp->GetProcess()->GetRunLock())) { + const std::vector thread_list(queue_sp->GetThreads()); + m_thread_list_fetched = true; + const uint32_t num_threads = thread_list.size(); + for (uint32_t idx = 0; idx < num_threads; ++idx) { + ThreadSP thread_sp = thread_list[idx]; + if (thread_sp && thread_sp->IsValid()) { + m_threads.push_back(thread_sp); } - return result; + } } - - uint32_t - GetNumRunningItems () - { - uint32_t result = 0; - QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - result = queue_sp->GetNumRunningWorkItems(); - return result; - } - - lldb::SBProcess - GetProcess () - { - SBProcess result; - QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - { - result.SetSP (queue_sp->GetProcess()); + } + } + } + + void FetchItems() { + if (m_pending_items_fetched == false) { + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&queue_sp->GetProcess()->GetRunLock())) { + const std::vector queue_items( + queue_sp->GetPendingItems()); + m_pending_items_fetched = true; + const uint32_t num_pending_items = queue_items.size(); + for (uint32_t idx = 0; idx < num_pending_items; ++idx) { + QueueItemSP item = queue_items[idx]; + if (item && item->IsValid()) { + m_pending_items.push_back(item); } - return result; + } } - - lldb::QueueKind - GetKind () - { - lldb::QueueKind kind = eQueueKindUnknown; - QueueSP queue_sp = m_queue_wp.lock(); - if (queue_sp) - kind = queue_sp->GetKind(); - - return kind; + } + } + } + + uint32_t GetNumThreads() { + uint32_t result = 0; + + FetchThreads(); + if (m_thread_list_fetched) { + result = m_threads.size(); + } + return result; + } + + lldb::SBThread GetThreadAtIndex(uint32_t idx) { + FetchThreads(); + + SBThread sb_thread; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp && idx < m_threads.size()) { + ProcessSP process_sp = queue_sp->GetProcess(); + if (process_sp) { + ThreadSP thread_sp = m_threads[idx].lock(); + if (thread_sp) { + sb_thread.SetThread(thread_sp); } - - private: - lldb::QueueWP m_queue_wp; - std::vector m_threads; // threads currently executing this queue's items - bool m_thread_list_fetched; // have we tried to fetch the threads list already? - std::vector m_pending_items; // items currently enqueued - bool m_pending_items_fetched; // have we tried to fetch the item list already? - }; - + } + } + return sb_thread; + } + + uint32_t GetNumPendingItems() { + uint32_t result = 0; + + QueueSP queue_sp = m_queue_wp.lock(); + if (m_pending_items_fetched == false && queue_sp) { + result = queue_sp->GetNumPendingWorkItems(); + } else { + result = m_pending_items.size(); + } + return result; + } + + lldb::SBQueueItem GetPendingItemAtIndex(uint32_t idx) { + SBQueueItem result; + FetchItems(); + if (m_pending_items_fetched && idx < m_pending_items.size()) { + result.SetQueueItem(m_pending_items[idx]); + } + return result; + } + + uint32_t GetNumRunningItems() { + uint32_t result = 0; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) + result = queue_sp->GetNumRunningWorkItems(); + return result; + } + + lldb::SBProcess GetProcess() { + SBProcess result; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) { + result.SetSP(queue_sp->GetProcess()); + } + return result; + } + + lldb::QueueKind GetKind() { + lldb::QueueKind kind = eQueueKindUnknown; + QueueSP queue_sp = m_queue_wp.lock(); + if (queue_sp) + kind = queue_sp->GetKind(); + + return kind; + } + +private: + lldb::QueueWP m_queue_wp; + std::vector + m_threads; // threads currently executing this queue's items + bool + m_thread_list_fetched; // have we tried to fetch the threads list already? + std::vector m_pending_items; // items currently enqueued + bool m_pending_items_fetched; // have we tried to fetch the item list already? +}; } -SBQueue::SBQueue () : - m_opaque_sp (new QueueImpl()) -{ -} +SBQueue::SBQueue() : m_opaque_sp(new QueueImpl()) {} -SBQueue::SBQueue (const QueueSP& queue_sp) : - m_opaque_sp (new QueueImpl (queue_sp)) -{ -} +SBQueue::SBQueue(const QueueSP &queue_sp) + : m_opaque_sp(new QueueImpl(queue_sp)) {} -SBQueue::SBQueue (const SBQueue &rhs) -{ - if (&rhs == this) - return; +SBQueue::SBQueue(const SBQueue &rhs) { + if (&rhs == this) + return; - m_opaque_sp = rhs.m_opaque_sp; + m_opaque_sp = rhs.m_opaque_sp; } -const lldb::SBQueue & -SBQueue::operator = (const lldb::SBQueue &rhs) -{ - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const lldb::SBQueue &SBQueue::operator=(const lldb::SBQueue &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -SBQueue::~SBQueue() -{ -} +SBQueue::~SBQueue() {} -bool -SBQueue::IsValid() const -{ - bool is_valid = m_opaque_sp->IsValid (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::IsValid() == %s", m_opaque_sp->GetQueueID(), - is_valid ? "true" : "false"); - return is_valid; +bool SBQueue::IsValid() const { + bool is_valid = m_opaque_sp->IsValid(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::IsValid() == %s", + m_opaque_sp->GetQueueID(), is_valid ? "true" : "false"); + return is_valid; } - -void -SBQueue::Clear () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::Clear()", m_opaque_sp->GetQueueID()); - m_opaque_sp->Clear(); +void SBQueue::Clear() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::Clear()", m_opaque_sp->GetQueueID()); + m_opaque_sp->Clear(); } - -void -SBQueue::SetQueue (const QueueSP& queue_sp) -{ - m_opaque_sp->SetQueue (queue_sp); +void SBQueue::SetQueue(const QueueSP &queue_sp) { + m_opaque_sp->SetQueue(queue_sp); } -lldb::queue_id_t -SBQueue::GetQueueID () const -{ - lldb::queue_id_t qid = m_opaque_sp->GetQueueID (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetQueueID() == 0x%" PRIx64, m_opaque_sp->GetQueueID(), (uint64_t) qid); - return qid; +lldb::queue_id_t SBQueue::GetQueueID() const { + lldb::queue_id_t qid = m_opaque_sp->GetQueueID(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetQueueID() == 0x%" PRIx64, + m_opaque_sp->GetQueueID(), (uint64_t)qid); + return qid; } -uint32_t -SBQueue::GetIndexID () const -{ - uint32_t index_id = m_opaque_sp->GetIndexID (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetIndexID() == 0x%" PRIx32, m_opaque_sp->GetQueueID(), index_id); - return index_id; +uint32_t SBQueue::GetIndexID() const { + uint32_t index_id = m_opaque_sp->GetIndexID(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetIndexID() == 0x%" PRIx32, + m_opaque_sp->GetQueueID(), index_id); + return index_id; } -const char * -SBQueue::GetName () const -{ - const char *name = m_opaque_sp->GetName (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetName() == %s", m_opaque_sp->GetQueueID(), - name ? name : ""); - return name; +const char *SBQueue::GetName() const { + const char *name = m_opaque_sp->GetName(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetName() == %s", + m_opaque_sp->GetQueueID(), name ? name : ""); + return name; } -uint32_t -SBQueue::GetNumThreads () -{ - uint32_t numthreads = m_opaque_sp->GetNumThreads (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumThreads() == %d", m_opaque_sp->GetQueueID(), numthreads); - return numthreads; +uint32_t SBQueue::GetNumThreads() { + uint32_t numthreads = m_opaque_sp->GetNumThreads(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetNumThreads() == %d", + m_opaque_sp->GetQueueID(), numthreads); + return numthreads; } -SBThread -SBQueue::GetThreadAtIndex (uint32_t idx) -{ - SBThread th = m_opaque_sp->GetThreadAtIndex (idx); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetThreadAtIndex(%d)", m_opaque_sp->GetQueueID(), idx); - return th; +SBThread SBQueue::GetThreadAtIndex(uint32_t idx) { + SBThread th = m_opaque_sp->GetThreadAtIndex(idx); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetThreadAtIndex(%d)", + m_opaque_sp->GetQueueID(), idx); + return th; } - -uint32_t -SBQueue::GetNumPendingItems () -{ - uint32_t pending_items = m_opaque_sp->GetNumPendingItems (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumPendingItems() == %d", m_opaque_sp->GetQueueID(), pending_items); - return pending_items; +uint32_t SBQueue::GetNumPendingItems() { + uint32_t pending_items = m_opaque_sp->GetNumPendingItems(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetNumPendingItems() == %d", + m_opaque_sp->GetQueueID(), pending_items); + return pending_items; } -SBQueueItem -SBQueue::GetPendingItemAtIndex (uint32_t idx) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetPendingItemAtIndex(%d)", m_opaque_sp->GetQueueID(), idx); - return m_opaque_sp->GetPendingItemAtIndex (idx); +SBQueueItem SBQueue::GetPendingItemAtIndex(uint32_t idx) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetPendingItemAtIndex(%d)", + m_opaque_sp->GetQueueID(), idx); + return m_opaque_sp->GetPendingItemAtIndex(idx); } -uint32_t -SBQueue::GetNumRunningItems () -{ - uint32_t running_items = m_opaque_sp->GetNumRunningItems (); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueue(0x%" PRIx64 ")::GetNumRunningItems() == %d", m_opaque_sp->GetQueueID(), running_items); - return running_items; +uint32_t SBQueue::GetNumRunningItems() { + uint32_t running_items = m_opaque_sp->GetNumRunningItems(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueue(0x%" PRIx64 ")::GetNumRunningItems() == %d", + m_opaque_sp->GetQueueID(), running_items); + return running_items; } -SBProcess -SBQueue::GetProcess () -{ - return m_opaque_sp->GetProcess(); -} +SBProcess SBQueue::GetProcess() { return m_opaque_sp->GetProcess(); } -lldb::QueueKind -SBQueue::GetKind () -{ - return m_opaque_sp->GetKind(); -} +lldb::QueueKind SBQueue::GetKind() { return m_opaque_sp->GetKind(); } diff --git a/lldb/source/API/SBQueueItem.cpp b/lldb/source/API/SBQueueItem.cpp index e7a199b9f0b..2e06bc89b3d 100644 --- a/lldb/source/API/SBQueueItem.cpp +++ b/lldb/source/API/SBQueueItem.cpp @@ -24,144 +24,111 @@ using namespace lldb_private; //---------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------- -SBQueueItem::SBQueueItem () : - m_queue_item_sp() -{ -} +SBQueueItem::SBQueueItem() : m_queue_item_sp() {} -SBQueueItem::SBQueueItem (const QueueItemSP& queue_item_sp) : - m_queue_item_sp (queue_item_sp) -{ -} +SBQueueItem::SBQueueItem(const QueueItemSP &queue_item_sp) + : m_queue_item_sp(queue_item_sp) {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -SBQueueItem::~SBQueueItem() -{ - m_queue_item_sp.reset(); -} - -bool -SBQueueItem::IsValid() const -{ - bool is_valid = m_queue_item_sp.get() != NULL; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueItem(%p)::IsValid() == %s", - static_cast(m_queue_item_sp.get()), - is_valid ? "true" : "false"); - return is_valid; +SBQueueItem::~SBQueueItem() { m_queue_item_sp.reset(); } + +bool SBQueueItem::IsValid() const { + bool is_valid = m_queue_item_sp.get() != NULL; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueueItem(%p)::IsValid() == %s", + static_cast(m_queue_item_sp.get()), + is_valid ? "true" : "false"); + return is_valid; } - -void -SBQueueItem::Clear () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf("SBQueueItem(%p)::Clear()", - static_cast(m_queue_item_sp.get())); - m_queue_item_sp.reset(); +void SBQueueItem::Clear() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBQueueItem(%p)::Clear()", + static_cast(m_queue_item_sp.get())); + m_queue_item_sp.reset(); } - -void -SBQueueItem::SetQueueItem (const QueueItemSP& queue_item_sp) -{ - m_queue_item_sp = queue_item_sp; +void SBQueueItem::SetQueueItem(const QueueItemSP &queue_item_sp) { + m_queue_item_sp = queue_item_sp; } - -lldb::QueueItemKind -SBQueueItem::GetKind () const -{ - QueueItemKind result = eQueueItemKindUnknown; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_queue_item_sp) - { - result = m_queue_item_sp->GetKind (); - } - if (log) - log->Printf("SBQueueItem(%p)::GetKind() == %d", - static_cast(m_queue_item_sp.get()), - static_cast(result)); - return result; +lldb::QueueItemKind SBQueueItem::GetKind() const { + QueueItemKind result = eQueueItemKindUnknown; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_queue_item_sp) { + result = m_queue_item_sp->GetKind(); + } + if (log) + log->Printf("SBQueueItem(%p)::GetKind() == %d", + static_cast(m_queue_item_sp.get()), + static_cast(result)); + return result; } -void -SBQueueItem::SetKind (lldb::QueueItemKind kind) -{ - if (m_queue_item_sp) - { - m_queue_item_sp->SetKind (kind); - } +void SBQueueItem::SetKind(lldb::QueueItemKind kind) { + if (m_queue_item_sp) { + m_queue_item_sp->SetKind(kind); + } } -SBAddress -SBQueueItem::GetAddress () const -{ - SBAddress result; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_queue_item_sp) - { - result.SetAddress (&m_queue_item_sp->GetAddress()); - } - if (log) - { - StreamString sstr; - const Address *addr = result.get(); - if (addr) - addr->Dump (&sstr, NULL, Address::DumpStyleModuleWithFileAddress, Address::DumpStyleInvalid, 4); - log->Printf ("SBQueueItem(%p)::GetAddress() == SBAddress(%p): %s", - static_cast(m_queue_item_sp.get()), - static_cast(result.get()), sstr.GetData()); - } - return result; +SBAddress SBQueueItem::GetAddress() const { + SBAddress result; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_queue_item_sp) { + result.SetAddress(&m_queue_item_sp->GetAddress()); + } + if (log) { + StreamString sstr; + const Address *addr = result.get(); + if (addr) + addr->Dump(&sstr, NULL, Address::DumpStyleModuleWithFileAddress, + Address::DumpStyleInvalid, 4); + log->Printf("SBQueueItem(%p)::GetAddress() == SBAddress(%p): %s", + static_cast(m_queue_item_sp.get()), + static_cast(result.get()), sstr.GetData()); + } + return result; } -void -SBQueueItem::SetAddress (SBAddress addr) -{ - if (m_queue_item_sp) - { - m_queue_item_sp->SetAddress (addr.ref()); - } +void SBQueueItem::SetAddress(SBAddress addr) { + if (m_queue_item_sp) { + m_queue_item_sp->SetAddress(addr.ref()); + } } -SBThread -SBQueueItem::GetExtendedBacktraceThread (const char *type) -{ - SBThread result; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (m_queue_item_sp) - { - ProcessSP process_sp = m_queue_item_sp->GetProcessSP(); - Process::StopLocker stop_locker; - if (process_sp && stop_locker.TryLock(&process_sp->GetRunLock())) - { - ThreadSP thread_sp; - ConstString type_const (type); - thread_sp = m_queue_item_sp->GetExtendedBacktraceThread (type_const); - if (thread_sp) - { - // Save this in the Process' ExtendedThreadList so a strong pointer retains the - // object - process_sp->GetExtendedThreadList().AddThread (thread_sp); - result.SetThread (thread_sp); - if (log) - { - const char *queue_name = thread_sp->GetQueueName(); - if (queue_name == NULL) - queue_name = ""; - log->Printf ("SBQueueItem(%p)::GetExtendedBacktraceThread() = new extended Thread created (%p) with queue_id 0x%" PRIx64 " queue name '%s'", - static_cast(m_queue_item_sp.get()), - static_cast(thread_sp.get()), - static_cast(thread_sp->GetQueueID()), - queue_name); - } - } +SBThread SBQueueItem::GetExtendedBacktraceThread(const char *type) { + SBThread result; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (m_queue_item_sp) { + ProcessSP process_sp = m_queue_item_sp->GetProcessSP(); + Process::StopLocker stop_locker; + if (process_sp && stop_locker.TryLock(&process_sp->GetRunLock())) { + ThreadSP thread_sp; + ConstString type_const(type); + thread_sp = m_queue_item_sp->GetExtendedBacktraceThread(type_const); + if (thread_sp) { + // Save this in the Process' ExtendedThreadList so a strong pointer + // retains the + // object + process_sp->GetExtendedThreadList().AddThread(thread_sp); + result.SetThread(thread_sp); + if (log) { + const char *queue_name = thread_sp->GetQueueName(); + if (queue_name == NULL) + queue_name = ""; + log->Printf( + "SBQueueItem(%p)::GetExtendedBacktraceThread() = new extended " + "Thread created (%p) with queue_id 0x%" PRIx64 " queue name '%s'", + static_cast(m_queue_item_sp.get()), + static_cast(thread_sp.get()), + static_cast(thread_sp->GetQueueID()), queue_name); } + } } - return result; + } + return result; } diff --git a/lldb/source/API/SBSection.cpp b/lldb/source/API/SBSection.cpp index 809eca60c68..77d5e25a99a 100644 --- a/lldb/source/API/SBSection.cpp +++ b/lldb/source/API/SBSection.cpp @@ -18,282 +18,209 @@ #include "lldb/Core/StreamString.h" #include "lldb/Symbol/ObjectFile.h" - using namespace lldb; using namespace lldb_private; +SBSection::SBSection() : m_opaque_wp() {} -SBSection::SBSection () : - m_opaque_wp () -{ -} - -SBSection::SBSection (const SBSection &rhs) : - m_opaque_wp (rhs.m_opaque_wp) -{ -} - - +SBSection::SBSection(const SBSection &rhs) : m_opaque_wp(rhs.m_opaque_wp) {} -SBSection::SBSection (const lldb::SectionSP §ion_sp) : - m_opaque_wp () // Don't init with section_sp otherwise this will throw if section_sp doesn't contain a valid Section * +SBSection::SBSection(const lldb::SectionSP §ion_sp) + : m_opaque_wp() // Don't init with section_sp otherwise this will throw if + // section_sp doesn't contain a valid Section * { - if (section_sp) - m_opaque_wp = section_sp; + if (section_sp) + m_opaque_wp = section_sp; } -const SBSection & -SBSection::operator = (const SBSection &rhs) -{ - m_opaque_wp = rhs.m_opaque_wp; - return *this; +const SBSection &SBSection::operator=(const SBSection &rhs) { + m_opaque_wp = rhs.m_opaque_wp; + return *this; } -SBSection::~SBSection () -{ -} +SBSection::~SBSection() {} -bool -SBSection::IsValid () const -{ - SectionSP section_sp (GetSP()); - return section_sp && section_sp->GetModule().get() != NULL; +bool SBSection::IsValid() const { + SectionSP section_sp(GetSP()); + return section_sp && section_sp->GetModule().get() != NULL; } -const char * -SBSection::GetName () -{ - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetName().GetCString(); - return NULL; +const char *SBSection::GetName() { + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetName().GetCString(); + return NULL; } -lldb::SBSection -SBSection::GetParent() -{ - lldb::SBSection sb_section; - SectionSP section_sp (GetSP()); - if (section_sp) - { - SectionSP parent_section_sp (section_sp->GetParent()); - if (parent_section_sp) - sb_section.SetSP(parent_section_sp); - } - return sb_section; +lldb::SBSection SBSection::GetParent() { + lldb::SBSection sb_section; + SectionSP section_sp(GetSP()); + if (section_sp) { + SectionSP parent_section_sp(section_sp->GetParent()); + if (parent_section_sp) + sb_section.SetSP(parent_section_sp); + } + return sb_section; } - -lldb::SBSection -SBSection::FindSubSection (const char *sect_name) -{ - lldb::SBSection sb_section; - if (sect_name) - { - SectionSP section_sp (GetSP()); - if (section_sp) - { - ConstString const_sect_name(sect_name); - sb_section.SetSP(section_sp->GetChildren ().FindSectionByName(const_sect_name)); - } +lldb::SBSection SBSection::FindSubSection(const char *sect_name) { + lldb::SBSection sb_section; + if (sect_name) { + SectionSP section_sp(GetSP()); + if (section_sp) { + ConstString const_sect_name(sect_name); + sb_section.SetSP( + section_sp->GetChildren().FindSectionByName(const_sect_name)); } - return sb_section; -} - -size_t -SBSection::GetNumSubSections () -{ - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetChildren ().GetSize(); - return 0; -} - -lldb::SBSection -SBSection::GetSubSectionAtIndex (size_t idx) -{ - lldb::SBSection sb_section; - SectionSP section_sp (GetSP()); - if (section_sp) - sb_section.SetSP (section_sp->GetChildren ().GetSectionAtIndex(idx)); - return sb_section; + } + return sb_section; } -lldb::SectionSP -SBSection::GetSP() const -{ - return m_opaque_wp.lock(); +size_t SBSection::GetNumSubSections() { + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetChildren().GetSize(); + return 0; } -void -SBSection::SetSP(const lldb::SectionSP §ion_sp) -{ - m_opaque_wp = section_sp; +lldb::SBSection SBSection::GetSubSectionAtIndex(size_t idx) { + lldb::SBSection sb_section; + SectionSP section_sp(GetSP()); + if (section_sp) + sb_section.SetSP(section_sp->GetChildren().GetSectionAtIndex(idx)); + return sb_section; } -lldb::addr_t -SBSection::GetFileAddress () -{ - lldb::addr_t file_addr = LLDB_INVALID_ADDRESS; - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetFileAddress(); - return file_addr; -} +lldb::SectionSP SBSection::GetSP() const { return m_opaque_wp.lock(); } -lldb::addr_t -SBSection::GetLoadAddress (lldb::SBTarget &sb_target) -{ - TargetSP target_sp(sb_target.GetSP()); - if (target_sp) - { - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetLoadBaseAddress(target_sp.get()); - } - return LLDB_INVALID_ADDRESS; - +void SBSection::SetSP(const lldb::SectionSP §ion_sp) { + m_opaque_wp = section_sp; } - - -lldb::addr_t -SBSection::GetByteSize () -{ - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetByteSize(); - return 0; +lldb::addr_t SBSection::GetFileAddress() { + lldb::addr_t file_addr = LLDB_INVALID_ADDRESS; + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetFileAddress(); + return file_addr; } -uint64_t -SBSection::GetFileOffset () -{ - SectionSP section_sp (GetSP()); +lldb::addr_t SBSection::GetLoadAddress(lldb::SBTarget &sb_target) { + TargetSP target_sp(sb_target.GetSP()); + if (target_sp) { + SectionSP section_sp(GetSP()); if (section_sp) - { - ModuleSP module_sp (section_sp->GetModule()); - if (module_sp) - { - ObjectFile *objfile = module_sp->GetObjectFile(); - if (objfile) - return objfile->GetFileOffset() + section_sp->GetFileOffset(); - } + return section_sp->GetLoadBaseAddress(target_sp.get()); + } + return LLDB_INVALID_ADDRESS; +} + +lldb::addr_t SBSection::GetByteSize() { + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetByteSize(); + return 0; +} + +uint64_t SBSection::GetFileOffset() { + SectionSP section_sp(GetSP()); + if (section_sp) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ObjectFile *objfile = module_sp->GetObjectFile(); + if (objfile) + return objfile->GetFileOffset() + section_sp->GetFileOffset(); } - return UINT64_MAX; -} - -uint64_t -SBSection::GetFileByteSize () -{ - SectionSP section_sp (GetSP()); - if (section_sp) - return section_sp->GetFileSize(); - return 0; -} - -SBData -SBSection::GetSectionData () -{ - return GetSectionData (0, UINT64_MAX); -} - -SBData -SBSection::GetSectionData (uint64_t offset, uint64_t size) -{ - SBData sb_data; - SectionSP section_sp (GetSP()); - if (section_sp) - { - const uint64_t sect_file_size = section_sp->GetFileSize(); - if (sect_file_size > 0) - { - ModuleSP module_sp (section_sp->GetModule()); - if (module_sp) - { - ObjectFile *objfile = module_sp->GetObjectFile(); - if (objfile) - { - const uint64_t sect_file_offset = objfile->GetFileOffset() + section_sp->GetFileOffset(); - const uint64_t file_offset = sect_file_offset + offset; - uint64_t file_size = size; - if (file_size == UINT64_MAX) - { - file_size = section_sp->GetByteSize(); - if (file_size > offset) - file_size -= offset; - else - file_size = 0; - } - DataBufferSP data_buffer_sp (objfile->GetFileSpec().ReadFileContents (file_offset, file_size)); - if (data_buffer_sp && data_buffer_sp->GetByteSize() > 0) - { - DataExtractorSP data_extractor_sp (new DataExtractor (data_buffer_sp, - objfile->GetByteOrder(), - objfile->GetAddressByteSize())); - - sb_data.SetOpaque (data_extractor_sp); - } - } - } + } + return UINT64_MAX; +} + +uint64_t SBSection::GetFileByteSize() { + SectionSP section_sp(GetSP()); + if (section_sp) + return section_sp->GetFileSize(); + return 0; +} + +SBData SBSection::GetSectionData() { return GetSectionData(0, UINT64_MAX); } + +SBData SBSection::GetSectionData(uint64_t offset, uint64_t size) { + SBData sb_data; + SectionSP section_sp(GetSP()); + if (section_sp) { + const uint64_t sect_file_size = section_sp->GetFileSize(); + if (sect_file_size > 0) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ObjectFile *objfile = module_sp->GetObjectFile(); + if (objfile) { + const uint64_t sect_file_offset = + objfile->GetFileOffset() + section_sp->GetFileOffset(); + const uint64_t file_offset = sect_file_offset + offset; + uint64_t file_size = size; + if (file_size == UINT64_MAX) { + file_size = section_sp->GetByteSize(); + if (file_size > offset) + file_size -= offset; + else + file_size = 0; + } + DataBufferSP data_buffer_sp( + objfile->GetFileSpec().ReadFileContents(file_offset, file_size)); + if (data_buffer_sp && data_buffer_sp->GetByteSize() > 0) { + DataExtractorSP data_extractor_sp( + new DataExtractor(data_buffer_sp, objfile->GetByteOrder(), + objfile->GetAddressByteSize())); + + sb_data.SetOpaque(data_extractor_sp); + } } + } } - return sb_data; + } + return sb_data; } -SectionType -SBSection::GetSectionType () -{ - SectionSP section_sp (GetSP()); - if (section_sp.get()) - return section_sp->GetType(); - return eSectionTypeInvalid; +SectionType SBSection::GetSectionType() { + SectionSP section_sp(GetSP()); + if (section_sp.get()) + return section_sp->GetType(); + return eSectionTypeInvalid; } -uint32_t -SBSection::GetTargetByteSize () -{ - SectionSP section_sp (GetSP()); - if (section_sp.get()) - return section_sp->GetTargetByteSize(); - return 0; +uint32_t SBSection::GetTargetByteSize() { + SectionSP section_sp(GetSP()); + if (section_sp.get()) + return section_sp->GetTargetByteSize(); + return 0; } -bool -SBSection::operator == (const SBSection &rhs) -{ - SectionSP lhs_section_sp (GetSP()); - SectionSP rhs_section_sp (rhs.GetSP()); - if (lhs_section_sp && rhs_section_sp) - return lhs_section_sp == rhs_section_sp; - return false; +bool SBSection::operator==(const SBSection &rhs) { + SectionSP lhs_section_sp(GetSP()); + SectionSP rhs_section_sp(rhs.GetSP()); + if (lhs_section_sp && rhs_section_sp) + return lhs_section_sp == rhs_section_sp; + return false; } -bool -SBSection::operator != (const SBSection &rhs) -{ - SectionSP lhs_section_sp (GetSP()); - SectionSP rhs_section_sp (rhs.GetSP()); - return lhs_section_sp != rhs_section_sp; +bool SBSection::operator!=(const SBSection &rhs) { + SectionSP lhs_section_sp(GetSP()); + SectionSP rhs_section_sp(rhs.GetSP()); + return lhs_section_sp != rhs_section_sp; } -bool -SBSection::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBSection::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - SectionSP section_sp (GetSP()); - if (section_sp) - { - const addr_t file_addr = section_sp->GetFileAddress(); - strm.Printf ("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") ", file_addr, file_addr + section_sp->GetByteSize()); - section_sp->DumpName(&strm); - } - else - { - strm.PutCString ("No value"); - } + SectionSP section_sp(GetSP()); + if (section_sp) { + const addr_t file_addr = section_sp->GetFileAddress(); + strm.Printf("[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") ", file_addr, + file_addr + section_sp->GetByteSize()); + section_sp->DumpName(&strm); + } else { + strm.PutCString("No value"); + } - return true; + return true; } - diff --git a/lldb/source/API/SBSourceManager.cpp b/lldb/source/API/SBSourceManager.cpp index 8196b91d00b..69220760c9f 100644 --- a/lldb/source/API/SBSourceManager.cpp +++ b/lldb/source/API/SBSourceManager.cpp @@ -7,138 +7,99 @@ // //===----------------------------------------------------------------------===// -#include "lldb/API/SBDebugger.h" #include "lldb/API/SBSourceManager.h" -#include "lldb/API/SBTarget.h" +#include "lldb/API/SBDebugger.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBTarget.h" #include "lldb/API/SBFileSpec.h" #include "lldb/Core/Debugger.h" +#include "lldb/Core/SourceManager.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Core/SourceManager.h" #include "lldb/Target/Target.h" -namespace lldb_private -{ - class SourceManagerImpl - { - public: - SourceManagerImpl (const lldb::DebuggerSP &debugger_sp) : - m_debugger_wp (debugger_sp), - m_target_wp () - { - } - - SourceManagerImpl (const lldb::TargetSP &target_sp) : - m_debugger_wp (), - m_target_wp (target_sp) - { - } - - SourceManagerImpl (const SourceManagerImpl &rhs) - { - if (&rhs == this) - return; - m_debugger_wp = rhs.m_debugger_wp; - m_target_wp = rhs.m_target_wp; - } - - size_t - DisplaySourceLinesWithLineNumbers (const lldb_private::FileSpec &file, +namespace lldb_private { +class SourceManagerImpl { +public: + SourceManagerImpl(const lldb::DebuggerSP &debugger_sp) + : m_debugger_wp(debugger_sp), m_target_wp() {} + + SourceManagerImpl(const lldb::TargetSP &target_sp) + : m_debugger_wp(), m_target_wp(target_sp) {} + + SourceManagerImpl(const SourceManagerImpl &rhs) { + if (&rhs == this) + return; + m_debugger_wp = rhs.m_debugger_wp; + m_target_wp = rhs.m_target_wp; + } + + size_t DisplaySourceLinesWithLineNumbers(const lldb_private::FileSpec &file, uint32_t line, uint32_t context_before, uint32_t context_after, const char *current_line_cstr, - lldb_private::Stream *s) - { - if (!file) - return 0; - - lldb::TargetSP target_sp (m_target_wp.lock()); - if (target_sp) - { - return target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file, - line, - context_before, - context_after, - current_line_cstr, - s); - } - else - { - lldb::DebuggerSP debugger_sp (m_debugger_wp.lock()); - if (debugger_sp) - { - return debugger_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file, - line, - context_before, - context_after, - current_line_cstr, - s); - } - } - return 0; - } - - private: - lldb::DebuggerWP m_debugger_wp; - lldb::TargetWP m_target_wp; - - }; + lldb_private::Stream *s) { + if (!file) + return 0; + + lldb::TargetSP target_sp(m_target_wp.lock()); + if (target_sp) { + return target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers( + file, line, context_before, context_after, current_line_cstr, s); + } else { + lldb::DebuggerSP debugger_sp(m_debugger_wp.lock()); + if (debugger_sp) { + return debugger_sp->GetSourceManager() + .DisplaySourceLinesWithLineNumbers(file, line, context_before, + context_after, current_line_cstr, + s); + } + } + return 0; + } + +private: + lldb::DebuggerWP m_debugger_wp; + lldb::TargetWP m_target_wp; +}; } using namespace lldb; using namespace lldb_private; -SBSourceManager::SBSourceManager (const SBDebugger &debugger) -{ - m_opaque_ap.reset(new SourceManagerImpl (debugger.get_sp())); +SBSourceManager::SBSourceManager(const SBDebugger &debugger) { + m_opaque_ap.reset(new SourceManagerImpl(debugger.get_sp())); } -SBSourceManager::SBSourceManager (const SBTarget &target) -{ - m_opaque_ap.reset(new SourceManagerImpl (target.GetSP())); +SBSourceManager::SBSourceManager(const SBTarget &target) { + m_opaque_ap.reset(new SourceManagerImpl(target.GetSP())); } -SBSourceManager::SBSourceManager (const SBSourceManager &rhs) -{ - if (&rhs == this) - return; - - m_opaque_ap.reset(new SourceManagerImpl (*(rhs.m_opaque_ap.get()))); -} +SBSourceManager::SBSourceManager(const SBSourceManager &rhs) { + if (&rhs == this) + return; -const lldb::SBSourceManager & -SBSourceManager::operator = (const lldb::SBSourceManager &rhs) -{ - m_opaque_ap.reset (new SourceManagerImpl (*(rhs.m_opaque_ap.get()))); - return *this; + m_opaque_ap.reset(new SourceManagerImpl(*(rhs.m_opaque_ap.get()))); } -SBSourceManager::~SBSourceManager() -{ +const lldb::SBSourceManager &SBSourceManager:: +operator=(const lldb::SBSourceManager &rhs) { + m_opaque_ap.reset(new SourceManagerImpl(*(rhs.m_opaque_ap.get()))); + return *this; } -size_t -SBSourceManager::DisplaySourceLinesWithLineNumbers -( - const SBFileSpec &file, - uint32_t line, - uint32_t context_before, - uint32_t context_after, - const char *current_line_cstr, - SBStream &s -) -{ - if (m_opaque_ap.get() == NULL) - return 0; - - return m_opaque_ap->DisplaySourceLinesWithLineNumbers (file.ref(), - line, - context_before, - context_after, - current_line_cstr, - s.get()); +SBSourceManager::~SBSourceManager() {} + +size_t SBSourceManager::DisplaySourceLinesWithLineNumbers( + const SBFileSpec &file, uint32_t line, uint32_t context_before, + uint32_t context_after, const char *current_line_cstr, SBStream &s) { + if (m_opaque_ap.get() == NULL) + return 0; + + return m_opaque_ap->DisplaySourceLinesWithLineNumbers( + file.ref(), line, context_before, context_after, current_line_cstr, + s.get()); } diff --git a/lldb/source/API/SBStream.cpp b/lldb/source/API/SBStream.cpp index f3be3be6a10..0ade453f845 100644 --- a/lldb/source/API/SBStream.cpp +++ b/lldb/source/API/SBStream.cpp @@ -17,186 +17,141 @@ using namespace lldb; using namespace lldb_private; -SBStream::SBStream () : - m_opaque_ap (new StreamString()), - m_is_file (false) -{ -} +SBStream::SBStream() : m_opaque_ap(new StreamString()), m_is_file(false) {} -SBStream::SBStream (SBStream &&rhs) : - m_opaque_ap (std::move(rhs.m_opaque_ap)), - m_is_file (rhs.m_is_file) -{ -} +SBStream::SBStream(SBStream &&rhs) + : m_opaque_ap(std::move(rhs.m_opaque_ap)), m_is_file(rhs.m_is_file) {} +SBStream::~SBStream() {} -SBStream::~SBStream () -{ -} - -bool -SBStream::IsValid() const -{ - return (m_opaque_ap.get() != NULL); -} +bool SBStream::IsValid() const { return (m_opaque_ap.get() != NULL); } // If this stream is not redirected to a file, it will maintain a local // cache for the stream data which can be accessed using this accessor. -const char * -SBStream::GetData () -{ - if (m_is_file || m_opaque_ap.get() == NULL) - return NULL; - - return static_cast(m_opaque_ap.get())->GetData(); +const char *SBStream::GetData() { + if (m_is_file || m_opaque_ap.get() == NULL) + return NULL; + + return static_cast(m_opaque_ap.get())->GetData(); } // If this stream is not redirected to a file, it will maintain a local -// cache for the stream output whose length can be accessed using this +// cache for the stream output whose length can be accessed using this // accessor. -size_t -SBStream::GetSize() -{ - if (m_is_file || m_opaque_ap.get() == NULL) - return 0; - - return static_cast(m_opaque_ap.get())->GetSize(); -} +size_t SBStream::GetSize() { + if (m_is_file || m_opaque_ap.get() == NULL) + return 0; -void -SBStream::Printf (const char *format, ...) -{ - if (!format) - return; - va_list args; - va_start (args, format); - ref().PrintfVarArg (format, args); - va_end (args); + return static_cast(m_opaque_ap.get())->GetSize(); } -void -SBStream::RedirectToFile (const char *path, bool append) -{ - if (path == nullptr) - return; - - std::string local_data; - if (m_opaque_ap.get()) - { - // See if we have any locally backed data. If so, copy it so we can then - // redirect it to the file so we don't lose the data - if (!m_is_file) - local_data.swap(static_cast(m_opaque_ap.get())->GetString()); - } - StreamFile *stream_file = new StreamFile; - uint32_t open_options = File::eOpenOptionWrite | File::eOpenOptionCanCreate; - if (append) - open_options |= File::eOpenOptionAppend; - else - open_options |= File::eOpenOptionTruncate; - stream_file->GetFile().Open (path, open_options, lldb::eFilePermissionsFileDefault); - - m_opaque_ap.reset (stream_file); - - if (m_opaque_ap.get()) - { - m_is_file = true; - - // If we had any data locally in our StreamString, then pass that along to - // the to new file we are redirecting to. - if (!local_data.empty()) - m_opaque_ap->Write (&local_data[0], local_data.size()); - } - else - m_is_file = false; +void SBStream::Printf(const char *format, ...) { + if (!format) + return; + va_list args; + va_start(args, format); + ref().PrintfVarArg(format, args); + va_end(args); } -void -SBStream::RedirectToFileHandle (FILE *fh, bool transfer_fh_ownership) -{ - if (fh == nullptr) - return; - - std::string local_data; - if (m_opaque_ap.get()) - { - // See if we have any locally backed data. If so, copy it so we can then - // redirect it to the file so we don't lose the data - if (!m_is_file) - local_data.swap(static_cast(m_opaque_ap.get())->GetString()); - } - m_opaque_ap.reset (new StreamFile (fh, transfer_fh_ownership)); - - if (m_opaque_ap.get()) - { - m_is_file = true; - - // If we had any data locally in our StreamString, then pass that along to - // the to new file we are redirecting to. - if (!local_data.empty()) - m_opaque_ap->Write (&local_data[0], local_data.size()); - } - else - m_is_file = false; +void SBStream::RedirectToFile(const char *path, bool append) { + if (path == nullptr) + return; + + std::string local_data; + if (m_opaque_ap.get()) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data.swap( + static_cast(m_opaque_ap.get())->GetString()); + } + StreamFile *stream_file = new StreamFile; + uint32_t open_options = File::eOpenOptionWrite | File::eOpenOptionCanCreate; + if (append) + open_options |= File::eOpenOptionAppend; + else + open_options |= File::eOpenOptionTruncate; + stream_file->GetFile().Open(path, open_options, + lldb::eFilePermissionsFileDefault); + + m_opaque_ap.reset(stream_file); + + if (m_opaque_ap.get()) { + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_ap->Write(&local_data[0], local_data.size()); + } else + m_is_file = false; } -void -SBStream::RedirectToFileDescriptor (int fd, bool transfer_fh_ownership) -{ - std::string local_data; - if (m_opaque_ap.get()) - { - // See if we have any locally backed data. If so, copy it so we can then - // redirect it to the file so we don't lose the data - if (!m_is_file) - local_data.swap(static_cast(m_opaque_ap.get())->GetString()); - } - - m_opaque_ap.reset (new StreamFile (::fdopen (fd, "w"), transfer_fh_ownership)); - if (m_opaque_ap.get()) - { - m_is_file = true; - - // If we had any data locally in our StreamString, then pass that along to - // the to new file we are redirecting to. - if (!local_data.empty()) - m_opaque_ap->Write (&local_data[0], local_data.size()); - } - else - m_is_file = false; - +void SBStream::RedirectToFileHandle(FILE *fh, bool transfer_fh_ownership) { + if (fh == nullptr) + return; + + std::string local_data; + if (m_opaque_ap.get()) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data.swap( + static_cast(m_opaque_ap.get())->GetString()); + } + m_opaque_ap.reset(new StreamFile(fh, transfer_fh_ownership)); + + if (m_opaque_ap.get()) { + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_ap->Write(&local_data[0], local_data.size()); + } else + m_is_file = false; } -lldb_private::Stream * -SBStream::operator->() -{ - return m_opaque_ap.get(); +void SBStream::RedirectToFileDescriptor(int fd, bool transfer_fh_ownership) { + std::string local_data; + if (m_opaque_ap.get()) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (!m_is_file) + local_data.swap( + static_cast(m_opaque_ap.get())->GetString()); + } + + m_opaque_ap.reset(new StreamFile(::fdopen(fd, "w"), transfer_fh_ownership)); + if (m_opaque_ap.get()) { + m_is_file = true; + + // If we had any data locally in our StreamString, then pass that along to + // the to new file we are redirecting to. + if (!local_data.empty()) + m_opaque_ap->Write(&local_data[0], local_data.size()); + } else + m_is_file = false; } -lldb_private::Stream * -SBStream::get() -{ - return m_opaque_ap.get(); -} +lldb_private::Stream *SBStream::operator->() { return m_opaque_ap.get(); } -lldb_private::Stream & -SBStream::ref() -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new StreamString()); - return *m_opaque_ap.get(); +lldb_private::Stream *SBStream::get() { return m_opaque_ap.get(); } + +lldb_private::Stream &SBStream::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new StreamString()); + return *m_opaque_ap.get(); } -void -SBStream::Clear () -{ - if (m_opaque_ap.get()) - { - // See if we have any locally backed data. If so, copy it so we can then - // redirect it to the file so we don't lose the data - if (m_is_file) - m_opaque_ap.reset(); - else - static_cast(m_opaque_ap.get())->GetString().clear(); - } +void SBStream::Clear() { + if (m_opaque_ap.get()) { + // See if we have any locally backed data. If so, copy it so we can then + // redirect it to the file so we don't lose the data + if (m_is_file) + m_opaque_ap.reset(); + else + static_cast(m_opaque_ap.get())->GetString().clear(); + } } diff --git a/lldb/source/API/SBStringList.cpp b/lldb/source/API/SBStringList.cpp index f469bc4336f..34465f76f61 100644 --- a/lldb/source/API/SBStringList.cpp +++ b/lldb/source/API/SBStringList.cpp @@ -14,133 +14,90 @@ using namespace lldb; using namespace lldb_private; -SBStringList::SBStringList () : - m_opaque_ap () -{ -} +SBStringList::SBStringList() : m_opaque_ap() {} -SBStringList::SBStringList (const lldb_private::StringList *lldb_strings_ptr) : - m_opaque_ap () -{ - if (lldb_strings_ptr) - m_opaque_ap.reset (new lldb_private::StringList (*lldb_strings_ptr)); +SBStringList::SBStringList(const lldb_private::StringList *lldb_strings_ptr) + : m_opaque_ap() { + if (lldb_strings_ptr) + m_opaque_ap.reset(new lldb_private::StringList(*lldb_strings_ptr)); } -SBStringList::SBStringList (const SBStringList &rhs) : - m_opaque_ap () -{ - if (rhs.IsValid()) - m_opaque_ap.reset (new lldb_private::StringList(*rhs)); +SBStringList::SBStringList(const SBStringList &rhs) : m_opaque_ap() { + if (rhs.IsValid()) + m_opaque_ap.reset(new lldb_private::StringList(*rhs)); } - -const SBStringList & -SBStringList::operator = (const SBStringList &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_ap.reset(new lldb_private::StringList(*rhs)); - else - m_opaque_ap.reset(); - } - return *this; -} - -SBStringList::~SBStringList () -{ +const SBStringList &SBStringList::operator=(const SBStringList &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_ap.reset(new lldb_private::StringList(*rhs)); + else + m_opaque_ap.reset(); + } + return *this; } -const lldb_private::StringList * -SBStringList::operator->() const -{ - return m_opaque_ap.get(); -} +SBStringList::~SBStringList() {} -const lldb_private::StringList & -SBStringList::operator*() const -{ - return *m_opaque_ap; +const lldb_private::StringList *SBStringList::operator->() const { + return m_opaque_ap.get(); } -bool -SBStringList::IsValid() const -{ - return (m_opaque_ap.get() != NULL); +const lldb_private::StringList &SBStringList::operator*() const { + return *m_opaque_ap; } -void -SBStringList::AppendString (const char *str) -{ - if (str != NULL) - { - if (IsValid()) - m_opaque_ap->AppendString (str); - else - m_opaque_ap.reset (new lldb_private::StringList (str)); - } +bool SBStringList::IsValid() const { return (m_opaque_ap.get() != NULL); } +void SBStringList::AppendString(const char *str) { + if (str != NULL) { + if (IsValid()) + m_opaque_ap->AppendString(str); + else + m_opaque_ap.reset(new lldb_private::StringList(str)); + } } -void -SBStringList::AppendList (const char **strv, int strc) -{ - if ((strv != NULL) - && (strc > 0)) - { - if (IsValid()) - m_opaque_ap->AppendList (strv, strc); - else - m_opaque_ap.reset (new lldb_private::StringList (strv, strc)); - } +void SBStringList::AppendList(const char **strv, int strc) { + if ((strv != NULL) && (strc > 0)) { + if (IsValid()) + m_opaque_ap->AppendList(strv, strc); + else + m_opaque_ap.reset(new lldb_private::StringList(strv, strc)); + } } -void -SBStringList::AppendList (const SBStringList &strings) -{ - if (strings.IsValid()) - { - if (! IsValid()) - m_opaque_ap.reset (new lldb_private::StringList()); - m_opaque_ap->AppendList (*(strings.m_opaque_ap)); - } +void SBStringList::AppendList(const SBStringList &strings) { + if (strings.IsValid()) { + if (!IsValid()) + m_opaque_ap.reset(new lldb_private::StringList()); + m_opaque_ap->AppendList(*(strings.m_opaque_ap)); + } } -uint32_t -SBStringList::GetSize () const -{ - if (IsValid()) - { - return m_opaque_ap->GetSize(); - } - return 0; +uint32_t SBStringList::GetSize() const { + if (IsValid()) { + return m_opaque_ap->GetSize(); + } + return 0; } -const char * -SBStringList::GetStringAtIndex (size_t idx) -{ - if (IsValid()) - { - return m_opaque_ap->GetStringAtIndex (idx); - } - return NULL; +const char *SBStringList::GetStringAtIndex(size_t idx) { + if (IsValid()) { + return m_opaque_ap->GetStringAtIndex(idx); + } + return NULL; } -const char * -SBStringList::GetStringAtIndex (size_t idx) const -{ - if (IsValid()) - { - return m_opaque_ap->GetStringAtIndex (idx); - } - return NULL; +const char *SBStringList::GetStringAtIndex(size_t idx) const { + if (IsValid()) { + return m_opaque_ap->GetStringAtIndex(idx); + } + return NULL; } -void -SBStringList::Clear () -{ - if (IsValid()) - { - m_opaque_ap->Clear(); - } +void SBStringList::Clear() { + if (IsValid()) { + m_opaque_ap->Clear(); + } } diff --git a/lldb/source/API/SBStructuredData.cpp b/lldb/source/API/SBStructuredData.cpp index 5e4417484f0..3c04b3bbba9 100644 --- a/lldb/source/API/SBStructuredData.cpp +++ b/lldb/source/API/SBStructuredData.cpp @@ -19,147 +19,101 @@ using namespace lldb; using namespace lldb_private; -#pragma mark -- +#pragma mark-- #pragma mark Impl -class SBStructuredData::Impl -{ +class SBStructuredData::Impl { public: + Impl() : m_plugin_wp(), m_data_sp() {} - Impl() : - m_plugin_wp(), - m_data_sp() - { - } + Impl(const Impl &rhs) = default; - Impl(const Impl &rhs) = default; + Impl(const EventSP &event_sp) + : m_plugin_wp( + EventDataStructuredData::GetPluginFromEvent(event_sp.get())), + m_data_sp(EventDataStructuredData::GetObjectFromEvent(event_sp.get())) { + } - Impl(const EventSP &event_sp) : - m_plugin_wp(EventDataStructuredData::GetPluginFromEvent(event_sp.get())), - m_data_sp(EventDataStructuredData::GetObjectFromEvent(event_sp.get())) - { - } + ~Impl() = default; - ~Impl() = default; + Impl &operator=(const Impl &rhs) = default; - Impl& - operator =(const Impl &rhs) = default; + bool IsValid() const { return m_data_sp.get() != nullptr; } - bool - IsValid() const - { - return m_data_sp.get() != nullptr; - } + void Clear() { + m_plugin_wp.reset(); + m_data_sp.reset(); + } + + SBError GetAsJSON(lldb::SBStream &stream) const { + SBError sb_error; - void - Clear() - { - m_plugin_wp.reset(); - m_data_sp.reset(); + if (!m_data_sp) { + sb_error.SetErrorString("No structured data."); + return sb_error; } - SBError - GetAsJSON(lldb::SBStream &stream) const - { - SBError sb_error; + m_data_sp->Dump(stream.ref()); + return sb_error; + } - if (!m_data_sp) - { - sb_error.SetErrorString("No structured data."); - return sb_error; - } + lldb::SBError GetDescription(lldb::SBStream &stream) const { + SBError sb_error; - m_data_sp->Dump(stream.ref()); - return sb_error; + if (!m_data_sp) { + sb_error.SetErrorString("Cannot pretty print structured data: " + "no data to print."); + return sb_error; } - lldb::SBError - GetDescription(lldb::SBStream &stream) const - { - SBError sb_error; - - if (!m_data_sp) - { - sb_error.SetErrorString("Cannot pretty print structured data: " - "no data to print."); - return sb_error; - } - - // Grab the plugin. - auto plugin_sp = StructuredDataPluginSP(m_plugin_wp); - if (!plugin_sp) - { - sb_error.SetErrorString("Cannot pretty print structured data: " - "plugin doesn't exist."); - return sb_error; - } - - // Get the data's description. - auto error = plugin_sp->GetDescription(m_data_sp, stream.ref()); - if (!error.Success()) - sb_error.SetError(error); - - return sb_error; + // Grab the plugin. + auto plugin_sp = StructuredDataPluginSP(m_plugin_wp); + if (!plugin_sp) { + sb_error.SetErrorString("Cannot pretty print structured data: " + "plugin doesn't exist."); + return sb_error; } -private: + // Get the data's description. + auto error = plugin_sp->GetDescription(m_data_sp, stream.ref()); + if (!error.Success()) + sb_error.SetError(error); - StructuredDataPluginWP m_plugin_wp; - StructuredData::ObjectSP m_data_sp; + return sb_error; + } +private: + StructuredDataPluginWP m_plugin_wp; + StructuredData::ObjectSP m_data_sp; }; -#pragma mark -- +#pragma mark-- #pragma mark SBStructuredData +SBStructuredData::SBStructuredData() : m_impl_up(new Impl()) {} -SBStructuredData::SBStructuredData() : - m_impl_up(new Impl()) -{ -} - -SBStructuredData::SBStructuredData(const lldb::SBStructuredData &rhs) : - m_impl_up(new Impl(*rhs.m_impl_up.get())) -{ -} +SBStructuredData::SBStructuredData(const lldb::SBStructuredData &rhs) + : m_impl_up(new Impl(*rhs.m_impl_up.get())) {} -SBStructuredData::SBStructuredData(const lldb::EventSP &event_sp) : - m_impl_up(new Impl(event_sp)) -{ -} +SBStructuredData::SBStructuredData(const lldb::EventSP &event_sp) + : m_impl_up(new Impl(event_sp)) {} -SBStructuredData::~SBStructuredData() -{ -} +SBStructuredData::~SBStructuredData() {} -SBStructuredData & -SBStructuredData::operator =(const lldb::SBStructuredData &rhs) -{ - *m_impl_up = *rhs.m_impl_up; - return *this; +SBStructuredData &SBStructuredData:: +operator=(const lldb::SBStructuredData &rhs) { + *m_impl_up = *rhs.m_impl_up; + return *this; } -bool -SBStructuredData::IsValid() const -{ - return m_impl_up->IsValid(); -} +bool SBStructuredData::IsValid() const { return m_impl_up->IsValid(); } -void -SBStructuredData::Clear() -{ - m_impl_up->Clear(); -} +void SBStructuredData::Clear() { m_impl_up->Clear(); } -SBError -SBStructuredData::GetAsJSON(lldb::SBStream &stream) const -{ - return m_impl_up->GetAsJSON(stream); +SBError SBStructuredData::GetAsJSON(lldb::SBStream &stream) const { + return m_impl_up->GetAsJSON(stream); } -lldb::SBError -SBStructuredData::GetDescription(lldb::SBStream &stream) const -{ - return m_impl_up->GetDescription(stream); +lldb::SBError SBStructuredData::GetDescription(lldb::SBStream &stream) const { + return m_impl_up->GetDescription(stream); } - diff --git a/lldb/source/API/SBSymbol.cpp b/lldb/source/API/SBSymbol.cpp index 0dbed1238b8..a4cc5252b1c 100644 --- a/lldb/source/API/SBSymbol.cpp +++ b/lldb/source/API/SBSymbol.cpp @@ -19,225 +19,159 @@ using namespace lldb; using namespace lldb_private; -SBSymbol::SBSymbol () : - m_opaque_ptr (NULL) -{ -} +SBSymbol::SBSymbol() : m_opaque_ptr(NULL) {} -SBSymbol::SBSymbol (lldb_private::Symbol *lldb_object_ptr) : - m_opaque_ptr (lldb_object_ptr) -{ -} +SBSymbol::SBSymbol(lldb_private::Symbol *lldb_object_ptr) + : m_opaque_ptr(lldb_object_ptr) {} -SBSymbol::SBSymbol (const lldb::SBSymbol &rhs) : - m_opaque_ptr (rhs.m_opaque_ptr) -{ -} +SBSymbol::SBSymbol(const lldb::SBSymbol &rhs) + : m_opaque_ptr(rhs.m_opaque_ptr) {} -const SBSymbol & -SBSymbol::operator = (const SBSymbol &rhs) -{ - m_opaque_ptr = rhs.m_opaque_ptr; - return *this; +const SBSymbol &SBSymbol::operator=(const SBSymbol &rhs) { + m_opaque_ptr = rhs.m_opaque_ptr; + return *this; } -SBSymbol::~SBSymbol () -{ - m_opaque_ptr = NULL; -} +SBSymbol::~SBSymbol() { m_opaque_ptr = NULL; } -void -SBSymbol::SetSymbol (lldb_private::Symbol *lldb_object_ptr) -{ - m_opaque_ptr = lldb_object_ptr; +void SBSymbol::SetSymbol(lldb_private::Symbol *lldb_object_ptr) { + m_opaque_ptr = lldb_object_ptr; } -bool -SBSymbol::IsValid () const -{ - return m_opaque_ptr != NULL; +bool SBSymbol::IsValid() const { return m_opaque_ptr != NULL; } + +const char *SBSymbol::GetName() const { + const char *name = NULL; + if (m_opaque_ptr) + name = m_opaque_ptr->GetName().AsCString(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBSymbol(%p)::GetName () => \"%s\"", + static_cast(m_opaque_ptr), name ? name : ""); + return name; } -const char * -SBSymbol::GetName() const -{ - const char *name = NULL; - if (m_opaque_ptr) - name = m_opaque_ptr->GetName().AsCString(); +const char *SBSymbol::GetDisplayName() const { + const char *name = NULL; + if (m_opaque_ptr) + name = m_opaque_ptr->GetMangled() + .GetDisplayDemangledName(m_opaque_ptr->GetLanguage()) + .AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBSymbol(%p)::GetName () => \"%s\"", - static_cast(m_opaque_ptr), name ? name : ""); - return name; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBSymbol(%p)::GetDisplayName () => \"%s\"", + static_cast(m_opaque_ptr), name ? name : ""); + return name; } -const char * -SBSymbol::GetDisplayName() const -{ - const char *name = NULL; - if (m_opaque_ptr) - name = m_opaque_ptr->GetMangled().GetDisplayDemangledName(m_opaque_ptr->GetLanguage()).AsCString(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBSymbol(%p)::GetDisplayName () => \"%s\"", - static_cast(m_opaque_ptr), name ? name : ""); - return name; +const char *SBSymbol::GetMangledName() const { + const char *name = NULL; + if (m_opaque_ptr) + name = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBSymbol(%p)::GetMangledName () => \"%s\"", + static_cast(m_opaque_ptr), name ? name : ""); + + return name; } -const char * -SBSymbol::GetMangledName () const -{ - const char *name = NULL; - if (m_opaque_ptr) - name = m_opaque_ptr->GetMangled().GetMangledName().AsCString(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBSymbol(%p)::GetMangledName () => \"%s\"", - static_cast(m_opaque_ptr), name ? name : ""); +bool SBSymbol::operator==(const SBSymbol &rhs) const { + return m_opaque_ptr == rhs.m_opaque_ptr; +} - return name; +bool SBSymbol::operator!=(const SBSymbol &rhs) const { + return m_opaque_ptr != rhs.m_opaque_ptr; } +bool SBSymbol::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + + if (m_opaque_ptr) { + m_opaque_ptr->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + } else + strm.PutCString("No value"); -bool -SBSymbol::operator == (const SBSymbol &rhs) const -{ - return m_opaque_ptr == rhs.m_opaque_ptr; + return true; } -bool -SBSymbol::operator != (const SBSymbol &rhs) const -{ - return m_opaque_ptr != rhs.m_opaque_ptr; +SBInstructionList SBSymbol::GetInstructions(SBTarget target) { + return GetInstructions(target, NULL); } -bool -SBSymbol::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +SBInstructionList SBSymbol::GetInstructions(SBTarget target, + const char *flavor_string) { + SBInstructionList sb_instructions; + if (m_opaque_ptr) { + ExecutionContext exe_ctx; + TargetSP target_sp(target.GetSP()); + std::unique_lock lock; + if (target_sp) { + lock = std::unique_lock(target_sp->GetAPIMutex()); - if (m_opaque_ptr) - { - m_opaque_ptr->GetDescription (&strm, - lldb::eDescriptionLevelFull, NULL); + target_sp->CalculateExecutionContext(exe_ctx); } - else - strm.PutCString ("No value"); - - return true; -} - -SBInstructionList -SBSymbol::GetInstructions (SBTarget target) -{ - return GetInstructions (target, NULL); -} - -SBInstructionList -SBSymbol::GetInstructions (SBTarget target, const char *flavor_string) -{ - SBInstructionList sb_instructions; - if (m_opaque_ptr) - { - ExecutionContext exe_ctx; - TargetSP target_sp (target.GetSP()); - std::unique_lock lock; - if (target_sp) - { - lock = std::unique_lock(target_sp->GetAPIMutex()); - - target_sp->CalculateExecutionContext (exe_ctx); - } - if (m_opaque_ptr->ValueIsAddress()) - { - const Address &symbol_addr = m_opaque_ptr->GetAddressRef(); - ModuleSP module_sp = symbol_addr.GetModule(); - if (module_sp) - { - AddressRange symbol_range (symbol_addr, m_opaque_ptr->GetByteSize()); - const bool prefer_file_cache = false; - sb_instructions.SetDisassembler (Disassembler::DisassembleRange (module_sp->GetArchitecture (), - NULL, - flavor_string, - exe_ctx, - symbol_range, - prefer_file_cache)); - } - } + if (m_opaque_ptr->ValueIsAddress()) { + const Address &symbol_addr = m_opaque_ptr->GetAddressRef(); + ModuleSP module_sp = symbol_addr.GetModule(); + if (module_sp) { + AddressRange symbol_range(symbol_addr, m_opaque_ptr->GetByteSize()); + const bool prefer_file_cache = false; + sb_instructions.SetDisassembler(Disassembler::DisassembleRange( + module_sp->GetArchitecture(), NULL, flavor_string, exe_ctx, + symbol_range, prefer_file_cache)); + } } - return sb_instructions; + } + return sb_instructions; } -lldb_private::Symbol * -SBSymbol::get () -{ - return m_opaque_ptr; -} +lldb_private::Symbol *SBSymbol::get() { return m_opaque_ptr; } -void -SBSymbol::reset (lldb_private::Symbol *symbol) -{ - m_opaque_ptr = symbol; +void SBSymbol::reset(lldb_private::Symbol *symbol) { m_opaque_ptr = symbol; } + +SBAddress SBSymbol::GetStartAddress() { + SBAddress addr; + if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { + addr.SetAddress(&m_opaque_ptr->GetAddressRef()); + } + return addr; } -SBAddress -SBSymbol::GetStartAddress () -{ - SBAddress addr; - if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) - { - addr.SetAddress (&m_opaque_ptr->GetAddressRef()); - } - return addr; -} - -SBAddress -SBSymbol::GetEndAddress () -{ - SBAddress addr; - if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) - { - lldb::addr_t range_size = m_opaque_ptr->GetByteSize(); - if (range_size > 0) - { - addr.SetAddress (&m_opaque_ptr->GetAddressRef()); - addr->Slide (m_opaque_ptr->GetByteSize()); - } +SBAddress SBSymbol::GetEndAddress() { + SBAddress addr; + if (m_opaque_ptr && m_opaque_ptr->ValueIsAddress()) { + lldb::addr_t range_size = m_opaque_ptr->GetByteSize(); + if (range_size > 0) { + addr.SetAddress(&m_opaque_ptr->GetAddressRef()); + addr->Slide(m_opaque_ptr->GetByteSize()); } - return addr; + } + return addr; } -uint32_t -SBSymbol::GetPrologueByteSize () -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetPrologueByteSize(); - return 0; +uint32_t SBSymbol::GetPrologueByteSize() { + if (m_opaque_ptr) + return m_opaque_ptr->GetPrologueByteSize(); + return 0; } -SymbolType -SBSymbol::GetType () -{ - if (m_opaque_ptr) - return m_opaque_ptr->GetType(); - return eSymbolTypeInvalid; +SymbolType SBSymbol::GetType() { + if (m_opaque_ptr) + return m_opaque_ptr->GetType(); + return eSymbolTypeInvalid; } -bool -SBSymbol::IsExternal() -{ - if (m_opaque_ptr) - return m_opaque_ptr->IsExternal(); - return false; +bool SBSymbol::IsExternal() { + if (m_opaque_ptr) + return m_opaque_ptr->IsExternal(); + return false; } -bool -SBSymbol::IsSynthetic() -{ - if (m_opaque_ptr) - return m_opaque_ptr->IsSynthetic(); - return false; +bool SBSymbol::IsSynthetic() { + if (m_opaque_ptr) + return m_opaque_ptr->IsSynthetic(); + return false; } - diff --git a/lldb/source/API/SBSymbolContext.cpp b/lldb/source/API/SBSymbolContext.cpp index 481fa1a1d1a..47488367331 100644 --- a/lldb/source/API/SBSymbolContext.cpp +++ b/lldb/source/API/SBSymbolContext.cpp @@ -18,270 +18,199 @@ using namespace lldb; using namespace lldb_private; +SBSymbolContext::SBSymbolContext() : m_opaque_ap() {} - -SBSymbolContext::SBSymbolContext () : - m_opaque_ap () -{ +SBSymbolContext::SBSymbolContext(const SymbolContext *sc_ptr) : m_opaque_ap() { + if (sc_ptr) + m_opaque_ap.reset(new SymbolContext(*sc_ptr)); } -SBSymbolContext::SBSymbolContext (const SymbolContext *sc_ptr) : - m_opaque_ap () -{ - if (sc_ptr) - m_opaque_ap.reset (new SymbolContext (*sc_ptr)); +SBSymbolContext::SBSymbolContext(const SBSymbolContext &rhs) : m_opaque_ap() { + if (rhs.IsValid()) { + if (m_opaque_ap.get()) + *m_opaque_ap = *rhs.m_opaque_ap; + else + ref() = *rhs.m_opaque_ap; + } } -SBSymbolContext::SBSymbolContext (const SBSymbolContext& rhs) : - m_opaque_ap () -{ - if (rhs.IsValid()) - { - if (m_opaque_ap.get()) - *m_opaque_ap = *rhs.m_opaque_ap; - else - ref() = *rhs.m_opaque_ap; - } -} +SBSymbolContext::~SBSymbolContext() {} -SBSymbolContext::~SBSymbolContext () -{ -} - -const SBSymbolContext & -SBSymbolContext::operator = (const SBSymbolContext &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_ap.reset (new lldb_private::SymbolContext(*rhs.m_opaque_ap.get())); - } - return *this; +const SBSymbolContext &SBSymbolContext::operator=(const SBSymbolContext &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_ap.reset( + new lldb_private::SymbolContext(*rhs.m_opaque_ap.get())); + } + return *this; } -void -SBSymbolContext::SetSymbolContext (const SymbolContext *sc_ptr) -{ - if (sc_ptr) - { - if (m_opaque_ap.get()) - *m_opaque_ap = *sc_ptr; - else - m_opaque_ap.reset (new SymbolContext (*sc_ptr)); - } +void SBSymbolContext::SetSymbolContext(const SymbolContext *sc_ptr) { + if (sc_ptr) { + if (m_opaque_ap.get()) + *m_opaque_ap = *sc_ptr; else - { - if (m_opaque_ap.get()) - m_opaque_ap->Clear(true); - } + m_opaque_ap.reset(new SymbolContext(*sc_ptr)); + } else { + if (m_opaque_ap.get()) + m_opaque_ap->Clear(true); + } } -bool -SBSymbolContext::IsValid () const -{ - return m_opaque_ap.get() != NULL; -} +bool SBSymbolContext::IsValid() const { return m_opaque_ap.get() != NULL; } +SBModule SBSymbolContext::GetModule() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBModule sb_module; + ModuleSP module_sp; + if (m_opaque_ap.get()) { + module_sp = m_opaque_ap->module_sp; + sb_module.SetSP(module_sp); + } -SBModule -SBSymbolContext::GetModule () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + if (log) { + SBStream sstr; + sb_module.GetDescription(sstr); + log->Printf("SBSymbolContext(%p)::GetModule () => SBModule(%p): %s", + static_cast(m_opaque_ap.get()), + static_cast(module_sp.get()), sstr.GetData()); + } - SBModule sb_module; - ModuleSP module_sp; - if (m_opaque_ap.get()) - { - module_sp = m_opaque_ap->module_sp; - sb_module.SetSP (module_sp); - } - - if (log) - { - SBStream sstr; - sb_module.GetDescription (sstr); - log->Printf ("SBSymbolContext(%p)::GetModule () => SBModule(%p): %s", - static_cast(m_opaque_ap.get()), - static_cast(module_sp.get()), sstr.GetData()); - } - - return sb_module; + return sb_module; } -SBCompileUnit -SBSymbolContext::GetCompileUnit () -{ - return SBCompileUnit (m_opaque_ap.get() ? m_opaque_ap->comp_unit : NULL); +SBCompileUnit SBSymbolContext::GetCompileUnit() { + return SBCompileUnit(m_opaque_ap.get() ? m_opaque_ap->comp_unit : NULL); } -SBFunction -SBSymbolContext::GetFunction () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBFunction SBSymbolContext::GetFunction() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - Function *function = NULL; + Function *function = NULL; - if (m_opaque_ap.get()) - function = m_opaque_ap->function; + if (m_opaque_ap.get()) + function = m_opaque_ap->function; - SBFunction sb_function (function); + SBFunction sb_function(function); - if (log) - log->Printf ("SBSymbolContext(%p)::GetFunction () => SBFunction(%p)", - static_cast(m_opaque_ap.get()), - static_cast(function)); + if (log) + log->Printf("SBSymbolContext(%p)::GetFunction () => SBFunction(%p)", + static_cast(m_opaque_ap.get()), + static_cast(function)); - return sb_function; + return sb_function; } -SBBlock -SBSymbolContext::GetBlock () -{ - return SBBlock (m_opaque_ap.get() ? m_opaque_ap->block : NULL); +SBBlock SBSymbolContext::GetBlock() { + return SBBlock(m_opaque_ap.get() ? m_opaque_ap->block : NULL); } -SBLineEntry -SBSymbolContext::GetLineEntry () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBLineEntry SBSymbolContext::GetLineEntry() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBLineEntry sb_line_entry; - if (m_opaque_ap.get()) - sb_line_entry.SetLineEntry (m_opaque_ap->line_entry); + SBLineEntry sb_line_entry; + if (m_opaque_ap.get()) + sb_line_entry.SetLineEntry(m_opaque_ap->line_entry); - if (log) - { - log->Printf ("SBSymbolContext(%p)::GetLineEntry () => SBLineEntry(%p)", - static_cast(m_opaque_ap.get()), - static_cast(sb_line_entry.get())); - } + if (log) { + log->Printf("SBSymbolContext(%p)::GetLineEntry () => SBLineEntry(%p)", + static_cast(m_opaque_ap.get()), + static_cast(sb_line_entry.get())); + } - return sb_line_entry; + return sb_line_entry; } -SBSymbol -SBSymbolContext::GetSymbol () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBSymbol SBSymbolContext::GetSymbol() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - Symbol *symbol = NULL; + Symbol *symbol = NULL; - if (m_opaque_ap.get()) - symbol = m_opaque_ap->symbol; + if (m_opaque_ap.get()) + symbol = m_opaque_ap->symbol; - SBSymbol sb_symbol (symbol); + SBSymbol sb_symbol(symbol); - if (log) - log->Printf ("SBSymbolContext(%p)::GetSymbol () => SBSymbol(%p)", - static_cast(m_opaque_ap.get()), - static_cast(symbol)); + if (log) + log->Printf("SBSymbolContext(%p)::GetSymbol () => SBSymbol(%p)", + static_cast(m_opaque_ap.get()), + static_cast(symbol)); - return sb_symbol; + return sb_symbol; } -void -SBSymbolContext::SetModule (lldb::SBModule module) -{ - ref().module_sp = module.GetSP(); +void SBSymbolContext::SetModule(lldb::SBModule module) { + ref().module_sp = module.GetSP(); } -void -SBSymbolContext::SetCompileUnit (lldb::SBCompileUnit compile_unit) -{ - ref().comp_unit = compile_unit.get(); +void SBSymbolContext::SetCompileUnit(lldb::SBCompileUnit compile_unit) { + ref().comp_unit = compile_unit.get(); } -void -SBSymbolContext::SetFunction (lldb::SBFunction function) -{ - ref().function = function.get(); +void SBSymbolContext::SetFunction(lldb::SBFunction function) { + ref().function = function.get(); } -void -SBSymbolContext::SetBlock (lldb::SBBlock block) -{ - ref().block = block.GetPtr(); +void SBSymbolContext::SetBlock(lldb::SBBlock block) { + ref().block = block.GetPtr(); } -void -SBSymbolContext::SetLineEntry (lldb::SBLineEntry line_entry) -{ - if (line_entry.IsValid()) - ref().line_entry = line_entry.ref(); - else - ref().line_entry.Clear(); +void SBSymbolContext::SetLineEntry(lldb::SBLineEntry line_entry) { + if (line_entry.IsValid()) + ref().line_entry = line_entry.ref(); + else + ref().line_entry.Clear(); } -void -SBSymbolContext::SetSymbol (lldb::SBSymbol symbol) -{ - ref().symbol = symbol.get(); +void SBSymbolContext::SetSymbol(lldb::SBSymbol symbol) { + ref().symbol = symbol.get(); } - -lldb_private::SymbolContext* -SBSymbolContext::operator->() const -{ - return m_opaque_ap.get(); +lldb_private::SymbolContext *SBSymbolContext::operator->() const { + return m_opaque_ap.get(); } - -const lldb_private::SymbolContext& -SBSymbolContext::operator*() const -{ - assert (m_opaque_ap.get()); - return *m_opaque_ap.get(); +const lldb_private::SymbolContext &SBSymbolContext::operator*() const { + assert(m_opaque_ap.get()); + return *m_opaque_ap.get(); } - -lldb_private::SymbolContext& -SBSymbolContext::operator*() -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new SymbolContext); - return *m_opaque_ap.get(); +lldb_private::SymbolContext &SBSymbolContext::operator*() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new SymbolContext); + return *m_opaque_ap.get(); } -lldb_private::SymbolContext& -SBSymbolContext::ref() -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new SymbolContext); - return *m_opaque_ap.get(); +lldb_private::SymbolContext &SBSymbolContext::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new SymbolContext); + return *m_opaque_ap.get(); } -lldb_private::SymbolContext * -SBSymbolContext::get() const -{ - return m_opaque_ap.get(); +lldb_private::SymbolContext *SBSymbolContext::get() const { + return m_opaque_ap.get(); } -bool -SBSymbolContext::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); +bool SBSymbolContext::GetDescription(SBStream &description) { + Stream &strm = description.ref(); - if (m_opaque_ap.get()) - { - m_opaque_ap->GetDescription (&strm, lldb::eDescriptionLevelFull, NULL); - } - else - strm.PutCString ("No value"); + if (m_opaque_ap.get()) { + m_opaque_ap->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + } else + strm.PutCString("No value"); - return true; + return true; } SBSymbolContext -SBSymbolContext::GetParentOfInlinedScope (const SBAddress &curr_frame_pc, - SBAddress &parent_frame_addr) const -{ - SBSymbolContext sb_sc; - if (m_opaque_ap.get() && curr_frame_pc.IsValid()) - { - if (m_opaque_ap->GetParentOfInlinedScope (curr_frame_pc.ref(), sb_sc.ref(), parent_frame_addr.ref())) - return sb_sc; - } - return SBSymbolContext(); +SBSymbolContext::GetParentOfInlinedScope(const SBAddress &curr_frame_pc, + SBAddress &parent_frame_addr) const { + SBSymbolContext sb_sc; + if (m_opaque_ap.get() && curr_frame_pc.IsValid()) { + if (m_opaque_ap->GetParentOfInlinedScope(curr_frame_pc.ref(), sb_sc.ref(), + parent_frame_addr.ref())) + return sb_sc; + } + return SBSymbolContext(); } - diff --git a/lldb/source/API/SBSymbolContextList.cpp b/lldb/source/API/SBSymbolContextList.cpp index 0730096c5f3..8cc29c3422d 100644 --- a/lldb/source/API/SBSymbolContextList.cpp +++ b/lldb/source/API/SBSymbolContextList.cpp @@ -14,104 +14,68 @@ using namespace lldb; using namespace lldb_private; -SBSymbolContextList::SBSymbolContextList () : - m_opaque_ap (new SymbolContextList()) -{ -} +SBSymbolContextList::SBSymbolContextList() + : m_opaque_ap(new SymbolContextList()) {} -SBSymbolContextList::SBSymbolContextList (const SBSymbolContextList& rhs) : - m_opaque_ap (new SymbolContextList(*rhs.m_opaque_ap)) -{ -} +SBSymbolContextList::SBSymbolContextList(const SBSymbolContextList &rhs) + : m_opaque_ap(new SymbolContextList(*rhs.m_opaque_ap)) {} -SBSymbolContextList::~SBSymbolContextList () -{ -} +SBSymbolContextList::~SBSymbolContextList() {} -const SBSymbolContextList & -SBSymbolContextList::operator = (const SBSymbolContextList &rhs) -{ - if (this != &rhs) - { - *m_opaque_ap = *rhs.m_opaque_ap; - } - return *this; +const SBSymbolContextList &SBSymbolContextList:: +operator=(const SBSymbolContextList &rhs) { + if (this != &rhs) { + *m_opaque_ap = *rhs.m_opaque_ap; + } + return *this; } -uint32_t -SBSymbolContextList::GetSize() const -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetSize(); - return 0; +uint32_t SBSymbolContextList::GetSize() const { + if (m_opaque_ap.get()) + return m_opaque_ap->GetSize(); + return 0; } -SBSymbolContext -SBSymbolContextList::GetContextAtIndex (uint32_t idx) -{ - SBSymbolContext sb_sc; - if (m_opaque_ap.get()) - { - SymbolContext sc; - if (m_opaque_ap->GetContextAtIndex (idx, sc)) - { - sb_sc.SetSymbolContext(&sc); - } +SBSymbolContext SBSymbolContextList::GetContextAtIndex(uint32_t idx) { + SBSymbolContext sb_sc; + if (m_opaque_ap.get()) { + SymbolContext sc; + if (m_opaque_ap->GetContextAtIndex(idx, sc)) { + sb_sc.SetSymbolContext(&sc); } - return sb_sc; + } + return sb_sc; } -void -SBSymbolContextList::Clear() -{ - if (m_opaque_ap.get()) - m_opaque_ap->Clear(); +void SBSymbolContextList::Clear() { + if (m_opaque_ap.get()) + m_opaque_ap->Clear(); } -void -SBSymbolContextList::Append(SBSymbolContext &sc) -{ - if (sc.IsValid() && m_opaque_ap.get()) - m_opaque_ap->Append(*sc); +void SBSymbolContextList::Append(SBSymbolContext &sc) { + if (sc.IsValid() && m_opaque_ap.get()) + m_opaque_ap->Append(*sc); } -void -SBSymbolContextList::Append(SBSymbolContextList &sc_list) -{ - if (sc_list.IsValid() && m_opaque_ap.get()) - m_opaque_ap->Append(*sc_list); +void SBSymbolContextList::Append(SBSymbolContextList &sc_list) { + if (sc_list.IsValid() && m_opaque_ap.get()) + m_opaque_ap->Append(*sc_list); } +bool SBSymbolContextList::IsValid() const { return m_opaque_ap.get() != NULL; } -bool -SBSymbolContextList::IsValid () const -{ - return m_opaque_ap.get() != NULL; +lldb_private::SymbolContextList *SBSymbolContextList::operator->() const { + return m_opaque_ap.get(); } - - -lldb_private::SymbolContextList* -SBSymbolContextList::operator->() const -{ - return m_opaque_ap.get(); +lldb_private::SymbolContextList &SBSymbolContextList::operator*() const { + assert(m_opaque_ap.get()); + return *m_opaque_ap.get(); } - -lldb_private::SymbolContextList& -SBSymbolContextList::operator*() const -{ - assert (m_opaque_ap.get()); - return *m_opaque_ap.get(); -} - -bool -SBSymbolContextList::GetDescription (lldb::SBStream &description) -{ - Stream &strm = description.ref(); - if (m_opaque_ap.get()) - m_opaque_ap->GetDescription (&strm, lldb::eDescriptionLevelFull, NULL); - return true; +bool SBSymbolContextList::GetDescription(lldb::SBStream &description) { + Stream &strm = description.ref(); + if (m_opaque_ap.get()) + m_opaque_ap->GetDescription(&strm, lldb::eDescriptionLevelFull, NULL); + return true; } - - diff --git a/lldb/source/API/SBTarget.cpp b/lldb/source/API/SBTarget.cpp index 6a5301b0605..5ada7fb8a30 100644 --- a/lldb/source/API/SBTarget.cpp +++ b/lldb/source/API/SBTarget.cpp @@ -19,8 +19,8 @@ #include "lldb/API/SBListener.h" #include "lldb/API/SBModule.h" #include "lldb/API/SBModuleSpec.h" -#include "lldb/API/SBSourceManager.h" #include "lldb/API/SBProcess.h" +#include "lldb/API/SBSourceManager.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBStringList.h" #include "lldb/API/SBSymbolContextList.h" @@ -38,9 +38,9 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/RegularExpression.h" +#include "lldb/Core/STLUtils.h" #include "lldb/Core/SearchFilter.h" #include "lldb/Core/Section.h" -#include "lldb/Core/STLUtils.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Core/ValueObjectList.h" #include "lldb/Core/ValueObjectVariable.h" @@ -62,11 +62,10 @@ #include "lldb/Target/Target.h" #include "lldb/Target/TargetList.h" -#include "lldb/Interpreter/CommandReturnObject.h" #include "../source/Commands/CommandObjectBreakpoint.h" +#include "lldb/Interpreter/CommandReturnObject.h" #include "llvm/Support/Regex.h" - using namespace lldb; using namespace lldb_private; @@ -74,2444 +73,2025 @@ using namespace lldb_private; namespace { -Error -AttachToProcess (ProcessAttachInfo &attach_info, Target &target) -{ - std::lock_guard guard(target.GetAPIMutex()); +Error AttachToProcess(ProcessAttachInfo &attach_info, Target &target) { + std::lock_guard guard(target.GetAPIMutex()); - auto process_sp = target.GetProcessSP (); - if (process_sp) - { - const auto state = process_sp->GetState (); - if (process_sp->IsAlive () && state == eStateConnected) - { - // If we are already connected, then we have already specified the - // listener, so if a valid listener is supplied, we need to error out - // to let the client know. - if (attach_info.GetListener ()) - return Error ("process is connected and already has a listener, pass empty listener"); - } + auto process_sp = target.GetProcessSP(); + if (process_sp) { + const auto state = process_sp->GetState(); + if (process_sp->IsAlive() && state == eStateConnected) { + // If we are already connected, then we have already specified the + // listener, so if a valid listener is supplied, we need to error out + // to let the client know. + if (attach_info.GetListener()) + return Error("process is connected and already has a listener, pass " + "empty listener"); } + } - return target.Attach (attach_info, nullptr); + return target.Attach(attach_info, nullptr); } -} // namespace +} // namespace //---------------------------------------------------------------------- // SBTarget constructor //---------------------------------------------------------------------- -SBTarget::SBTarget () : - m_opaque_sp () -{ -} +SBTarget::SBTarget() : m_opaque_sp() {} -SBTarget::SBTarget (const SBTarget& rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) {} -SBTarget::SBTarget(const TargetSP& target_sp) : - m_opaque_sp (target_sp) -{ -} +SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) {} -const SBTarget& -SBTarget::operator = (const SBTarget& rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBTarget &SBTarget::operator=(const SBTarget &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -SBTarget::~SBTarget() -{ +SBTarget::~SBTarget() {} + +bool SBTarget::EventIsTargetEvent(const SBEvent &event) { + return Target::TargetEventData::GetEventDataFromEvent(event.get()) != NULL; } -bool -SBTarget::EventIsTargetEvent (const SBEvent &event) -{ - return Target::TargetEventData::GetEventDataFromEvent(event.get()) != NULL; +SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) { + return Target::TargetEventData::GetTargetFromEvent(event.get()); } -SBTarget -SBTarget::GetTargetFromEvent (const SBEvent &event) -{ - return Target::TargetEventData::GetTargetFromEvent (event.get()); +uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) { + const ModuleList module_list = + Target::TargetEventData::GetModuleListFromEvent(event.get()); + return module_list.GetSize(); } -uint32_t -SBTarget::GetNumModulesFromEvent (const SBEvent &event) -{ - const ModuleList module_list = Target::TargetEventData::GetModuleListFromEvent (event.get()); - return module_list.GetSize(); +SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx, + const SBEvent &event) { + const ModuleList module_list = + Target::TargetEventData::GetModuleListFromEvent(event.get()); + return SBModule(module_list.GetModuleAtIndex(idx)); } -SBModule -SBTarget::GetModuleAtIndexFromEvent (const uint32_t idx, const SBEvent &event) -{ - const ModuleList module_list = Target::TargetEventData::GetModuleListFromEvent (event.get()); - return SBModule(module_list.GetModuleAtIndex(idx)); +const char *SBTarget::GetBroadcasterClassName() { + return Target::GetStaticBroadcasterClass().AsCString(); } -const char * -SBTarget::GetBroadcasterClassName () -{ - return Target::GetStaticBroadcasterClass().AsCString(); +bool SBTarget::IsValid() const { + return m_opaque_sp.get() != NULL && m_opaque_sp->IsValid(); } -bool -SBTarget::IsValid () const -{ - return m_opaque_sp.get() != NULL && m_opaque_sp->IsValid(); +SBProcess SBTarget::GetProcess() { + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + if (target_sp) { + process_sp = target_sp->GetProcessSP(); + sb_process.SetSP(process_sp); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBTarget(%p)::GetProcess () => SBProcess(%p)", + static_cast(target_sp.get()), + static_cast(process_sp.get())); + + return sb_process; } -SBProcess -SBTarget::GetProcess () -{ - SBProcess sb_process; - ProcessSP process_sp; - TargetSP target_sp(GetSP()); - if (target_sp) - { - process_sp = target_sp->GetProcessSP(); - sb_process.SetSP (process_sp); - } +SBPlatform SBTarget::GetPlatform() { + TargetSP target_sp(GetSP()); + if (!target_sp) + return SBPlatform(); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBTarget(%p)::GetProcess () => SBProcess(%p)", - static_cast(target_sp.get()), - static_cast(process_sp.get())); + SBPlatform platform; + platform.m_opaque_sp = target_sp->GetPlatform(); - return sb_process; + return platform; } -SBPlatform -SBTarget::GetPlatform () -{ - TargetSP target_sp(GetSP()); - if (!target_sp) - return SBPlatform(); +SBDebugger SBTarget::GetDebugger() const { + SBDebugger debugger; + TargetSP target_sp(GetSP()); + if (target_sp) + debugger.reset(target_sp->GetDebugger().shared_from_this()); + return debugger; +} - SBPlatform platform; - platform.m_opaque_sp = target_sp->GetPlatform(); +SBProcess SBTarget::LoadCore(const char *core_file) { + SBProcess sb_process; + TargetSP target_sp(GetSP()); + if (target_sp) { + FileSpec filespec(core_file, true); + ProcessSP process_sp(target_sp->CreateProcess( + target_sp->GetDebugger().GetListener(), NULL, &filespec)); + if (process_sp) { + process_sp->LoadCore(); + sb_process.SetSP(process_sp); + } + } + return sb_process; +} - return platform; +SBProcess SBTarget::LaunchSimple(char const **argv, char const **envp, + const char *working_directory) { + char *stdin_path = NULL; + char *stdout_path = NULL; + char *stderr_path = NULL; + uint32_t launch_flags = 0; + bool stop_at_entry = false; + SBError error; + SBListener listener = GetDebugger().GetListener(); + return Launch(listener, argv, envp, stdin_path, stdout_path, stderr_path, + working_directory, launch_flags, stop_at_entry, error); } -SBDebugger -SBTarget::GetDebugger () const -{ - SBDebugger debugger; - TargetSP target_sp(GetSP()); - if (target_sp) - debugger.reset (target_sp->GetDebugger().shared_from_this()); - return debugger; +SBError SBTarget::Install() { + SBError sb_error; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + sb_error.ref() = target_sp->Install(NULL); + } + return sb_error; } -SBProcess -SBTarget::LoadCore (const char *core_file) -{ - SBProcess sb_process; - TargetSP target_sp(GetSP()); - if (target_sp) - { - FileSpec filespec(core_file, true); - ProcessSP process_sp (target_sp->CreateProcess(target_sp->GetDebugger().GetListener(), - NULL, - &filespec)); - if (process_sp) - { - process_sp->LoadCore(); - sb_process.SetSP (process_sp); +SBProcess SBTarget::Launch(SBListener &listener, char const **argv, + char const **envp, const char *stdin_path, + const char *stdout_path, const char *stderr_path, + const char *working_directory, + uint32_t launch_flags, // See LaunchFlags + bool stop_at_entry, lldb::SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + + if (log) + log->Printf("SBTarget(%p)::Launch (argv=%p, envp=%p, stdin=%s, stdout=%s, " + "stderr=%s, working-dir=%s, launch_flags=0x%x, " + "stop_at_entry=%i, &error (%p))...", + static_cast(target_sp.get()), static_cast(argv), + static_cast(envp), stdin_path ? stdin_path : "NULL", + stdout_path ? stdout_path : "NULL", + stderr_path ? stderr_path : "NULL", + working_directory ? working_directory : "NULL", launch_flags, + stop_at_entry, static_cast(error.get())); + + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + + if (stop_at_entry) + launch_flags |= eLaunchFlagStopAtEntry; + + if (getenv("LLDB_LAUNCH_FLAG_DISABLE_ASLR")) + launch_flags |= eLaunchFlagDisableASLR; + + StateType state = eStateInvalid; + process_sp = target_sp->GetProcessSP(); + if (process_sp) { + state = process_sp->GetState(); + + if (process_sp->IsAlive() && state != eStateConnected) { + if (state == eStateAttaching) + error.SetErrorString("process attach is in progress"); + else + error.SetErrorString("a process is already being debugged"); + return sb_process; + } + } + + if (state == eStateConnected) { + // If we are already connected, then we have already specified the + // listener, so if a valid listener is supplied, we need to error out + // to let the client know. + if (listener.IsValid()) { + error.SetErrorString("process is connected and already has a listener, " + "pass empty listener"); + return sb_process; + } + } + + if (getenv("LLDB_LAUNCH_FLAG_DISABLE_STDIO")) + launch_flags |= eLaunchFlagDisableSTDIO; + + ProcessLaunchInfo launch_info( + FileSpec{stdin_path, false}, FileSpec{stdout_path, false}, + FileSpec{stderr_path, false}, FileSpec{working_directory, false}, + launch_flags); + + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + if (argv) + launch_info.GetArguments().AppendArguments(argv); + if (envp) + launch_info.GetEnvironmentEntries().SetArguments(envp); + + if (listener.IsValid()) + launch_info.SetListener(listener.GetSP()); + + error.SetError(target_sp->Launch(launch_info, NULL)); + + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } + + log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); + if (log) + log->Printf("SBTarget(%p)::Launch (...) => SBProcess(%p), SBError(%s)", + static_cast(target_sp.get()), + static_cast(sb_process.GetSP().get()), + error.GetCString()); + + return sb_process; +} + +SBProcess SBTarget::Launch(SBLaunchInfo &sb_launch_info, SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (log) + log->Printf("SBTarget(%p)::Launch (launch_info, error)...", + static_cast(target_sp.get())); + + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + StateType state = eStateInvalid; + { + ProcessSP process_sp = target_sp->GetProcessSP(); + if (process_sp) { + state = process_sp->GetState(); + + if (process_sp->IsAlive() && state != eStateConnected) { + if (state == eStateAttaching) + error.SetErrorString("process attach is in progress"); + else + error.SetErrorString("a process is already being debugged"); + return sb_process; } + } } - return sb_process; -} - -SBProcess -SBTarget::LaunchSimple -( - char const **argv, - char const **envp, - const char *working_directory -) -{ - char *stdin_path = NULL; - char *stdout_path = NULL; - char *stderr_path = NULL; - uint32_t launch_flags = 0; - bool stop_at_entry = false; - SBError error; - SBListener listener = GetDebugger().GetListener(); - return Launch (listener, - argv, - envp, - stdin_path, - stdout_path, - stderr_path, - working_directory, - launch_flags, - stop_at_entry, - error); -} - -SBError -SBTarget::Install() -{ - SBError sb_error; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - sb_error.ref() = target_sp->Install(NULL); - } - return sb_error; -} - -SBProcess -SBTarget::Launch -( - SBListener &listener, - char const **argv, - char const **envp, - const char *stdin_path, - const char *stdout_path, - const char *stderr_path, - const char *working_directory, - uint32_t launch_flags, // See LaunchFlags - bool stop_at_entry, - lldb::SBError& error -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBProcess sb_process; - ProcessSP process_sp; - TargetSP target_sp(GetSP()); - if (log) - log->Printf ("SBTarget(%p)::Launch (argv=%p, envp=%p, stdin=%s, stdout=%s, stderr=%s, working-dir=%s, launch_flags=0x%x, stop_at_entry=%i, &error (%p))...", - static_cast(target_sp.get()), - static_cast(argv), static_cast(envp), - stdin_path ? stdin_path : "NULL", - stdout_path ? stdout_path : "NULL", - stderr_path ? stderr_path : "NULL", - working_directory ? working_directory : "NULL", - launch_flags, stop_at_entry, - static_cast(error.get())); + lldb_private::ProcessLaunchInfo &launch_info = sb_launch_info.ref(); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - - if (stop_at_entry) - launch_flags |= eLaunchFlagStopAtEntry; - - if (getenv("LLDB_LAUNCH_FLAG_DISABLE_ASLR")) - launch_flags |= eLaunchFlagDisableASLR; - - StateType state = eStateInvalid; - process_sp = target_sp->GetProcessSP(); - if (process_sp) - { - state = process_sp->GetState(); - - if (process_sp->IsAlive() && state != eStateConnected) - { - if (state == eStateAttaching) - error.SetErrorString ("process attach is in progress"); - else - error.SetErrorString ("a process is already being debugged"); - return sb_process; - } - } + if (!launch_info.GetExecutableFile()) { + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); + } - if (state == eStateConnected) - { - // If we are already connected, then we have already specified the - // listener, so if a valid listener is supplied, we need to error out - // to let the client know. - if (listener.IsValid()) - { - error.SetErrorString ("process is connected and already has a listener, pass empty listener"); - return sb_process; - } - } + const ArchSpec &arch_spec = target_sp->GetArchitecture(); + if (arch_spec.IsValid()) + launch_info.GetArchitecture() = arch_spec; - if (getenv("LLDB_LAUNCH_FLAG_DISABLE_STDIO")) - launch_flags |= eLaunchFlagDisableSTDIO; + error.SetError(target_sp->Launch(launch_info, NULL)); + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } - ProcessLaunchInfo launch_info(FileSpec{stdin_path, false}, - FileSpec{stdout_path, false}, - FileSpec{stderr_path, false}, - FileSpec{working_directory, false}, - launch_flags); + log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API); + if (log) + log->Printf("SBTarget(%p)::Launch (...) => SBProcess(%p)", + static_cast(target_sp.get()), + static_cast(sb_process.GetSP().get())); - Module *exe_module = target_sp->GetExecutableModulePointer(); - if (exe_module) - launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); - if (argv) - launch_info.GetArguments().AppendArguments (argv); - if (envp) - launch_info.GetEnvironmentEntries ().SetArguments (envp); + return sb_process; +} - if (listener.IsValid()) - launch_info.SetListener(listener.GetSP()); +lldb::SBProcess SBTarget::Attach(SBAttachInfo &sb_attach_info, SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - error.SetError (target_sp->Launch(launch_info, NULL)); + SBProcess sb_process; + TargetSP target_sp(GetSP()); - sb_process.SetSP(target_sp->GetProcessSP()); - } - else - { - error.SetErrorString ("SBTarget is invalid"); + if (log) + log->Printf("SBTarget(%p)::Attach (sb_attach_info, error)...", + static_cast(target_sp.get())); + + if (target_sp) { + ProcessAttachInfo &attach_info = sb_attach_info.ref(); + if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid()) { + PlatformSP platform_sp = target_sp->GetPlatform(); + // See if we can pre-verify if a process exists or not + if (platform_sp && platform_sp->IsConnected()) { + lldb::pid_t attach_pid = attach_info.GetProcessID(); + ProcessInstanceInfo instance_info; + if (platform_sp->GetProcessInfo(attach_pid, instance_info)) { + attach_info.SetUserID(instance_info.GetEffectiveUserID()); + } else { + error.ref().SetErrorStringWithFormat( + "no process found with process ID %" PRIu64, attach_pid); + if (log) { + log->Printf("SBTarget(%p)::Attach (...) => error %s", + static_cast(target_sp.get()), + error.GetCString()); + } + return sb_process; + } + } } + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else { + error.SetErrorString("SBTarget is invalid"); + } - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API); - if (log) - log->Printf("SBTarget(%p)::Launch (...) => SBProcess(%p), SBError(%s)", static_cast(target_sp.get()), - static_cast(sb_process.GetSP().get()), error.GetCString()); + if (log) + log->Printf("SBTarget(%p)::Attach (...) => SBProcess(%p)", + static_cast(target_sp.get()), + static_cast(sb_process.GetSP().get())); - return sb_process; + return sb_process; } -SBProcess -SBTarget::Launch (SBLaunchInfo &sb_launch_info, SBError& error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +#if defined(__APPLE__) - SBProcess sb_process; - TargetSP target_sp(GetSP()); +lldb::SBProcess SBTarget::AttachToProcessWithID(SBListener &listener, + ::pid_t pid, + lldb::SBError &error) { + return AttachToProcessWithID(listener, (lldb::pid_t)pid, error); +} - if (log) - log->Printf ("SBTarget(%p)::Launch (launch_info, error)...", - static_cast(target_sp.get())); +#endif // #if defined(__APPLE__) - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - StateType state = eStateInvalid; - { - ProcessSP process_sp = target_sp->GetProcessSP(); - if (process_sp) - { - state = process_sp->GetState(); - - if (process_sp->IsAlive() && state != eStateConnected) - { - if (state == eStateAttaching) - error.SetErrorString ("process attach is in progress"); - else - error.SetErrorString ("a process is already being debugged"); - return sb_process; - } - } - } +lldb::SBProcess SBTarget::AttachToProcessWithID( + SBListener &listener, + lldb::pid_t pid, // The process ID to attach to + SBError &error // An error explaining what went wrong if attach fails + ) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (log) + log->Printf("SBTarget(%p)::%s (listener, pid=%" PRId64 ", error)...", + static_cast(target_sp.get()), __FUNCTION__, pid); + + if (target_sp) { + ProcessAttachInfo attach_info; + attach_info.SetProcessID(pid); + if (listener.IsValid()) + attach_info.SetListener(listener.GetSP()); + + ProcessInstanceInfo instance_info; + if (target_sp->GetPlatform()->GetProcessInfo(pid, instance_info)) + attach_info.SetUserID(instance_info.GetEffectiveUserID()); + + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else + error.SetErrorString("SBTarget is invalid"); + + if (log) + log->Printf("SBTarget(%p)::%s (...) => SBProcess(%p)", + static_cast(target_sp.get()), __FUNCTION__, + static_cast(sb_process.GetSP().get())); + return sb_process; +} + +lldb::SBProcess SBTarget::AttachToProcessWithName( + SBListener &listener, + const char *name, // basename of process to attach to + bool wait_for, // if true wait for a new instance of "name" to be launched + SBError &error // An error explaining what went wrong if attach fails + ) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBProcess sb_process; + TargetSP target_sp(GetSP()); + + if (log) + log->Printf("SBTarget(%p)::%s (listener, name=%s, wait_for=%s, error)...", + static_cast(target_sp.get()), __FUNCTION__, name, + wait_for ? "true" : "false"); + + if (name && target_sp) { + ProcessAttachInfo attach_info; + attach_info.GetExecutableFile().SetFile(name, false); + attach_info.SetWaitForLaunch(wait_for); + if (listener.IsValid()) + attach_info.SetListener(listener.GetSP()); + + error.SetError(AttachToProcess(attach_info, *target_sp)); + if (error.Success()) + sb_process.SetSP(target_sp->GetProcessSP()); + } else + error.SetErrorString("SBTarget is invalid"); + + if (log) + log->Printf("SBTarget(%p)::%s (...) => SBProcess(%p)", + static_cast(target_sp.get()), __FUNCTION__, + static_cast(sb_process.GetSP().get())); + return sb_process; +} + +lldb::SBProcess SBTarget::ConnectRemote(SBListener &listener, const char *url, + const char *plugin_name, + SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBProcess sb_process; + ProcessSP process_sp; + TargetSP target_sp(GetSP()); + + if (log) + log->Printf("SBTarget(%p)::ConnectRemote (listener, url=%s, " + "plugin_name=%s, error)...", + static_cast(target_sp.get()), url, plugin_name); + + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + if (listener.IsValid()) + process_sp = + target_sp->CreateProcess(listener.m_opaque_sp, plugin_name, NULL); + else + process_sp = target_sp->CreateProcess( + target_sp->GetDebugger().GetListener(), plugin_name, NULL); - lldb_private::ProcessLaunchInfo &launch_info = sb_launch_info.ref(); + if (process_sp) { + sb_process.SetSP(process_sp); + error.SetError(process_sp->ConnectRemote(NULL, url)); + } else { + error.SetErrorString("unable to create lldb_private::Process"); + } + } else { + error.SetErrorString("SBTarget is invalid"); + } - if (!launch_info.GetExecutableFile()) - { - Module *exe_module = target_sp->GetExecutableModulePointer(); - if (exe_module) - launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); - } + if (log) + log->Printf("SBTarget(%p)::ConnectRemote (...) => SBProcess(%p)", + static_cast(target_sp.get()), + static_cast(process_sp.get())); + return sb_process; +} - const ArchSpec &arch_spec = target_sp->GetArchitecture(); - if (arch_spec.IsValid()) - launch_info.GetArchitecture () = arch_spec; +SBFileSpec SBTarget::GetExecutable() { - error.SetError (target_sp->Launch (launch_info, NULL)); - sb_process.SetSP(target_sp->GetProcessSP()); - } - else - { - error.SetErrorString ("SBTarget is invalid"); - } + SBFileSpec exe_file_spec; + TargetSP target_sp(GetSP()); + if (target_sp) { + Module *exe_module = target_sp->GetExecutableModulePointer(); + if (exe_module) + exe_file_spec.SetFileSpec(exe_module->GetFileSpec()); + } - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API); - if (log) - log->Printf ("SBTarget(%p)::Launch (...) => SBProcess(%p)", - static_cast(target_sp.get()), - static_cast(sb_process.GetSP().get())); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + log->Printf("SBTarget(%p)::GetExecutable () => SBFileSpec(%p)", + static_cast(target_sp.get()), + static_cast(exe_file_spec.get())); + } - return sb_process; + return exe_file_spec; } -lldb::SBProcess -SBTarget::Attach (SBAttachInfo &sb_attach_info, SBError& error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBTarget::operator==(const SBTarget &rhs) const { + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); +} - SBProcess sb_process; - TargetSP target_sp(GetSP()); +bool SBTarget::operator!=(const SBTarget &rhs) const { + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); +} - if (log) - log->Printf ("SBTarget(%p)::Attach (sb_attach_info, error)...", - static_cast(target_sp.get())); +lldb::TargetSP SBTarget::GetSP() const { return m_opaque_sp; } - if (target_sp) - { - ProcessAttachInfo &attach_info = sb_attach_info.ref(); - if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid()) - { - PlatformSP platform_sp = target_sp->GetPlatform(); - // See if we can pre-verify if a process exists or not - if (platform_sp && platform_sp->IsConnected()) - { - lldb::pid_t attach_pid = attach_info.GetProcessID(); - ProcessInstanceInfo instance_info; - if (platform_sp->GetProcessInfo(attach_pid, instance_info)) - { - attach_info.SetUserID(instance_info.GetEffectiveUserID()); - } - else - { - error.ref().SetErrorStringWithFormat("no process found with process ID %" PRIu64, attach_pid); - if (log) - { - log->Printf ("SBTarget(%p)::Attach (...) => error %s", - static_cast(target_sp.get()), error.GetCString()); - } - return sb_process; - } - } - } - error.SetError(AttachToProcess(attach_info, *target_sp)); - if (error.Success()) - sb_process.SetSP(target_sp->GetProcessSP()); - } - else - { - error.SetErrorString ("SBTarget is invalid"); - } +void SBTarget::SetSP(const lldb::TargetSP &target_sp) { + m_opaque_sp = target_sp; +} - if (log) - log->Printf ("SBTarget(%p)::Attach (...) => SBProcess(%p)", - static_cast(target_sp.get()), - static_cast(sb_process.GetSP().get())); +lldb::SBAddress SBTarget::ResolveLoadAddress(lldb::addr_t vm_addr) { + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveLoadAddress(vm_addr, addr)) + return sb_addr; + } - return sb_process; + // We have a load address that isn't in a section, just return an address + // with the offset filled in (the address) and the section set to NULL + addr.SetRawAddress(vm_addr); + return sb_addr; } +lldb::SBAddress SBTarget::ResolveFileAddress(lldb::addr_t file_addr) { + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveFileAddress(file_addr, addr)) + return sb_addr; + } -#if defined(__APPLE__) - -lldb::SBProcess -SBTarget::AttachToProcessWithID (SBListener &listener, - ::pid_t pid, - lldb::SBError& error) -{ - return AttachToProcessWithID (listener, (lldb::pid_t)pid, error); + addr.SetRawAddress(file_addr); + return sb_addr; } -#endif // #if defined(__APPLE__) +lldb::SBAddress SBTarget::ResolvePastLoadAddress(uint32_t stop_id, + lldb::addr_t vm_addr) { + lldb::SBAddress sb_addr; + Address &addr = sb_addr.ref(); + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + if (target_sp->ResolveLoadAddress(vm_addr, addr)) + return sb_addr; + } + + // We have a load address that isn't in a section, just return an address + // with the offset filled in (the address) and the section set to NULL + addr.SetRawAddress(vm_addr); + return sb_addr; +} -lldb::SBProcess -SBTarget::AttachToProcessWithID -( - SBListener &listener, - lldb::pid_t pid,// The process ID to attach to - SBError& error // An error explaining what went wrong if attach fails -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBProcess sb_process; +SBSymbolContext +SBTarget::ResolveSymbolContextForAddress(const SBAddress &addr, + uint32_t resolve_scope) { + SBSymbolContext sc; + if (addr.IsValid()) { TargetSP target_sp(GetSP()); + if (target_sp) + target_sp->GetImages().ResolveSymbolContextForAddress( + addr.ref(), resolve_scope, sc.ref()); + } + return sc; +} - if (log) - log->Printf ("SBTarget(%p)::%s (listener, pid=%" PRId64 ", error)...", - static_cast(target_sp.get()), - __FUNCTION__, - pid); +size_t SBTarget::ReadMemory(const SBAddress addr, void *buf, size_t size, + lldb::SBError &error) { + SBError sb_error; + size_t bytes_read = 0; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + bytes_read = + target_sp->ReadMemory(addr.ref(), false, buf, size, sb_error.ref()); + } else { + sb_error.SetErrorString("invalid target"); + } - if (target_sp) - { - ProcessAttachInfo attach_info; - attach_info.SetProcessID (pid); - if (listener.IsValid()) - attach_info.SetListener(listener.GetSP()); + return bytes_read; +} - ProcessInstanceInfo instance_info; - if (target_sp->GetPlatform ()->GetProcessInfo (pid, instance_info)) - attach_info.SetUserID (instance_info.GetEffectiveUserID ()); +SBBreakpoint SBTarget::BreakpointCreateByLocation(const char *file, + uint32_t line) { + return SBBreakpoint( + BreakpointCreateByLocation(SBFileSpec(file, false), line)); +} - error.SetError (AttachToProcess (attach_info, *target_sp)); - if (error.Success ()) - sb_process.SetSP (target_sp->GetProcessSP ()); - } - else - error.SetErrorString ("SBTarget is invalid"); +SBBreakpoint +SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, + uint32_t line) { + return BreakpointCreateByLocation(sb_file_spec, line, 0); +} - if (log) - log->Printf ("SBTarget(%p)::%s (...) => SBProcess(%p)", - static_cast(target_sp.get ()), - __FUNCTION__, - static_cast(sb_process.GetSP().get ())); - return sb_process; -} - -lldb::SBProcess -SBTarget::AttachToProcessWithName -( - SBListener &listener, - const char *name, // basename of process to attach to - bool wait_for, // if true wait for a new instance of "name" to be launched - SBError& error // An error explaining what went wrong if attach fails -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBProcess sb_process; - TargetSP target_sp(GetSP()); +SBBreakpoint +SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec, + uint32_t line, lldb::addr_t offset) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && line != 0) { + std::lock_guard guard(target_sp->GetAPIMutex()); + + const LazyBool check_inlines = eLazyBoolCalculate; + const LazyBool skip_prologue = eLazyBoolCalculate; + const bool internal = false; + const bool hardware = false; + const LazyBool move_to_nearest_code = eLazyBoolCalculate; + *sb_bp = target_sp->CreateBreakpoint(NULL, *sb_file_spec, line, offset, + check_inlines, skip_prologue, internal, + hardware, move_to_nearest_code); + } + + if (log) { + SBStream sstr; + sb_bp.GetDescription(sstr); + char path[PATH_MAX]; + sb_file_spec->GetPath(path, sizeof(path)); + log->Printf("SBTarget(%p)::BreakpointCreateByLocation ( %s:%u ) => " + "SBBreakpoint(%p): %s", + static_cast(target_sp.get()), path, line, + static_cast(sb_bp.get()), sstr.GetData()); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name, + const char *module_name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp.get()) { + std::lock_guard guard(target_sp->GetAPIMutex()); + + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + const lldb::addr_t offset = 0; + if (module_name && module_name[0]) { + FileSpecList module_spec_list; + module_spec_list.Append(FileSpec(module_name, false)); + *sb_bp = target_sp->CreateBreakpoint( + &module_spec_list, NULL, symbol_name, eFunctionNameTypeAuto, + eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); + } else { + *sb_bp = target_sp->CreateBreakpoint( + NULL, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, + offset, skip_prologue, internal, hardware); + } + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", " + "module=\"%s\") => SBBreakpoint(%p)", + static_cast(target_sp.get()), symbol_name, module_name, + static_cast(sb_bp.get())); + + return sb_bp; +} + +lldb::SBBreakpoint +SBTarget::BreakpointCreateByName(const char *symbol_name, + const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + uint32_t name_type_mask = eFunctionNameTypeAuto; + return BreakpointCreateByName(symbol_name, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByName( + const char *symbol_name, uint32_t name_type_mask, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + return BreakpointCreateByName(symbol_name, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByName( + const char *symbol_name, uint32_t name_type_mask, + LanguageType symbol_language, const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && symbol_name && symbol_name[0]) { + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + std::lock_guard guard(target_sp->GetAPIMutex()); + *sb_bp = target_sp->CreateBreakpoint( + module_list.get(), comp_unit_list.get(), symbol_name, name_type_mask, + symbol_language, 0, skip_prologue, internal, hardware); + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", " + "name_type: %d) => SBBreakpoint(%p)", + static_cast(target_sp.get()), symbol_name, + name_type_mask, static_cast(sb_bp.get())); + + return sb_bp; +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, + eLanguageTypeUnknown, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + LanguageType symbol_language, const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, + eLanguageTypeUnknown, 0, module_list, + comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByNames( + const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask, + LanguageType symbol_language, lldb::addr_t offset, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && num_names > 0) { + std::lock_guard guard(target_sp->GetAPIMutex()); + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + *sb_bp = target_sp->CreateBreakpoint( + module_list.get(), comp_unit_list.get(), symbol_names, num_names, + name_type_mask, symbol_language, offset, skip_prologue, internal, + hardware); + } + + if (log) { + log->Printf("SBTarget(%p)::BreakpointCreateByName (symbols={", + static_cast(target_sp.get())); + for (uint32_t i = 0; i < num_names; i++) { + char sep; + if (i < num_names - 1) + sep = ','; + else + sep = '}'; + if (symbol_names[i] != NULL) + log->Printf("\"%s\"%c ", symbol_names[i], sep); + else + log->Printf("\"\"%c ", sep); + } + log->Printf("name_type: %d) => SBBreakpoint(%p)", name_type_mask, + static_cast(sb_bp.get())); + } + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex, + const char *module_name) { + SBFileSpecList module_spec_list; + SBFileSpecList comp_unit_list; + if (module_name && module_name[0]) { + module_spec_list.Append(FileSpec(module_name, false)); + } + return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, + module_spec_list, comp_unit_list); +} +lldb::SBBreakpoint +SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex, + const SBFileSpecList &module_list, + const SBFileSpecList &comp_unit_list) { + return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, + module_list, comp_unit_list); +} + +lldb::SBBreakpoint SBTarget::BreakpointCreateByRegex( + const char *symbol_name_regex, LanguageType symbol_language, + const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && symbol_name_regex && symbol_name_regex[0]) { + std::lock_guard guard(target_sp->GetAPIMutex()); + RegularExpression regexp(symbol_name_regex); + const bool internal = false; + const bool hardware = false; + const LazyBool skip_prologue = eLazyBoolCalculate; + + *sb_bp = target_sp->CreateFuncRegexBreakpoint( + module_list.get(), comp_unit_list.get(), regexp, symbol_language, + skip_prologue, internal, hardware); + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByRegex (symbol_regex=\"%s\") " + "=> SBBreakpoint(%p)", + static_cast(target_sp.get()), symbol_name_regex, + static_cast(sb_bp.get())); + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + const bool hardware = false; + *sb_bp = target_sp->CreateBreakpoint(address, false, hardware); + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByAddress (address=%" PRIu64 + ") => SBBreakpoint(%p)", + static_cast(target_sp.get()), + static_cast(address), + static_cast(sb_bp.get())); + + return sb_bp; +} + +SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (!sb_address.IsValid()) { if (log) - log->Printf ("SBTarget(%p)::%s (listener, name=%s, wait_for=%s, error)...", - static_cast(target_sp.get()), - __FUNCTION__, - name, - wait_for ? "true" : "false"); + log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress called with " + "invalid address", + static_cast(target_sp.get())); + return sb_bp; + } - if (name && target_sp) - { - ProcessAttachInfo attach_info; - attach_info.GetExecutableFile().SetFile(name, false); - attach_info.SetWaitForLaunch(wait_for); - if (listener.IsValid()) - attach_info.SetListener(listener.GetSP()); - - error.SetError (AttachToProcess (attach_info, *target_sp)); - if (error.Success ()) - sb_process.SetSP (target_sp->GetProcessSP ()); - } - else - error.SetErrorString ("SBTarget is invalid"); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + const bool hardware = false; + *sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware); + } - if (log) - log->Printf ("SBTarget(%p)::%s (...) => SBProcess(%p)", - static_cast(target_sp.get()), - __FUNCTION__, - static_cast(sb_process.GetSP().get())); - return sb_process; + if (log) { + SBStream s; + sb_address.GetDescription(s); + log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress (address=%s) => " + "SBBreakpoint(%p)", + static_cast(target_sp.get()), s.GetData(), + static_cast(sb_bp.get())); + } + + return sb_bp; } -lldb::SBProcess -SBTarget::ConnectRemote -( - SBListener &listener, - const char *url, - const char *plugin_name, - SBError& error -) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBProcess sb_process; - ProcessSP process_sp; - TargetSP target_sp(GetSP()); +lldb::SBBreakpoint +SBTarget::BreakpointCreateBySourceRegex(const char *source_regex, + const lldb::SBFileSpec &source_file, + const char *module_name) { + SBFileSpecList module_spec_list; - if (log) - log->Printf ("SBTarget(%p)::ConnectRemote (listener, url=%s, plugin_name=%s, error)...", - static_cast(target_sp.get()), url, plugin_name); + if (module_name && module_name[0]) { + module_spec_list.Append(FileSpec(module_name, false)); + } - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - if (listener.IsValid()) - process_sp = target_sp->CreateProcess (listener.m_opaque_sp, plugin_name, NULL); - else - process_sp = target_sp->CreateProcess (target_sp->GetDebugger().GetListener(), plugin_name, NULL); + SBFileSpecList source_file_list; + if (source_file.IsValid()) { + source_file_list.Append(source_file); + } - if (process_sp) - { - sb_process.SetSP (process_sp); - error.SetError (process_sp->ConnectRemote (NULL, url)); - } - else - { - error.SetErrorString ("unable to create lldb_private::Process"); - } - } - else - { - error.SetErrorString ("SBTarget is invalid"); - } + return BreakpointCreateBySourceRegex(source_regex, module_spec_list, + source_file_list); +} - if (log) - log->Printf ("SBTarget(%p)::ConnectRemote (...) => SBProcess(%p)", - static_cast(target_sp.get()), - static_cast(process_sp.get())); - return sb_process; +lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex( + const char *source_regex, const SBFileSpecList &module_list, + const lldb::SBFileSpecList &source_file_list) { + return BreakpointCreateBySourceRegex(source_regex, module_list, + source_file_list, SBStringList()); } -SBFileSpec -SBTarget::GetExecutable () -{ +lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex( + const char *source_regex, const SBFileSpecList &module_list, + const lldb::SBFileSpecList &source_file_list, + const SBStringList &func_names) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - SBFileSpec exe_file_spec; - TargetSP target_sp(GetSP()); - if (target_sp) - { - Module *exe_module = target_sp->GetExecutableModulePointer(); - if (exe_module) - exe_file_spec.SetFileSpec (exe_module->GetFileSpec()); + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp && source_regex && source_regex[0]) { + std::lock_guard guard(target_sp->GetAPIMutex()); + const bool hardware = false; + const LazyBool move_to_nearest_code = eLazyBoolCalculate; + RegularExpression regexp(source_regex); + std::unordered_set func_names_set; + for (size_t i = 0; i < func_names.GetSize(); i++) { + func_names_set.insert(func_names.GetStringAtIndex(i)); } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - log->Printf ("SBTarget(%p)::GetExecutable () => SBFileSpec(%p)", - static_cast(target_sp.get()), - static_cast(exe_file_spec.get())); - } + *sb_bp = target_sp->CreateSourceRegexBreakpoint( + module_list.get(), source_file_list.get(), func_names_set, regexp, + false, hardware, move_to_nearest_code); + } - return exe_file_spec; -} + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByRegex (source_regex=\"%s\") " + "=> SBBreakpoint(%p)", + static_cast(target_sp.get()), source_regex, + static_cast(sb_bp.get())); -bool -SBTarget::operator == (const SBTarget &rhs) const -{ - return m_opaque_sp.get() == rhs.m_opaque_sp.get(); + return sb_bp; } -bool -SBTarget::operator != (const SBTarget &rhs) const -{ - return m_opaque_sp.get() != rhs.m_opaque_sp.get(); +lldb::SBBreakpoint +SBTarget::BreakpointCreateForException(lldb::LanguageType language, + bool catch_bp, bool throw_bp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_bp; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + const bool hardware = false; + *sb_bp = target_sp->CreateExceptionBreakpoint(language, catch_bp, throw_bp, + hardware); + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointCreateByRegex (Language: %s, catch: " + "%s throw: %s) => SBBreakpoint(%p)", + static_cast(target_sp.get()), + Language::GetNameForLanguageType(language), + catch_bp ? "on" : "off", throw_bp ? "on" : "off", + static_cast(sb_bp.get())); + + return sb_bp; +} + +uint32_t SBTarget::GetNumBreakpoints() const { + TargetSP target_sp(GetSP()); + if (target_sp) { + // The breakpoint list is thread safe, no need to lock + return target_sp->GetBreakpointList().GetSize(); + } + return 0; +} + +SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const { + SBBreakpoint sb_breakpoint; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The breakpoint list is thread safe, no need to lock + *sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx); + } + return sb_breakpoint; +} + +bool SBTarget::BreakpointDelete(break_id_t bp_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + bool result = false; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + result = target_sp->RemoveBreakpointByID(bp_id); + } + + if (log) + log->Printf("SBTarget(%p)::BreakpointDelete (bp_id=%d) => %i", + static_cast(target_sp.get()), + static_cast(bp_id), result); + + return result; +} + +SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBBreakpoint sb_breakpoint; + TargetSP target_sp(GetSP()); + if (target_sp && bp_id != LLDB_INVALID_BREAK_ID) { + std::lock_guard guard(target_sp->GetAPIMutex()); + *sb_breakpoint = target_sp->GetBreakpointByID(bp_id); + } + + if (log) + log->Printf( + "SBTarget(%p)::FindBreakpointByID (bp_id=%d) => SBBreakpoint(%p)", + static_cast(target_sp.get()), static_cast(bp_id), + static_cast(sb_breakpoint.get())); + + return sb_breakpoint; +} + +bool SBTarget::EnableAllBreakpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + target_sp->EnableAllBreakpoints(); + return true; + } + return false; } -lldb::TargetSP -SBTarget::GetSP () const -{ - return m_opaque_sp; +bool SBTarget::DisableAllBreakpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + target_sp->DisableAllBreakpoints(); + return true; + } + return false; } -void -SBTarget::SetSP (const lldb::TargetSP& target_sp) -{ - m_opaque_sp = target_sp; +bool SBTarget::DeleteAllBreakpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + target_sp->RemoveAllBreakpoints(); + return true; + } + return false; +} + +uint32_t SBTarget::GetNumWatchpoints() const { + TargetSP target_sp(GetSP()); + if (target_sp) { + // The watchpoint list is thread safe, no need to lock + return target_sp->GetWatchpointList().GetSize(); + } + return 0; +} + +SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const { + SBWatchpoint sb_watchpoint; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The watchpoint list is thread safe, no need to lock + sb_watchpoint.SetSP(target_sp->GetWatchpointList().GetByIndex(idx)); + } + return sb_watchpoint; +} + +bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + bool result = false; + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + std::unique_lock lock; + target_sp->GetWatchpointList().GetListMutex(lock); + result = target_sp->RemoveWatchpointByID(wp_id); + } + + if (log) + log->Printf("SBTarget(%p)::WatchpointDelete (wp_id=%d) => %i", + static_cast(target_sp.get()), + static_cast(wp_id), result); + + return result; +} + +SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBWatchpoint sb_watchpoint; + lldb::WatchpointSP watchpoint_sp; + TargetSP target_sp(GetSP()); + if (target_sp && wp_id != LLDB_INVALID_WATCH_ID) { + std::lock_guard guard(target_sp->GetAPIMutex()); + std::unique_lock lock; + target_sp->GetWatchpointList().GetListMutex(lock); + watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id); + sb_watchpoint.SetSP(watchpoint_sp); + } + + if (log) + log->Printf( + "SBTarget(%p)::FindWatchpointByID (bp_id=%d) => SBWatchpoint(%p)", + static_cast(target_sp.get()), static_cast(wp_id), + static_cast(watchpoint_sp.get())); + + return sb_watchpoint; +} + +lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size, + bool read, bool write, + SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBWatchpoint sb_watchpoint; + lldb::WatchpointSP watchpoint_sp; + TargetSP target_sp(GetSP()); + if (target_sp && (read || write) && addr != LLDB_INVALID_ADDRESS && + size > 0) { + std::lock_guard guard(target_sp->GetAPIMutex()); + uint32_t watch_type = 0; + if (read) + watch_type |= LLDB_WATCH_TYPE_READ; + if (write) + watch_type |= LLDB_WATCH_TYPE_WRITE; + if (watch_type == 0) { + error.SetErrorString( + "Can't create a watchpoint that is neither read nor write."); + return sb_watchpoint; + } + + // Target::CreateWatchpoint() is thread safe. + Error cw_error; + // This API doesn't take in a type, so we can't figure out what it is. + CompilerType *type = NULL; + watchpoint_sp = + target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error); + error.SetError(cw_error); + sb_watchpoint.SetSP(watchpoint_sp); + } + + if (log) + log->Printf("SBTarget(%p)::WatchAddress (addr=0x%" PRIx64 + ", 0x%u) => SBWatchpoint(%p)", + static_cast(target_sp.get()), addr, + static_cast(size), + static_cast(watchpoint_sp.get())); + + return sb_watchpoint; +} + +bool SBTarget::EnableAllWatchpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + std::unique_lock lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->EnableAllWatchpoints(); + return true; + } + return false; } -lldb::SBAddress -SBTarget::ResolveLoadAddress (lldb::addr_t vm_addr) -{ - lldb::SBAddress sb_addr; - Address &addr = sb_addr.ref(); - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - if (target_sp->ResolveLoadAddress (vm_addr, addr)) - return sb_addr; - } +bool SBTarget::DisableAllWatchpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + std::unique_lock lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->DisableAllWatchpoints(); + return true; + } + return false; +} + +SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr, + SBType type) { + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) { + lldb::addr_t load_addr(addr.GetLoadAddress(*this)); + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + CompilerType ast_type(type.GetSP()->GetCompilerType(true)); + new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBTarget(%p)::CreateValueFromAddress => \"%s\"", + static_cast(m_opaque_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBTarget(%p)::CreateValueFromAddress => NULL", + static_cast(m_opaque_sp.get())); + } + return sb_value; +} + +lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data, + lldb::SBType type) { + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && data.IsValid() && type.IsValid()) { + DataExtractorSP extractor(*data); + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + CompilerType ast_type(type.GetSP()->GetCompilerType(true)); + new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBTarget(%p)::CreateValueFromData => \"%s\"", + static_cast(m_opaque_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBTarget(%p)::CreateValueFromData => NULL", + static_cast(m_opaque_sp.get())); + } + return sb_value; +} + +lldb::SBValue SBTarget::CreateValueFromExpression(const char *name, + const char *expr) { + SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + if (IsValid() && name && *name && expr && *expr) { + ExecutionContext exe_ctx( + ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false))); + new_value_sp = + ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx); + } + sb_value.SetSP(new_value_sp); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBTarget(%p)::CreateValueFromExpression => \"%s\"", + static_cast(m_opaque_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBTarget(%p)::CreateValueFromExpression => NULL", + static_cast(m_opaque_sp.get())); + } + return sb_value; +} + +bool SBTarget::DeleteAllWatchpoints() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::lock_guard guard(target_sp->GetAPIMutex()); + std::unique_lock lock; + target_sp->GetWatchpointList().GetListMutex(lock); + target_sp->RemoveAllWatchpoints(); + return true; + } + return false; +} - // We have a load address that isn't in a section, just return an address - // with the offset filled in (the address) and the section set to NULL - addr.SetRawAddress(vm_addr); - return sb_addr; +lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, + const char *uuid_cstr) { + return AddModule(path, triple, uuid_cstr, NULL); } -lldb::SBAddress -SBTarget::ResolveFileAddress (lldb::addr_t file_addr) -{ - lldb::SBAddress sb_addr; - Address &addr = sb_addr.ref(); - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - if (target_sp->ResolveFileAddress (file_addr, addr)) - return sb_addr; - } +lldb::SBModule SBTarget::AddModule(const char *path, const char *triple, + const char *uuid_cstr, const char *symfile) { + lldb::SBModule sb_module; + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleSpec module_spec; + if (path) + module_spec.GetFileSpec().SetFile(path, false); + + if (uuid_cstr) + module_spec.GetUUID().SetFromCString(uuid_cstr); - addr.SetRawAddress(file_addr); - return sb_addr; + if (triple) + module_spec.GetArchitecture().SetTriple(triple, + target_sp->GetPlatform().get()); + else + module_spec.GetArchitecture() = target_sp->GetArchitecture(); + + if (symfile) + module_spec.GetSymbolFileSpec().SetFile(symfile, false); + + sb_module.SetSP(target_sp->GetSharedModule(module_spec)); + } + return sb_module; } -lldb::SBAddress -SBTarget::ResolvePastLoadAddress (uint32_t stop_id, lldb::addr_t vm_addr) -{ - lldb::SBAddress sb_addr; - Address &addr = sb_addr.ref(); - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - if (target_sp->ResolveLoadAddress (vm_addr, addr)) - return sb_addr; - } - - // We have a load address that isn't in a section, just return an address - // with the offset filled in (the address) and the section set to NULL - addr.SetRawAddress(vm_addr); - return sb_addr; +lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) { + lldb::SBModule sb_module; + TargetSP target_sp(GetSP()); + if (target_sp) + sb_module.SetSP(target_sp->GetSharedModule(*module_spec.m_opaque_ap)); + return sb_module; } -SBSymbolContext -SBTarget::ResolveSymbolContextForAddress (const SBAddress& addr, - uint32_t resolve_scope) -{ - SBSymbolContext sc; - if (addr.IsValid()) - { - TargetSP target_sp(GetSP()); - if (target_sp) - target_sp->GetImages().ResolveSymbolContextForAddress (addr.ref(), resolve_scope, sc.ref()); - } - return sc; +bool SBTarget::AddModule(lldb::SBModule &module) { + TargetSP target_sp(GetSP()); + if (target_sp) { + target_sp->GetImages().AppendIfNeeded(module.GetSP()); + return true; + } + return false; } -size_t -SBTarget::ReadMemory (const SBAddress addr, - void *buf, - size_t size, - lldb::SBError &error) -{ - SBError sb_error; - size_t bytes_read = 0; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - bytes_read = target_sp->ReadMemory(addr.ref(), false, buf, size, sb_error.ref()); - } - else - { - sb_error.SetErrorString("invalid target"); - } +uint32_t SBTarget::GetNumModules() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + uint32_t num = 0; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The module list is thread safe, no need to lock + num = target_sp->GetImages().GetSize(); + } + + if (log) + log->Printf("SBTarget(%p)::GetNumModules () => %d", + static_cast(target_sp.get()), num); - return bytes_read; + return num; } -SBBreakpoint -SBTarget::BreakpointCreateByLocation (const char *file, - uint32_t line) -{ - return SBBreakpoint(BreakpointCreateByLocation (SBFileSpec (file, false), line)); +void SBTarget::Clear() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + if (log) + log->Printf("SBTarget(%p)::Clear ()", + static_cast(m_opaque_sp.get())); + + m_opaque_sp.reset(); } -SBBreakpoint -SBTarget::BreakpointCreateByLocation (const SBFileSpec &sb_file_spec, - uint32_t line) -{ - return BreakpointCreateByLocation(sb_file_spec, line, 0); +SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) { + SBModule sb_module; + TargetSP target_sp(GetSP()); + if (target_sp && sb_file_spec.IsValid()) { + ModuleSpec module_spec(*sb_file_spec); + // The module list is thread safe, no need to lock + sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec)); + } + return sb_module; } -SBBreakpoint -SBTarget::BreakpointCreateByLocation (const SBFileSpec &sb_file_spec, - uint32_t line, - lldb::addr_t offset) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +lldb::ByteOrder SBTarget::GetByteOrder() { + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetArchitecture().GetByteOrder(); + return eByteOrderInvalid; +} - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp && line != 0) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - - const LazyBool check_inlines = eLazyBoolCalculate; - const LazyBool skip_prologue = eLazyBoolCalculate; - const bool internal = false; - const bool hardware = false; - const LazyBool move_to_nearest_code = eLazyBoolCalculate; - *sb_bp = target_sp->CreateBreakpoint (NULL, - *sb_file_spec, - line, - offset, - check_inlines, - skip_prologue, - internal, - hardware, - move_to_nearest_code); - } +const char *SBTarget::GetTriple() { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::string triple(target_sp->GetArchitecture().GetTriple().str()); + // Unique the string so we don't run into ownership issues since + // the const strings put the string into the string pool once and + // the strings never comes out + ConstString const_triple(triple.c_str()); + return const_triple.GetCString(); + } + return NULL; +} - if (log) - { - SBStream sstr; - sb_bp.GetDescription (sstr); - char path[PATH_MAX]; - sb_file_spec->GetPath (path, sizeof(path)); - log->Printf ("SBTarget(%p)::BreakpointCreateByLocation ( %s:%u ) => SBBreakpoint(%p): %s", - static_cast(target_sp.get()), path, line, - static_cast(sb_bp.get()), sstr.GetData()); - } +uint32_t SBTarget::GetDataByteSize() { + TargetSP target_sp(GetSP()); + if (target_sp) { + return target_sp->GetArchitecture().GetDataByteSize(); + } + return 0; +} - return sb_bp; +uint32_t SBTarget::GetCodeByteSize() { + TargetSP target_sp(GetSP()); + if (target_sp) { + return target_sp->GetArchitecture().GetCodeByteSize(); + } + return 0; } -SBBreakpoint -SBTarget::BreakpointCreateByName (const char *symbol_name, - const char *module_name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +uint32_t SBTarget::GetAddressByteSize() { + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetArchitecture().GetAddressByteSize(); + return sizeof(void *); +} - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp.get()) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - - const bool internal = false; - const bool hardware = false; - const LazyBool skip_prologue = eLazyBoolCalculate; - const lldb::addr_t offset = 0; - if (module_name && module_name[0]) - { - FileSpecList module_spec_list; - module_spec_list.Append (FileSpec (module_name, false)); - *sb_bp = target_sp->CreateBreakpoint (&module_spec_list, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); +SBModule SBTarget::GetModuleAtIndex(uint32_t idx) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBModule sb_module; + ModuleSP module_sp; + TargetSP target_sp(GetSP()); + if (target_sp) { + // The module list is thread safe, no need to lock + module_sp = target_sp->GetImages().GetModuleAtIndex(idx); + sb_module.SetSP(module_sp); + } + + if (log) + log->Printf("SBTarget(%p)::GetModuleAtIndex (idx=%d) => SBModule(%p)", + static_cast(target_sp.get()), idx, + static_cast(module_sp.get())); + + return sb_module; +} + +bool SBTarget::RemoveModule(lldb::SBModule module) { + TargetSP target_sp(GetSP()); + if (target_sp) + return target_sp->GetImages().Remove(module.GetSP()); + return false; +} + +SBBroadcaster SBTarget::GetBroadcaster() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + TargetSP target_sp(GetSP()); + SBBroadcaster broadcaster(target_sp.get(), false); + + if (log) + log->Printf("SBTarget(%p)::GetBroadcaster () => SBBroadcaster(%p)", + static_cast(target_sp.get()), + static_cast(broadcaster.get())); + + return broadcaster; +} + +bool SBTarget::GetDescription(SBStream &description, + lldb::DescriptionLevel description_level) { + Stream &strm = description.ref(); + + TargetSP target_sp(GetSP()); + if (target_sp) { + target_sp->Dump(&strm, description_level); + } else + strm.PutCString("No value"); + + return true; +} + +lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name, + uint32_t name_type_mask) { + lldb::SBSymbolContextList sb_sc_list; + if (name && name[0]) { + TargetSP target_sp(GetSP()); + if (target_sp) { + const bool symbols_ok = true; + const bool inlines_ok = true; + const bool append = true; + target_sp->GetImages().FindFunctions(ConstString(name), name_type_mask, + symbols_ok, inlines_ok, append, + *sb_sc_list); + } + } + return sb_sc_list; +} + +lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name, + uint32_t max_matches, + MatchType matchtype) { + lldb::SBSymbolContextList sb_sc_list; + if (name && name[0]) { + TargetSP target_sp(GetSP()); + if (target_sp) { + std::string regexstr; + switch (matchtype) { + case eMatchTypeRegex: + target_sp->GetImages().FindFunctions(RegularExpression(name), true, + true, true, *sb_sc_list); + break; + case eMatchTypeStartsWith: + regexstr = llvm::Regex::escape(name) + ".*"; + target_sp->GetImages().FindFunctions( + RegularExpression(regexstr.c_str()), true, true, true, *sb_sc_list); + break; + default: + target_sp->GetImages().FindFunctions(ConstString(name), + eFunctionNameTypeAny, true, true, + true, *sb_sc_list); + break; + } + } + } + return sb_sc_list; +} + +lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) { + TargetSP target_sp(GetSP()); + if (typename_cstr && typename_cstr[0] && target_sp) { + ConstString const_typename(typename_cstr); + SymbolContext sc; + const bool exact_match = false; + + const ModuleList &module_list = target_sp->GetImages(); + size_t count = module_list.GetSize(); + for (size_t idx = 0; idx < count; idx++) { + ModuleSP module_sp(module_list.GetModuleAtIndex(idx)); + if (module_sp) { + TypeSP type_sp( + module_sp->FindFirstType(sc, const_typename, exact_match)); + if (type_sp) + return SBType(type_sp); + } + } + + // Didn't find the type in the symbols; try the Objective-C runtime + // if one is installed + + ProcessSP process_sp(target_sp->GetProcessSP()); + + if (process_sp) { + ObjCLanguageRuntime *objc_language_runtime = + process_sp->GetObjCLanguageRuntime(); + + if (objc_language_runtime) { + DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); + + if (objc_decl_vendor) { + std::vector decls; + + if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) { + if (CompilerType type = ClangASTContext::GetTypeForDecl(decls[0])) { + return SBType(type); + } + } } - else - { - *sb_bp = target_sp->CreateBreakpoint (NULL, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); + } + } + + // No matches, search for basic typename matches + ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); + if (clang_ast) + return SBType(ClangASTContext::GetBasicType(clang_ast->getASTContext(), + const_typename)); + } + return SBType(); +} + +SBType SBTarget::GetBasicType(lldb::BasicType type) { + TargetSP target_sp(GetSP()); + if (target_sp) { + ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); + if (clang_ast) + return SBType( + ClangASTContext::GetBasicType(clang_ast->getASTContext(), type)); + } + return SBType(); +} + +lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) { + SBTypeList sb_type_list; + TargetSP target_sp(GetSP()); + if (typename_cstr && typename_cstr[0] && target_sp) { + ModuleList &images = target_sp->GetImages(); + ConstString const_typename(typename_cstr); + bool exact_match = false; + SymbolContext sc; + TypeList type_list; + llvm::DenseSet searched_symbol_files; + uint32_t num_matches = + images.FindTypes(sc, const_typename, exact_match, UINT32_MAX, + searched_symbol_files, type_list); + + if (num_matches > 0) { + for (size_t idx = 0; idx < num_matches; idx++) { + TypeSP type_sp(type_list.GetTypeAtIndex(idx)); + if (type_sp) + sb_type_list.Append(SBType(type_sp)); + } + } + + // Try the Objective-C runtime if one is installed + + ProcessSP process_sp(target_sp->GetProcessSP()); + + if (process_sp) { + ObjCLanguageRuntime *objc_language_runtime = + process_sp->GetObjCLanguageRuntime(); + + if (objc_language_runtime) { + DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); + + if (objc_decl_vendor) { + std::vector decls; + + if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) { + for (clang::NamedDecl *decl : decls) { + if (CompilerType type = ClangASTContext::GetTypeForDecl(decl)) { + sb_type_list.Append(SBType(type)); + } + } + } } - } + } + } - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", module=\"%s\") => SBBreakpoint(%p)", - static_cast(target_sp.get()), symbol_name, - module_name, static_cast(sb_bp.get())); + if (sb_type_list.GetSize() == 0) { + // No matches, search for basic typename matches + ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); + if (clang_ast) + sb_type_list.Append(SBType(ClangASTContext::GetBasicType( + clang_ast->getASTContext(), const_typename))); + } + } + return sb_type_list; +} + +SBValueList SBTarget::FindGlobalVariables(const char *name, + uint32_t max_matches) { + SBValueList sb_value_list; + + TargetSP target_sp(GetSP()); + if (name && target_sp) { + VariableList variable_list; + const bool append = true; + const uint32_t match_count = target_sp->GetImages().FindGlobalVariables( + ConstString(name), append, max_matches, variable_list); + + if (match_count > 0) { + ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); + if (exe_scope == NULL) + exe_scope = target_sp.get(); + for (uint32_t i = 0; i < match_count; ++i) { + lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create( + exe_scope, variable_list.GetVariableAtIndex(i))); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } + } + } + + return sb_value_list; +} + +SBValueList SBTarget::FindGlobalVariables(const char *name, + uint32_t max_matches, + MatchType matchtype) { + SBValueList sb_value_list; + + TargetSP target_sp(GetSP()); + if (name && target_sp) { + VariableList variable_list; + const bool append = true; + + std::string regexstr; + uint32_t match_count; + switch (matchtype) { + case eMatchTypeNormal: + match_count = target_sp->GetImages().FindGlobalVariables( + ConstString(name), append, max_matches, variable_list); + break; + case eMatchTypeRegex: + match_count = target_sp->GetImages().FindGlobalVariables( + RegularExpression(name), append, max_matches, variable_list); + break; + case eMatchTypeStartsWith: + regexstr = llvm::Regex::escape(name) + ".*"; + match_count = target_sp->GetImages().FindGlobalVariables( + RegularExpression(regexstr.c_str()), append, max_matches, + variable_list); + break; + } + + if (match_count > 0) { + ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); + if (exe_scope == NULL) + exe_scope = target_sp.get(); + for (uint32_t i = 0; i < match_count; ++i) { + lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create( + exe_scope, variable_list.GetVariableAtIndex(i))); + if (valobj_sp) + sb_value_list.Append(SBValue(valobj_sp)); + } + } + } + + return sb_value_list; +} + +lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) { + SBValueList sb_value_list(FindGlobalVariables(name, 1)); + if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0) + return sb_value_list.GetValueAtIndex(0); + return SBValue(); +} + +SBSourceManager SBTarget::GetSourceManager() { + SBSourceManager source_manager(*this); + return source_manager; +} + +lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, + uint32_t count) { + return ReadInstructions(base_addr, count, NULL); +} + +lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, + uint32_t count, + const char *flavor_string) { + SBInstructionList sb_instructions; + + TargetSP target_sp(GetSP()); + if (target_sp) { + Address *addr_ptr = base_addr.get(); + + if (addr_ptr) { + DataBufferHeap data( + target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0); + bool prefer_file_cache = false; + lldb_private::Error error; + lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; + const size_t bytes_read = + target_sp->ReadMemory(*addr_ptr, prefer_file_cache, data.GetBytes(), + data.GetByteSize(), error, &load_addr); + const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS; + sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( + target_sp->GetArchitecture(), NULL, flavor_string, *addr_ptr, + data.GetBytes(), bytes_read, count, data_from_file)); + } + } + + return sb_instructions; +} - return sb_bp; +lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr, + const void *buf, + size_t size) { + return GetInstructionsWithFlavor(base_addr, NULL, buf, size); } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByName (const char *symbol_name, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - uint32_t name_type_mask = eFunctionNameTypeAuto; - return BreakpointCreateByName (symbol_name, name_type_mask, eLanguageTypeUnknown, module_list, comp_unit_list); -} +lldb::SBInstructionList +SBTarget::GetInstructionsWithFlavor(lldb::SBAddress base_addr, + const char *flavor_string, const void *buf, + size_t size) { + SBInstructionList sb_instructions; -lldb::SBBreakpoint -SBTarget::BreakpointCreateByName (const char *symbol_name, - uint32_t name_type_mask, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - return BreakpointCreateByName (symbol_name, name_type_mask, eLanguageTypeUnknown, module_list, comp_unit_list); -} + TargetSP target_sp(GetSP()); + if (target_sp) { + Address addr; -lldb::SBBreakpoint -SBTarget::BreakpointCreateByName (const char *symbol_name, - uint32_t name_type_mask, - LanguageType symbol_language, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + if (base_addr.get()) + addr = *base_addr.get(); - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp && symbol_name && symbol_name[0]) - { - const bool internal = false; - const bool hardware = false; - const LazyBool skip_prologue = eLazyBoolCalculate; - std::lock_guard guard(target_sp->GetAPIMutex()); - *sb_bp = target_sp->CreateBreakpoint (module_list.get(), - comp_unit_list.get(), - symbol_name, - name_type_mask, - symbol_language, - 0, - skip_prologue, - internal, - hardware); - } + const bool data_from_file = true; - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", name_type: %d) => SBBreakpoint(%p)", - static_cast(target_sp.get()), symbol_name, - name_type_mask, static_cast(sb_bp.get())); + sb_instructions.SetDisassembler(Disassembler::DisassembleBytes( + target_sp->GetArchitecture(), NULL, flavor_string, addr, buf, size, + UINT32_MAX, data_from_file)); + } - return sb_bp; + return sb_instructions; } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByNames (const char *symbol_names[], - uint32_t num_names, - uint32_t name_type_mask, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, eLanguageTypeUnknown, module_list, comp_unit_list); +lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr, + const void *buf, + size_t size) { + return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), NULL, buf, + size); } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByNames (const char *symbol_names[], - uint32_t num_names, - uint32_t name_type_mask, - LanguageType symbol_language, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - return BreakpointCreateByNames(symbol_names, num_names, name_type_mask, eLanguageTypeUnknown, 0, module_list, comp_unit_list); +lldb::SBInstructionList +SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr, + const char *flavor_string, const void *buf, + size_t size) { + return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), flavor_string, + buf, size); +} + +SBError SBTarget::SetSectionLoadAddress(lldb::SBSection section, + lldb::addr_t section_base_addr) { + SBError sb_error; + TargetSP target_sp(GetSP()); + if (target_sp) { + if (!section.IsValid()) { + sb_error.SetErrorStringWithFormat("invalid section"); + } else { + SectionSP section_sp(section.GetSP()); + if (section_sp) { + if (section_sp->IsThreadSpecific()) { + sb_error.SetErrorString( + "thread specific sections are not yet supported"); + } else { + ProcessSP process_sp(target_sp->GetProcessSP()); + if (target_sp->SetSectionLoadAddress(section_sp, section_base_addr)) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidLoad(module_list); + } + // Flush info in the process (stack frames, etc) + if (process_sp) + process_sp->Flush(); + } + } + } + } + } else { + sb_error.SetErrorString("invalid target"); + } + return sb_error; } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByNames (const char *symbol_names[], - uint32_t num_names, - uint32_t name_type_mask, - LanguageType symbol_language, - lldb::addr_t offset, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp && num_names > 0) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - const bool internal = false; - const bool hardware = false; - const LazyBool skip_prologue = eLazyBoolCalculate; - *sb_bp = target_sp->CreateBreakpoint (module_list.get(), - comp_unit_list.get(), - symbol_names, - num_names, - name_type_mask, - symbol_language, - offset, - skip_prologue, - internal, - hardware); - } +SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) { + SBError sb_error; - if (log) - { - log->Printf ("SBTarget(%p)::BreakpointCreateByName (symbols={", - static_cast(target_sp.get())); - for (uint32_t i = 0 ; i < num_names; i++) - { - char sep; - if (i < num_names - 1) - sep = ','; - else - sep = '}'; - if (symbol_names[i] != NULL) - log->Printf ("\"%s\"%c ", symbol_names[i], sep); - else - log->Printf ("\"\"%c ", sep); + TargetSP target_sp(GetSP()); + if (target_sp) { + if (!section.IsValid()) { + sb_error.SetErrorStringWithFormat("invalid section"); + } else { + SectionSP section_sp(section.GetSP()); + if (section_sp) { + ProcessSP process_sp(target_sp->GetProcessSP()); + if (target_sp->SetSectionUnloaded(section_sp)) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidUnload(module_list, false); + } + // Flush info in the process (stack frames, etc) + if (process_sp) + process_sp->Flush(); + } + } else { + sb_error.SetErrorStringWithFormat("invalid section"); + } + } + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; +} + +SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module, + int64_t slide_offset) { + SBError sb_error; + + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleSP module_sp(module.GetSP()); + if (module_sp) { + bool changed = false; + if (module_sp->SetLoadAddress(*target_sp, slide_offset, true, changed)) { + // The load was successful, make sure that at least some sections + // changed before we notify that our module was loaded. + if (changed) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidLoad(module_list); + // Flush info in the process (stack frames, etc) + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + process_sp->Flush(); + } + } + } else { + sb_error.SetErrorStringWithFormat("invalid module"); + } + + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; +} + +SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) { + SBError sb_error; + + char path[PATH_MAX]; + TargetSP target_sp(GetSP()); + if (target_sp) { + ModuleSP module_sp(module.GetSP()); + if (module_sp) { + ObjectFile *objfile = module_sp->GetObjectFile(); + if (objfile) { + SectionList *section_list = objfile->GetSectionList(); + if (section_list) { + ProcessSP process_sp(target_sp->GetProcessSP()); + + bool changed = false; + const size_t num_sections = section_list->GetSize(); + for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) { + SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); + if (section_sp) + changed |= target_sp->SetSectionUnloaded(section_sp); + } + if (changed) { + ModuleList module_list; + module_list.Append(module_sp); + target_sp->ModulesDidUnload(module_list, false); + // Flush info in the process (stack frames, etc) + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + process_sp->Flush(); + } + } else { + module_sp->GetFileSpec().GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("no sections in object file '%s'", + path); } - log->Printf ("name_type: %d) => SBBreakpoint(%p)", name_type_mask, - static_cast(sb_bp.get())); + } else { + module_sp->GetFileSpec().GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("no object file for module '%s'", + path); + } + } else { + sb_error.SetErrorStringWithFormat("invalid module"); } - - return sb_bp; + } else { + sb_error.SetErrorStringWithFormat("invalid target"); + } + return sb_error; } -SBBreakpoint -SBTarget::BreakpointCreateByRegex (const char *symbol_name_regex, - const char *module_name) -{ - SBFileSpecList module_spec_list; - SBFileSpecList comp_unit_list; - if (module_name && module_name[0]) - { - module_spec_list.Append (FileSpec (module_name, false)); - +lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name, + lldb::SymbolType symbol_type) { + SBSymbolContextList sb_sc_list; + if (name && name[0]) { + TargetSP target_sp(GetSP()); + if (target_sp) { + bool append = true; + target_sp->GetImages().FindSymbolsWithNameAndType( + ConstString(name), symbol_type, *sb_sc_list, append); } - return BreakpointCreateByRegex (symbol_name_regex, eLanguageTypeUnknown, module_spec_list, comp_unit_list); + } + return sb_sc_list; } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByRegex (const char *symbol_name_regex, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - return BreakpointCreateByRegex (symbol_name_regex, eLanguageTypeUnknown, module_list, comp_unit_list); +lldb::SBValue SBTarget::EvaluateExpression(const char *expr) { + TargetSP target_sp(GetSP()); + if (!target_sp) + return SBValue(); + + SBExpressionOptions options; + lldb::DynamicValueType fetch_dynamic_value = + target_sp->GetPreferDynamicValue(); + options.SetFetchDynamicValue(fetch_dynamic_value); + options.SetUnwindOnError(true); + return EvaluateExpression(expr, options); } -lldb::SBBreakpoint -SBTarget::BreakpointCreateByRegex (const char *symbol_name_regex, - LanguageType symbol_language, - const SBFileSpecList &module_list, - const SBFileSpecList &comp_unit_list) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp && symbol_name_regex && symbol_name_regex[0]) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - RegularExpression regexp(symbol_name_regex); - const bool internal = false; - const bool hardware = false; - const LazyBool skip_prologue = eLazyBoolCalculate; - - *sb_bp = target_sp->CreateFuncRegexBreakpoint (module_list.get(), comp_unit_list.get(), regexp, symbol_language, skip_prologue, internal, hardware); - } - - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByRegex (symbol_regex=\"%s\") => SBBreakpoint(%p)", - static_cast(target_sp.get()), symbol_name_regex, - static_cast(sb_bp.get())); - - return sb_bp; -} - -SBBreakpoint -SBTarget::BreakpointCreateByAddress (addr_t address) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - const bool hardware = false; - *sb_bp = target_sp->CreateBreakpoint (address, false, hardware); - } - - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByAddress (address=%" PRIu64 ") => SBBreakpoint(%p)", - static_cast(target_sp.get()), - static_cast(address), - static_cast(sb_bp.get())); - - return sb_bp; -} - -SBBreakpoint -SBTarget::BreakpointCreateBySBAddress (SBAddress &sb_address) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (!sb_address.IsValid()) - { - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateBySBAddress called with invalid address", - static_cast(target_sp.get())); - return sb_bp; - } - - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - const bool hardware = false; - *sb_bp = target_sp->CreateBreakpoint (sb_address.ref(), false, hardware); - } - - if (log) - { - SBStream s; - sb_address.GetDescription(s); - log->Printf ("SBTarget(%p)::BreakpointCreateBySBAddress (address=%s) => SBBreakpoint(%p)", - static_cast(target_sp.get()), - s.GetData(), - static_cast(sb_bp.get())); - } - - return sb_bp; -} - -lldb::SBBreakpoint -SBTarget::BreakpointCreateBySourceRegex (const char *source_regex, - const lldb::SBFileSpec &source_file, - const char *module_name) -{ - SBFileSpecList module_spec_list; - - if (module_name && module_name[0]) - { - module_spec_list.Append (FileSpec (module_name, false)); - } - - SBFileSpecList source_file_list; - if (source_file.IsValid()) - { - source_file_list.Append(source_file); - } - - return BreakpointCreateBySourceRegex (source_regex, module_spec_list, source_file_list); - -} - -lldb::SBBreakpoint -SBTarget::BreakpointCreateBySourceRegex (const char *source_regex, - const SBFileSpecList &module_list, - const lldb::SBFileSpecList &source_file_list) -{ - return BreakpointCreateBySourceRegex(source_regex, module_list, source_file_list, SBStringList()); -} - -lldb::SBBreakpoint -SBTarget::BreakpointCreateBySourceRegex (const char *source_regex, - const SBFileSpecList &module_list, - const lldb::SBFileSpecList &source_file_list, - const SBStringList &func_names) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp && source_regex && source_regex[0]) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - const bool hardware = false; - const LazyBool move_to_nearest_code = eLazyBoolCalculate; - RegularExpression regexp(source_regex); - std::unordered_set func_names_set; - for (size_t i = 0; i < func_names.GetSize(); i++) - { - func_names_set.insert(func_names.GetStringAtIndex(i)); - } - - *sb_bp = target_sp->CreateSourceRegexBreakpoint (module_list.get(), - source_file_list.get(), - func_names_set, - regexp, - false, - hardware, - move_to_nearest_code); - } - - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByRegex (source_regex=\"%s\") => SBBreakpoint(%p)", - static_cast(target_sp.get()), source_regex, - static_cast(sb_bp.get())); - - return sb_bp; -} - -lldb::SBBreakpoint -SBTarget::BreakpointCreateForException (lldb::LanguageType language, - bool catch_bp, - bool throw_bp) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_bp; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - const bool hardware = false; - *sb_bp = target_sp->CreateExceptionBreakpoint (language, catch_bp, throw_bp, hardware); - } - - if (log) - log->Printf ("SBTarget(%p)::BreakpointCreateByRegex (Language: %s, catch: %s throw: %s) => SBBreakpoint(%p)", - static_cast(target_sp.get()), - Language::GetNameForLanguageType(language), - catch_bp ? "on" : "off", throw_bp ? "on" : "off", - static_cast(sb_bp.get())); - - return sb_bp; -} - -uint32_t -SBTarget::GetNumBreakpoints () const -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The breakpoint list is thread safe, no need to lock - return target_sp->GetBreakpointList().GetSize(); - } - return 0; -} - -SBBreakpoint -SBTarget::GetBreakpointAtIndex (uint32_t idx) const -{ - SBBreakpoint sb_breakpoint; - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The breakpoint list is thread safe, no need to lock - *sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx); - } - return sb_breakpoint; -} - -bool -SBTarget::BreakpointDelete (break_id_t bp_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - bool result = false; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - result = target_sp->RemoveBreakpointByID (bp_id); - } - - if (log) - log->Printf ("SBTarget(%p)::BreakpointDelete (bp_id=%d) => %i", - static_cast(target_sp.get()), - static_cast(bp_id), result); - - return result; -} - -SBBreakpoint -SBTarget::FindBreakpointByID (break_id_t bp_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBBreakpoint sb_breakpoint; - TargetSP target_sp(GetSP()); - if (target_sp && bp_id != LLDB_INVALID_BREAK_ID) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - *sb_breakpoint = target_sp->GetBreakpointByID (bp_id); - } - - if (log) - log->Printf ("SBTarget(%p)::FindBreakpointByID (bp_id=%d) => SBBreakpoint(%p)", - static_cast(target_sp.get()), - static_cast(bp_id), - static_cast(sb_breakpoint.get())); - - return sb_breakpoint; -} - -bool -SBTarget::EnableAllBreakpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - target_sp->EnableAllBreakpoints (); - return true; - } - return false; -} - -bool -SBTarget::DisableAllBreakpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - target_sp->DisableAllBreakpoints (); - return true; - } - return false; -} - -bool -SBTarget::DeleteAllBreakpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - target_sp->RemoveAllBreakpoints (); - return true; - } - return false; -} - -uint32_t -SBTarget::GetNumWatchpoints () const -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The watchpoint list is thread safe, no need to lock - return target_sp->GetWatchpointList().GetSize(); - } - return 0; -} - -SBWatchpoint -SBTarget::GetWatchpointAtIndex (uint32_t idx) const -{ - SBWatchpoint sb_watchpoint; - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The watchpoint list is thread safe, no need to lock - sb_watchpoint.SetSP (target_sp->GetWatchpointList().GetByIndex(idx)); - } - return sb_watchpoint; -} - -bool -SBTarget::DeleteWatchpoint (watch_id_t wp_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - bool result = false; - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - std::unique_lock lock; - target_sp->GetWatchpointList().GetListMutex(lock); - result = target_sp->RemoveWatchpointByID (wp_id); - } - - if (log) - log->Printf ("SBTarget(%p)::WatchpointDelete (wp_id=%d) => %i", - static_cast(target_sp.get()), - static_cast(wp_id), result); - - return result; -} - -SBWatchpoint -SBTarget::FindWatchpointByID (lldb::watch_id_t wp_id) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBWatchpoint sb_watchpoint; - lldb::WatchpointSP watchpoint_sp; - TargetSP target_sp(GetSP()); - if (target_sp && wp_id != LLDB_INVALID_WATCH_ID) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - std::unique_lock lock; - target_sp->GetWatchpointList().GetListMutex(lock); - watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id); - sb_watchpoint.SetSP (watchpoint_sp); - } - - if (log) - log->Printf ("SBTarget(%p)::FindWatchpointByID (bp_id=%d) => SBWatchpoint(%p)", - static_cast(target_sp.get()), - static_cast(wp_id), - static_cast(watchpoint_sp.get())); - - return sb_watchpoint; -} - -lldb::SBWatchpoint -SBTarget::WatchAddress (lldb::addr_t addr, size_t size, bool read, bool write, SBError &error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBWatchpoint sb_watchpoint; - lldb::WatchpointSP watchpoint_sp; - TargetSP target_sp(GetSP()); - if (target_sp && (read || write) && addr != LLDB_INVALID_ADDRESS && size > 0) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - uint32_t watch_type = 0; - if (read) - watch_type |= LLDB_WATCH_TYPE_READ; - if (write) - watch_type |= LLDB_WATCH_TYPE_WRITE; - if (watch_type == 0) - { - error.SetErrorString("Can't create a watchpoint that is neither read nor write."); - return sb_watchpoint; - } - - // Target::CreateWatchpoint() is thread safe. - Error cw_error; - // This API doesn't take in a type, so we can't figure out what it is. - CompilerType *type = NULL; - watchpoint_sp = target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error); - error.SetError(cw_error); - sb_watchpoint.SetSP (watchpoint_sp); - } - - if (log) - log->Printf ("SBTarget(%p)::WatchAddress (addr=0x%" PRIx64 ", 0x%u) => SBWatchpoint(%p)", - static_cast(target_sp.get()), addr, - static_cast(size), - static_cast(watchpoint_sp.get())); - - return sb_watchpoint; -} - -bool -SBTarget::EnableAllWatchpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - std::unique_lock lock; - target_sp->GetWatchpointList().GetListMutex(lock); - target_sp->EnableAllWatchpoints (); - return true; - } - return false; -} - -bool -SBTarget::DisableAllWatchpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - std::unique_lock lock; - target_sp->GetWatchpointList().GetListMutex(lock); - target_sp->DisableAllWatchpoints (); - return true; - } - return false; -} - -SBValue -SBTarget::CreateValueFromAddress (const char *name, SBAddress addr, SBType type) -{ - SBValue sb_value; - lldb::ValueObjectSP new_value_sp; - if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) - { - lldb::addr_t load_addr(addr.GetLoadAddress(*this)); - ExecutionContext exe_ctx (ExecutionContextRef(ExecutionContext(m_opaque_sp.get(),false))); - CompilerType ast_type(type.GetSP()->GetCompilerType(true)); - new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr, exe_ctx, ast_type); - } - sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBTarget(%p)::CreateValueFromAddress => \"%s\"", - static_cast(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBTarget(%p)::CreateValueFromAddress => NULL", - static_cast(m_opaque_sp.get())); - } - return sb_value; -} - -lldb::SBValue -SBTarget::CreateValueFromData (const char *name, lldb::SBData data, lldb::SBType type) -{ - SBValue sb_value; - lldb::ValueObjectSP new_value_sp; - if (IsValid() && name && *name && data.IsValid() && type.IsValid()) - { - DataExtractorSP extractor(*data); - ExecutionContext exe_ctx (ExecutionContextRef(ExecutionContext(m_opaque_sp.get(),false))); - CompilerType ast_type(type.GetSP()->GetCompilerType(true)); - new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor, exe_ctx, ast_type); - } - sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBTarget(%p)::CreateValueFromData => \"%s\"", - static_cast(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBTarget(%p)::CreateValueFromData => NULL", - static_cast(m_opaque_sp.get())); - } - return sb_value; -} - -lldb::SBValue -SBTarget::CreateValueFromExpression (const char *name, const char* expr) -{ - SBValue sb_value; - lldb::ValueObjectSP new_value_sp; - if (IsValid() && name && *name && expr && *expr) - { - ExecutionContext exe_ctx (ExecutionContextRef(ExecutionContext(m_opaque_sp.get(),false))); - new_value_sp = ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx); - } - sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBTarget(%p)::CreateValueFromExpression => \"%s\"", - static_cast(m_opaque_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBTarget(%p)::CreateValueFromExpression => NULL", - static_cast(m_opaque_sp.get())); - } - return sb_value; -} - -bool -SBTarget::DeleteAllWatchpoints () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::lock_guard guard(target_sp->GetAPIMutex()); - std::unique_lock lock; - target_sp->GetWatchpointList().GetListMutex(lock); - target_sp->RemoveAllWatchpoints (); - return true; - } - return false; -} - - -lldb::SBModule -SBTarget::AddModule (const char *path, - const char *triple, - const char *uuid_cstr) -{ - return AddModule (path, triple, uuid_cstr, NULL); -} - -lldb::SBModule -SBTarget::AddModule (const char *path, - const char *triple, - const char *uuid_cstr, - const char *symfile) -{ - lldb::SBModule sb_module; - TargetSP target_sp(GetSP()); - if (target_sp) - { - ModuleSpec module_spec; - if (path) - module_spec.GetFileSpec().SetFile(path, false); - - if (uuid_cstr) - module_spec.GetUUID().SetFromCString(uuid_cstr); - - if (triple) - module_spec.GetArchitecture().SetTriple (triple, target_sp->GetPlatform ().get()); - else - module_spec.GetArchitecture() = target_sp->GetArchitecture(); - - if (symfile) - module_spec.GetSymbolFileSpec ().SetFile(symfile, false); - - sb_module.SetSP(target_sp->GetSharedModule (module_spec)); - } - return sb_module; -} - -lldb::SBModule -SBTarget::AddModule (const SBModuleSpec &module_spec) -{ - lldb::SBModule sb_module; - TargetSP target_sp(GetSP()); - if (target_sp) - sb_module.SetSP(target_sp->GetSharedModule (*module_spec.m_opaque_ap)); - return sb_module; -} - -bool -SBTarget::AddModule (lldb::SBModule &module) -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - target_sp->GetImages().AppendIfNeeded (module.GetSP()); - return true; - } - return false; -} - -uint32_t -SBTarget::GetNumModules () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t num = 0; - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The module list is thread safe, no need to lock - num = target_sp->GetImages().GetSize(); - } - - if (log) - log->Printf ("SBTarget(%p)::GetNumModules () => %d", - static_cast(target_sp.get()), num); - - return num; -} - -void -SBTarget::Clear () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - log->Printf ("SBTarget(%p)::Clear ()", - static_cast(m_opaque_sp.get())); - - m_opaque_sp.reset(); -} - - -SBModule -SBTarget::FindModule (const SBFileSpec &sb_file_spec) -{ - SBModule sb_module; - TargetSP target_sp(GetSP()); - if (target_sp && sb_file_spec.IsValid()) - { - ModuleSpec module_spec(*sb_file_spec); - // The module list is thread safe, no need to lock - sb_module.SetSP (target_sp->GetImages().FindFirstModule (module_spec)); - } - return sb_module; -} - -lldb::ByteOrder -SBTarget::GetByteOrder () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - return target_sp->GetArchitecture().GetByteOrder(); - return eByteOrderInvalid; -} - -const char * -SBTarget::GetTriple () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::string triple (target_sp->GetArchitecture().GetTriple().str()); - // Unique the string so we don't run into ownership issues since - // the const strings put the string into the string pool once and - // the strings never comes out - ConstString const_triple (triple.c_str()); - return const_triple.GetCString(); - } - return NULL; -} - -uint32_t -SBTarget::GetDataByteSize () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - return target_sp->GetArchitecture().GetDataByteSize() ; - } - return 0; -} - -uint32_t -SBTarget::GetCodeByteSize () -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - return target_sp->GetArchitecture().GetCodeByteSize() ; - } - return 0; -} - -uint32_t -SBTarget::GetAddressByteSize() -{ - TargetSP target_sp(GetSP()); - if (target_sp) - return target_sp->GetArchitecture().GetAddressByteSize(); - return sizeof(void*); -} - - -SBModule -SBTarget::GetModuleAtIndex (uint32_t idx) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBModule sb_module; - ModuleSP module_sp; - TargetSP target_sp(GetSP()); - if (target_sp) - { - // The module list is thread safe, no need to lock - module_sp = target_sp->GetImages().GetModuleAtIndex(idx); - sb_module.SetSP (module_sp); - } - - if (log) - log->Printf ("SBTarget(%p)::GetModuleAtIndex (idx=%d) => SBModule(%p)", - static_cast(target_sp.get()), idx, - static_cast(module_sp.get())); - - return sb_module; -} - -bool -SBTarget::RemoveModule (lldb::SBModule module) -{ - TargetSP target_sp(GetSP()); - if (target_sp) - return target_sp->GetImages().Remove(module.GetSP()); - return false; -} - - -SBBroadcaster -SBTarget::GetBroadcaster () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - TargetSP target_sp(GetSP()); - SBBroadcaster broadcaster(target_sp.get(), false); - - if (log) - log->Printf ("SBTarget(%p)::GetBroadcaster () => SBBroadcaster(%p)", - static_cast(target_sp.get()), - static_cast(broadcaster.get())); - - return broadcaster; -} - -bool -SBTarget::GetDescription (SBStream &description, lldb::DescriptionLevel description_level) -{ - Stream &strm = description.ref(); - - TargetSP target_sp(GetSP()); - if (target_sp) - { - target_sp->Dump (&strm, description_level); - } - else - strm.PutCString ("No value"); - - return true; -} - -lldb::SBSymbolContextList -SBTarget::FindFunctions (const char *name, uint32_t name_type_mask) -{ - lldb::SBSymbolContextList sb_sc_list; - if (name && name[0]) - { - TargetSP target_sp(GetSP()); - if (target_sp) - { - const bool symbols_ok = true; - const bool inlines_ok = true; - const bool append = true; - target_sp->GetImages().FindFunctions (ConstString(name), - name_type_mask, - symbols_ok, - inlines_ok, - append, - *sb_sc_list); - } - } - return sb_sc_list; -} - -lldb::SBSymbolContextList -SBTarget::FindGlobalFunctions(const char *name, uint32_t max_matches, MatchType matchtype) -{ - lldb::SBSymbolContextList sb_sc_list; - if (name && name[0]) - { - TargetSP target_sp(GetSP()); - if (target_sp) - { - std::string regexstr; - switch (matchtype) - { - case eMatchTypeRegex: - target_sp->GetImages().FindFunctions(RegularExpression(name), true, true, true, *sb_sc_list); - break; - case eMatchTypeStartsWith: - regexstr = llvm::Regex::escape(name) + ".*"; - target_sp->GetImages().FindFunctions(RegularExpression(regexstr.c_str()), true, true, true, *sb_sc_list); - break; - default: - target_sp->GetImages().FindFunctions(ConstString(name), eFunctionNameTypeAny, true, true, true, *sb_sc_list); - break; - } - } - } - return sb_sc_list; -} - -lldb::SBType -SBTarget::FindFirstType (const char* typename_cstr) -{ - TargetSP target_sp(GetSP()); - if (typename_cstr && typename_cstr[0] && target_sp) - { - ConstString const_typename(typename_cstr); - SymbolContext sc; - const bool exact_match = false; - - const ModuleList &module_list = target_sp->GetImages(); - size_t count = module_list.GetSize(); - for (size_t idx = 0; idx < count; idx++) - { - ModuleSP module_sp (module_list.GetModuleAtIndex(idx)); - if (module_sp) - { - TypeSP type_sp (module_sp->FindFirstType(sc, const_typename, exact_match)); - if (type_sp) - return SBType(type_sp); - } - } - - // Didn't find the type in the symbols; try the Objective-C runtime - // if one is installed - - ProcessSP process_sp(target_sp->GetProcessSP()); - - if (process_sp) - { - ObjCLanguageRuntime *objc_language_runtime = process_sp->GetObjCLanguageRuntime(); - - if (objc_language_runtime) - { - DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); - - if (objc_decl_vendor) - { - std::vector decls; - - if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) - { - if (CompilerType type = ClangASTContext::GetTypeForDecl(decls[0])) - { - return SBType(type); - } - } - } - } - } - - // No matches, search for basic typename matches - ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); - if (clang_ast) - return SBType (ClangASTContext::GetBasicType (clang_ast->getASTContext(), const_typename)); - } - return SBType(); -} - -SBType -SBTarget::GetBasicType(lldb::BasicType type) -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); - if (clang_ast) - return SBType (ClangASTContext::GetBasicType (clang_ast->getASTContext(), type)); - } - return SBType(); -} - - -lldb::SBTypeList -SBTarget::FindTypes (const char* typename_cstr) -{ - SBTypeList sb_type_list; - TargetSP target_sp(GetSP()); - if (typename_cstr && typename_cstr[0] && target_sp) - { - ModuleList& images = target_sp->GetImages(); - ConstString const_typename(typename_cstr); - bool exact_match = false; - SymbolContext sc; - TypeList type_list; - llvm::DenseSet searched_symbol_files; - uint32_t num_matches = images.FindTypes (sc, - const_typename, - exact_match, - UINT32_MAX, - searched_symbol_files, - type_list); - - if (num_matches > 0) - { - for (size_t idx = 0; idx < num_matches; idx++) - { - TypeSP type_sp (type_list.GetTypeAtIndex(idx)); - if (type_sp) - sb_type_list.Append(SBType(type_sp)); - } - } - - // Try the Objective-C runtime if one is installed - - ProcessSP process_sp(target_sp->GetProcessSP()); - - if (process_sp) - { - ObjCLanguageRuntime *objc_language_runtime = process_sp->GetObjCLanguageRuntime(); - - if (objc_language_runtime) - { - DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor(); - - if (objc_decl_vendor) - { - std::vector decls; - - if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) - { - for (clang::NamedDecl *decl : decls) - { - if (CompilerType type = ClangASTContext::GetTypeForDecl(decl)) - { - sb_type_list.Append(SBType(type)); - } - } - } - } - } - } - - if (sb_type_list.GetSize() == 0) - { - // No matches, search for basic typename matches - ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext(); - if (clang_ast) - sb_type_list.Append (SBType (ClangASTContext::GetBasicType (clang_ast->getASTContext(), const_typename))); - } - } - return sb_type_list; -} - -SBValueList -SBTarget::FindGlobalVariables (const char *name, uint32_t max_matches) -{ - SBValueList sb_value_list; - - TargetSP target_sp(GetSP()); - if (name && target_sp) - { - VariableList variable_list; - const bool append = true; - const uint32_t match_count = target_sp->GetImages().FindGlobalVariables (ConstString (name), - append, - max_matches, - variable_list); - - if (match_count > 0) - { - ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); - if (exe_scope == NULL) - exe_scope = target_sp.get(); - for (uint32_t i=0; iGetImages().FindGlobalVariables(ConstString(name), - append, - max_matches, - variable_list); - break; - case eMatchTypeRegex: - match_count = target_sp->GetImages().FindGlobalVariables(RegularExpression(name), - append, - max_matches, - variable_list); - break; - case eMatchTypeStartsWith: - regexstr = llvm::Regex::escape(name) + ".*"; - match_count = target_sp->GetImages().FindGlobalVariables(RegularExpression(regexstr.c_str()), - append, - max_matches, - variable_list); - break; - } - - - if (match_count > 0) - { - ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get(); - if (exe_scope == NULL) - exe_scope = target_sp.get(); - for (uint32_t i = 0; i 0) - return sb_value_list.GetValueAtIndex(0); - return SBValue(); -} - -SBSourceManager -SBTarget::GetSourceManager() -{ - SBSourceManager source_manager (*this); - return source_manager; -} - -lldb::SBInstructionList -SBTarget::ReadInstructions (lldb::SBAddress base_addr, uint32_t count) -{ - return ReadInstructions (base_addr, count, NULL); -} - -lldb::SBInstructionList -SBTarget::ReadInstructions (lldb::SBAddress base_addr, uint32_t count, const char *flavor_string) -{ - SBInstructionList sb_instructions; - - TargetSP target_sp(GetSP()); - if (target_sp) - { - Address *addr_ptr = base_addr.get(); - - if (addr_ptr) - { - DataBufferHeap data (target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0); - bool prefer_file_cache = false; - lldb_private::Error error; - lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; - const size_t bytes_read = target_sp->ReadMemory(*addr_ptr, - prefer_file_cache, - data.GetBytes(), - data.GetByteSize(), - error, - &load_addr); - const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS; - sb_instructions.SetDisassembler (Disassembler::DisassembleBytes (target_sp->GetArchitecture(), - NULL, - flavor_string, - *addr_ptr, - data.GetBytes(), - bytes_read, - count, - data_from_file)); - } - } - - return sb_instructions; - -} - -lldb::SBInstructionList -SBTarget::GetInstructions (lldb::SBAddress base_addr, const void *buf, size_t size) -{ - return GetInstructionsWithFlavor (base_addr, NULL, buf, size); -} - -lldb::SBInstructionList -SBTarget::GetInstructionsWithFlavor (lldb::SBAddress base_addr, const char *flavor_string, const void *buf, size_t size) -{ - SBInstructionList sb_instructions; - - TargetSP target_sp(GetSP()); - if (target_sp) - { - Address addr; - - if (base_addr.get()) - addr = *base_addr.get(); - - const bool data_from_file = true; - - sb_instructions.SetDisassembler (Disassembler::DisassembleBytes (target_sp->GetArchitecture(), - NULL, - flavor_string, - addr, - buf, - size, - UINT32_MAX, - data_from_file)); - } - - return sb_instructions; -} - -lldb::SBInstructionList -SBTarget::GetInstructions (lldb::addr_t base_addr, const void *buf, size_t size) -{ - return GetInstructionsWithFlavor (ResolveLoadAddress(base_addr), NULL, buf, size); -} - -lldb::SBInstructionList -SBTarget::GetInstructionsWithFlavor (lldb::addr_t base_addr, const char *flavor_string, const void *buf, size_t size) -{ - return GetInstructionsWithFlavor (ResolveLoadAddress(base_addr), flavor_string, buf, size); -} - -SBError -SBTarget::SetSectionLoadAddress (lldb::SBSection section, - lldb::addr_t section_base_addr) -{ - SBError sb_error; - TargetSP target_sp(GetSP()); - if (target_sp) - { - if (!section.IsValid()) - { - sb_error.SetErrorStringWithFormat ("invalid section"); - } - else - { - SectionSP section_sp (section.GetSP()); - if (section_sp) - { - if (section_sp->IsThreadSpecific()) - { - sb_error.SetErrorString ("thread specific sections are not yet supported"); - } - else - { - ProcessSP process_sp (target_sp->GetProcessSP()); - if (target_sp->SetSectionLoadAddress (section_sp, section_base_addr)) - { - ModuleSP module_sp(section_sp->GetModule()); - if (module_sp) - { - ModuleList module_list; - module_list.Append(module_sp); - target_sp->ModulesDidLoad (module_list); - } - // Flush info in the process (stack frames, etc) - if (process_sp) - process_sp->Flush(); - } - } - } - } - } - else - { - sb_error.SetErrorString ("invalid target"); - } - return sb_error; -} - -SBError -SBTarget::ClearSectionLoadAddress (lldb::SBSection section) -{ - SBError sb_error; - - TargetSP target_sp(GetSP()); - if (target_sp) - { - if (!section.IsValid()) - { - sb_error.SetErrorStringWithFormat ("invalid section"); - } - else - { - SectionSP section_sp (section.GetSP()); - if (section_sp) - { - ProcessSP process_sp (target_sp->GetProcessSP()); - if (target_sp->SetSectionUnloaded(section_sp)) - { - ModuleSP module_sp(section_sp->GetModule()); - if (module_sp) - { - ModuleList module_list; - module_list.Append(module_sp); - target_sp->ModulesDidUnload(module_list, false); - } - // Flush info in the process (stack frames, etc) - if (process_sp) - process_sp->Flush(); - } - } - else - { - sb_error.SetErrorStringWithFormat ("invalid section"); - } - } - } - else - { - sb_error.SetErrorStringWithFormat ("invalid target"); - } - return sb_error; -} - -SBError -SBTarget::SetModuleLoadAddress (lldb::SBModule module, int64_t slide_offset) -{ - SBError sb_error; - - TargetSP target_sp(GetSP()); - if (target_sp) - { - ModuleSP module_sp (module.GetSP()); - if (module_sp) - { - bool changed = false; - if (module_sp->SetLoadAddress (*target_sp, slide_offset, true, changed)) - { - // The load was successful, make sure that at least some sections - // changed before we notify that our module was loaded. - if (changed) - { - ModuleList module_list; - module_list.Append(module_sp); - target_sp->ModulesDidLoad (module_list); - // Flush info in the process (stack frames, etc) - ProcessSP process_sp (target_sp->GetProcessSP()); - if (process_sp) - process_sp->Flush(); - } - } - } - else - { - sb_error.SetErrorStringWithFormat ("invalid module"); - } - - } - else - { - sb_error.SetErrorStringWithFormat ("invalid target"); - } - return sb_error; -} - -SBError -SBTarget::ClearModuleLoadAddress (lldb::SBModule module) -{ - SBError sb_error; - - char path[PATH_MAX]; - TargetSP target_sp(GetSP()); - if (target_sp) - { - ModuleSP module_sp (module.GetSP()); - if (module_sp) - { - ObjectFile *objfile = module_sp->GetObjectFile(); - if (objfile) - { - SectionList *section_list = objfile->GetSectionList(); - if (section_list) - { - ProcessSP process_sp (target_sp->GetProcessSP()); - - bool changed = false; - const size_t num_sections = section_list->GetSize(); - for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) - { - SectionSP section_sp (section_list->GetSectionAtIndex(sect_idx)); - if (section_sp) - changed |= target_sp->SetSectionUnloaded (section_sp); - } - if (changed) - { - ModuleList module_list; - module_list.Append(module_sp); - target_sp->ModulesDidUnload(module_list, false); - // Flush info in the process (stack frames, etc) - ProcessSP process_sp (target_sp->GetProcessSP()); - if (process_sp) - process_sp->Flush(); - } - } - else - { - module_sp->GetFileSpec().GetPath (path, sizeof(path)); - sb_error.SetErrorStringWithFormat ("no sections in object file '%s'", path); - } - } - else - { - module_sp->GetFileSpec().GetPath (path, sizeof(path)); - sb_error.SetErrorStringWithFormat ("no object file for module '%s'", path); - } - } - else - { - sb_error.SetErrorStringWithFormat ("invalid module"); - } - } - else - { - sb_error.SetErrorStringWithFormat ("invalid target"); - } - return sb_error; -} - - -lldb::SBSymbolContextList -SBTarget::FindSymbols (const char *name, lldb::SymbolType symbol_type) -{ - SBSymbolContextList sb_sc_list; - if (name && name[0]) - { - TargetSP target_sp(GetSP()); - if (target_sp) - { - bool append = true; - target_sp->GetImages().FindSymbolsWithNameAndType (ConstString(name), - symbol_type, - *sb_sc_list, - append); - } - } - return sb_sc_list; - -} - -lldb::SBValue -SBTarget::EvaluateExpression (const char *expr) -{ - TargetSP target_sp(GetSP()); - if (!target_sp) - return SBValue(); - - SBExpressionOptions options; - lldb::DynamicValueType fetch_dynamic_value = target_sp->GetPreferDynamicValue(); - options.SetFetchDynamicValue (fetch_dynamic_value); - options.SetUnwindOnError (true); - return EvaluateExpression(expr, options); -} - -lldb::SBValue -SBTarget::EvaluateExpression (const char *expr, const SBExpressionOptions &options) -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +lldb::SBValue SBTarget::EvaluateExpression(const char *expr, + const SBExpressionOptions &options) { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); #if !defined(LLDB_DISABLE_PYTHON) - Log * expr_log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); + Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); #endif - SBValue expr_result; - ExpressionResults exe_results = eExpressionSetupError; - ValueObjectSP expr_value_sp; - TargetSP target_sp(GetSP()); - StackFrame *frame = NULL; - if (target_sp) - { - if (expr == NULL || expr[0] == '\0') - { - if (log) - log->Printf ("SBTarget::EvaluateExpression called with an empty expression"); - return expr_result; - } - - std::lock_guard guard(target_sp->GetAPIMutex()); - ExecutionContext exe_ctx (m_opaque_sp.get()); + SBValue expr_result; + ExpressionResults exe_results = eExpressionSetupError; + ValueObjectSP expr_value_sp; + TargetSP target_sp(GetSP()); + StackFrame *frame = NULL; + if (target_sp) { + if (expr == NULL || expr[0] == '\0') { + if (log) + log->Printf( + "SBTarget::EvaluateExpression called with an empty expression"); + return expr_result; + } + + std::lock_guard guard(target_sp->GetAPIMutex()); + ExecutionContext exe_ctx(m_opaque_sp.get()); - if (log) - log->Printf ("SBTarget()::EvaluateExpression (expr=\"%s\")...", expr); + if (log) + log->Printf("SBTarget()::EvaluateExpression (expr=\"%s\")...", expr); - frame = exe_ctx.GetFramePtr(); - Target *target = exe_ctx.GetTargetPtr(); + frame = exe_ctx.GetFramePtr(); + Target *target = exe_ctx.GetTargetPtr(); - if (target) - { + if (target) { #ifdef LLDB_CONFIGURATION_DEBUG - StreamString frame_description; - if (frame) - frame->DumpUsingSettingsFormat (&frame_description); - Host::SetCrashDescriptionWithFormat ("SBTarget::EvaluateExpression (expr = \"%s\", fetch_dynamic_value = %u) %s", - expr, options.GetFetchDynamicValue(), frame_description.GetString().c_str()); + StreamString frame_description; + if (frame) + frame->DumpUsingSettingsFormat(&frame_description); + Host::SetCrashDescriptionWithFormat( + "SBTarget::EvaluateExpression (expr = \"%s\", fetch_dynamic_value = " + "%u) %s", + expr, options.GetFetchDynamicValue(), + frame_description.GetString().c_str()); #endif - exe_results = target->EvaluateExpression (expr, - frame, - expr_value_sp, - options.ref()); + exe_results = + target->EvaluateExpression(expr, frame, expr_value_sp, options.ref()); - expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); + expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue()); #ifdef LLDB_CONFIGURATION_DEBUG - Host::SetCrashDescription (NULL); + Host::SetCrashDescription(NULL); #endif - } - else - { - if (log) - log->Printf ("SBTarget::EvaluateExpression () => error: could not reconstruct frame object for this SBTarget."); - } + } else { + if (log) + log->Printf("SBTarget::EvaluateExpression () => error: could not " + "reconstruct frame object for this SBTarget."); } + } #ifndef LLDB_DISABLE_PYTHON - if (expr_log) - expr_log->Printf("** [SBTarget::EvaluateExpression] Expression result is %s, summary %s **", - expr_result.GetValue(), expr_result.GetSummary()); - - if (log) - log->Printf ("SBTarget(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) (execution result=%d)", - static_cast(frame), expr, - static_cast(expr_value_sp.get()), exe_results); + if (expr_log) + expr_log->Printf("** [SBTarget::EvaluateExpression] Expression result is " + "%s, summary %s **", + expr_result.GetValue(), expr_result.GetSummary()); + + if (log) + log->Printf("SBTarget(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) " + "(execution result=%d)", + static_cast(frame), expr, + static_cast(expr_value_sp.get()), exe_results); #endif - return expr_result; + return expr_result; } - -lldb::addr_t -SBTarget::GetStackRedZoneSize() -{ - TargetSP target_sp(GetSP()); - if (target_sp) - { - ABISP abi_sp; - ProcessSP process_sp (target_sp->GetProcessSP()); - if (process_sp) - abi_sp = process_sp->GetABI(); - else - abi_sp = ABI::FindPlugin(target_sp->GetArchitecture()); - if (abi_sp) - return abi_sp->GetRedZoneSize(); - } - return 0; +lldb::addr_t SBTarget::GetStackRedZoneSize() { + TargetSP target_sp(GetSP()); + if (target_sp) { + ABISP abi_sp; + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp) + abi_sp = process_sp->GetABI(); + else + abi_sp = ABI::FindPlugin(target_sp->GetArchitecture()); + if (abi_sp) + return abi_sp->GetRedZoneSize(); + } + return 0; } -lldb::SBLaunchInfo -SBTarget::GetLaunchInfo () const -{ - lldb::SBLaunchInfo launch_info(NULL); - TargetSP target_sp(GetSP()); - if (target_sp) - launch_info.ref() = m_opaque_sp->GetProcessLaunchInfo(); - return launch_info; +lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const { + lldb::SBLaunchInfo launch_info(NULL); + TargetSP target_sp(GetSP()); + if (target_sp) + launch_info.ref() = m_opaque_sp->GetProcessLaunchInfo(); + return launch_info; } -void -SBTarget::SetLaunchInfo (const lldb::SBLaunchInfo &launch_info) -{ - TargetSP target_sp(GetSP()); - if (target_sp) - m_opaque_sp->SetProcessLaunchInfo(launch_info.ref()); +void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) { + TargetSP target_sp(GetSP()); + if (target_sp) + m_opaque_sp->SetProcessLaunchInfo(launch_info.ref()); } diff --git a/lldb/source/API/SBThread.cpp b/lldb/source/API/SBThread.cpp index 1f752b570b4..c9dba37b078 100644 --- a/lldb/source/API/SBThread.cpp +++ b/lldb/source/API/SBThread.cpp @@ -9,9 +9,9 @@ #include "lldb/API/SBThread.h" -#include "lldb/API/SBSymbolContext.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBSymbolContext.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/State.h" @@ -20,20 +20,20 @@ #include "lldb/Core/StructuredData.h" #include "lldb/Core/ValueObject.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/CompileUnit.h" -#include "lldb/Target/SystemRuntime.h" -#include "lldb/Target/Thread.h" +#include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Queue.h" -#include "lldb/Target/UnixSignals.h" #include "lldb/Target/StopInfo.h" +#include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlan.h" +#include "lldb/Target/ThreadPlanStepInRange.h" #include "lldb/Target/ThreadPlanStepInstruction.h" #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Target/ThreadPlanStepRange.h" -#include "lldb/Target/ThreadPlanStepInRange.h" +#include "lldb/Target/UnixSignals.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" @@ -47,1675 +47,1392 @@ using namespace lldb; using namespace lldb_private; -const char * -SBThread::GetBroadcasterClassName () -{ - return Thread::GetStaticBroadcasterClass().AsCString(); +const char *SBThread::GetBroadcasterClassName() { + return Thread::GetStaticBroadcasterClass().AsCString(); } //---------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------- -SBThread::SBThread () : - m_opaque_sp (new ExecutionContextRef()) -{ -} +SBThread::SBThread() : m_opaque_sp(new ExecutionContextRef()) {} -SBThread::SBThread (const ThreadSP& lldb_object_sp) : - m_opaque_sp (new ExecutionContextRef(lldb_object_sp)) -{ -} +SBThread::SBThread(const ThreadSP &lldb_object_sp) + : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) {} -SBThread::SBThread (const SBThread &rhs) : - m_opaque_sp (new ExecutionContextRef(*rhs.m_opaque_sp)) -{ - -} +SBThread::SBThread(const SBThread &rhs) + : m_opaque_sp(new ExecutionContextRef(*rhs.m_opaque_sp)) {} //---------------------------------------------------------------------- // Assignment operator //---------------------------------------------------------------------- -const lldb::SBThread & -SBThread::operator = (const SBThread &rhs) -{ - if (this != &rhs) - *m_opaque_sp = *rhs.m_opaque_sp; - return *this; +const lldb::SBThread &SBThread::operator=(const SBThread &rhs) { + if (this != &rhs) + *m_opaque_sp = *rhs.m_opaque_sp; + return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -SBThread::~SBThread() -{ -} - -lldb::SBQueue -SBThread::GetQueue () const -{ - SBQueue sb_queue; - QueueSP queue_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - queue_sp = exe_ctx.GetThreadPtr()->GetQueue(); - if (queue_sp) - { - sb_queue.SetQueue (queue_sp); - } - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetQueue() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +SBThread::~SBThread() {} + +lldb::SBQueue SBThread::GetQueue() const { + SBQueue sb_queue; + QueueSP queue_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + queue_sp = exe_ctx.GetThreadPtr()->GetQueue(); + if (queue_sp) { + sb_queue.SetQueue(queue_sp); + } + } else { + if (log) + log->Printf("SBThread(%p)::GetQueue() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetQueue () => SBQueue(%p)", - static_cast(exe_ctx.GetThreadPtr()), static_cast(queue_sp.get())); - - return sb_queue; -} - - -bool -SBThread::IsValid() const -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + if (log) + log->Printf("SBThread(%p)::GetQueue () => SBQueue(%p)", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(queue_sp.get())); - Target *target = exe_ctx.GetTargetPtr(); - Process *process = exe_ctx.GetProcessPtr(); - if (target && process) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&process->GetRunLock())) - return m_opaque_sp->GetThreadSP().get() != NULL; - } - // Without a valid target & process, this thread can't be valid. - return false; + return sb_queue; } -void -SBThread::Clear () -{ - m_opaque_sp->Clear(); +bool SBThread::IsValid() const { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Target *target = exe_ctx.GetTargetPtr(); + Process *process = exe_ctx.GetProcessPtr(); + if (target && process) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&process->GetRunLock())) + return m_opaque_sp->GetThreadSP().get() != NULL; + } + // Without a valid target & process, this thread can't be valid. + return false; } +void SBThread::Clear() { m_opaque_sp->Clear(); } -StopReason -SBThread::GetStopReason() -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +StopReason SBThread::GetStopReason() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - StopReason reason = eStopReasonInvalid; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + StopReason reason = eStopReasonInvalid; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - return exe_ctx.GetThreadPtr()->GetStopReason(); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetStopReason() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + return exe_ctx.GetThreadPtr()->GetStopReason(); + } else { + if (log) + log->Printf( + "SBThread(%p)::GetStopReason() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetStopReason () => %s", - static_cast(exe_ctx.GetThreadPtr()), - Thread::StopReasonAsCString (reason)); + if (log) + log->Printf("SBThread(%p)::GetStopReason () => %s", + static_cast(exe_ctx.GetThreadPtr()), + Thread::StopReasonAsCString(reason)); - return reason; + return reason; } -size_t -SBThread::GetStopReasonDataCount () -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo (); - if (stop_info_sp) - { - StopReason reason = stop_info_sp->GetStopReason(); - switch (reason) - { - case eStopReasonInvalid: - case eStopReasonNone: - case eStopReasonTrace: - case eStopReasonExec: - case eStopReasonPlanComplete: - case eStopReasonThreadExiting: - case eStopReasonInstrumentation: - // There is no data for these stop reasons. - return 0; - - case eStopReasonBreakpoint: - { - break_id_t site_id = stop_info_sp->GetValue(); - lldb::BreakpointSiteSP bp_site_sp (exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID (site_id)); - if (bp_site_sp) - return bp_site_sp->GetNumberOfOwners () * 2; - else - return 0; // Breakpoint must have cleared itself... - } - break; - - case eStopReasonWatchpoint: - return 1; - - case eStopReasonSignal: - return 1; - - case eStopReasonException: - return 1; - } - } - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBThread(%p)::GetStopReasonDataCount() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); +size_t SBThread::GetStopReasonDataCount() { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo(); + if (stop_info_sp) { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonExec: + case eStopReasonPlanComplete: + case eStopReasonThreadExiting: + case eStopReasonInstrumentation: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp( + exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID( + site_id)); + if (bp_site_sp) + return bp_site_sp->GetNumberOfOwners() * 2; + else + return 0; // Breakpoint must have cleared itself... + } break; + + case eStopReasonWatchpoint: + return 1; + + case eStopReasonSignal: + return 1; + + case eStopReasonException: + return 1; } + } + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBThread(%p)::GetStopReasonDataCount() => error: process " + "is running", + static_cast(exe_ctx.GetThreadPtr())); } - return 0; + } + return 0; } -uint64_t -SBThread::GetStopReasonDataAtIndex (uint32_t idx) -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - Thread *thread = exe_ctx.GetThreadPtr(); - StopInfoSP stop_info_sp = thread->GetStopInfo (); - if (stop_info_sp) - { - StopReason reason = stop_info_sp->GetStopReason(); - switch (reason) - { - case eStopReasonInvalid: - case eStopReasonNone: - case eStopReasonTrace: - case eStopReasonExec: - case eStopReasonPlanComplete: - case eStopReasonThreadExiting: - case eStopReasonInstrumentation: - // There is no data for these stop reasons. - return 0; - - case eStopReasonBreakpoint: - { - break_id_t site_id = stop_info_sp->GetValue(); - lldb::BreakpointSiteSP bp_site_sp (exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID (site_id)); - if (bp_site_sp) - { - uint32_t bp_index = idx / 2; - BreakpointLocationSP bp_loc_sp (bp_site_sp->GetOwnerAtIndex (bp_index)); - if (bp_loc_sp) - { - if (idx & 1) - { - // Odd idx, return the breakpoint location ID - return bp_loc_sp->GetID(); - } - else - { - // Even idx, return the breakpoint ID - return bp_loc_sp->GetBreakpoint().GetID(); - } - } - } - return LLDB_INVALID_BREAK_ID; - } - break; - - case eStopReasonWatchpoint: - return stop_info_sp->GetValue(); - - case eStopReasonSignal: - return stop_info_sp->GetValue(); - - case eStopReasonException: - return stop_info_sp->GetValue(); - } +uint64_t SBThread::GetStopReasonDataAtIndex(uint32_t idx) { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + StopInfoSP stop_info_sp = thread->GetStopInfo(); + if (stop_info_sp) { + StopReason reason = stop_info_sp->GetStopReason(); + switch (reason) { + case eStopReasonInvalid: + case eStopReasonNone: + case eStopReasonTrace: + case eStopReasonExec: + case eStopReasonPlanComplete: + case eStopReasonThreadExiting: + case eStopReasonInstrumentation: + // There is no data for these stop reasons. + return 0; + + case eStopReasonBreakpoint: { + break_id_t site_id = stop_info_sp->GetValue(); + lldb::BreakpointSiteSP bp_site_sp( + exe_ctx.GetProcessPtr()->GetBreakpointSiteList().FindByID( + site_id)); + if (bp_site_sp) { + uint32_t bp_index = idx / 2; + BreakpointLocationSP bp_loc_sp( + bp_site_sp->GetOwnerAtIndex(bp_index)); + if (bp_loc_sp) { + if (idx & 1) { + // Odd idx, return the breakpoint location ID + return bp_loc_sp->GetID(); + } else { + // Even idx, return the breakpoint ID + return bp_loc_sp->GetBreakpoint().GetID(); + } } + } + return LLDB_INVALID_BREAK_ID; + } break; + + case eStopReasonWatchpoint: + return stop_info_sp->GetValue(); + + case eStopReasonSignal: + return stop_info_sp->GetValue(); + + case eStopReasonException: + return stop_info_sp->GetValue(); } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBThread(%p)::GetStopReasonDataAtIndex() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } + } + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBThread(%p)::GetStopReasonDataAtIndex() => error: " + "process is running", + static_cast(exe_ctx.GetThreadPtr())); } - return 0; + } + return 0; } -bool -SBThread::GetStopReasonExtendedInfoAsJSON (lldb::SBStream &stream) -{ - Stream &strm = stream.ref(); - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (! exe_ctx.HasThreadScope()) - return false; - - - StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); - StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); - if (! info) - return false; - - info->Dump(strm); - - return true; +bool SBThread::GetStopReasonExtendedInfoAsJSON(lldb::SBStream &stream) { + Stream &strm = stream.ref(); + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return false; + + StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); + StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); + if (!info) + return false; + + info->Dump(strm); + + return true; } SBThreadCollection -SBThread::GetStopReasonExtendedBacktraces (InstrumentationRuntimeType type) -{ - ThreadCollectionSP threads; - threads.reset(new ThreadCollection()); - - // We currently only support ThreadSanitizer. - if (type != eInstrumentationRuntimeTypeThreadSanitizer) - return threads; - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (! exe_ctx.HasThreadScope()) - return threads; - - ProcessSP process_sp = exe_ctx.GetProcessSP(); - - StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); - StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); - if (! info) - return threads; - - return process_sp->GetInstrumentationRuntime(type)->GetBacktracesFromExtendedStopInfo(info); +SBThread::GetStopReasonExtendedBacktraces(InstrumentationRuntimeType type) { + ThreadCollectionSP threads; + threads.reset(new ThreadCollection()); + + // We currently only support ThreadSanitizer. + if (type != eInstrumentationRuntimeTypeThreadSanitizer) + return threads; + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (!exe_ctx.HasThreadScope()) + return threads; + + ProcessSP process_sp = exe_ctx.GetProcessSP(); + + StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); + StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); + if (!info) + return threads; + + return process_sp->GetInstrumentationRuntime(type) + ->GetBacktracesFromExtendedStopInfo(info); } -size_t -SBThread::GetStopDescription (char *dst, size_t dst_len) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - - StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo (); - if (stop_info_sp) - { - const char *stop_desc = stop_info_sp->GetDescription(); - if (stop_desc) - { - if (log) - log->Printf ("SBThread(%p)::GetStopDescription (dst, dst_len) => \"%s\"", - static_cast(exe_ctx.GetThreadPtr()), - stop_desc); - if (dst) - return ::snprintf (dst, dst_len, "%s", stop_desc); - else - { - // NULL dst passed in, return the length needed to contain the description - return ::strlen (stop_desc) + 1; // Include the NULL byte for size - } - } - else - { - size_t stop_desc_len = 0; - switch (stop_info_sp->GetStopReason()) - { - case eStopReasonTrace: - case eStopReasonPlanComplete: - { - static char trace_desc[] = "step"; - stop_desc = trace_desc; - stop_desc_len = sizeof(trace_desc); // Include the NULL byte for size - } - break; - - case eStopReasonBreakpoint: - { - static char bp_desc[] = "breakpoint hit"; - stop_desc = bp_desc; - stop_desc_len = sizeof(bp_desc); // Include the NULL byte for size - } - break; - - case eStopReasonWatchpoint: - { - static char wp_desc[] = "watchpoint hit"; - stop_desc = wp_desc; - stop_desc_len = sizeof(wp_desc); // Include the NULL byte for size - } - break; - - case eStopReasonSignal: - { - stop_desc = exe_ctx.GetProcessPtr()->GetUnixSignals()->GetSignalAsCString(stop_info_sp->GetValue()); - if (stop_desc == NULL || stop_desc[0] == '\0') - { - static char signal_desc[] = "signal"; - stop_desc = signal_desc; - stop_desc_len = sizeof(signal_desc); // Include the NULL byte for size - } - } - break; - - case eStopReasonException: - { - char exc_desc[] = "exception"; - stop_desc = exc_desc; - stop_desc_len = sizeof(exc_desc); // Include the NULL byte for size - } - break; - - case eStopReasonExec: - { - char exc_desc[] = "exec"; - stop_desc = exc_desc; - stop_desc_len = sizeof(exc_desc); // Include the NULL byte for size - } - break; - - case eStopReasonThreadExiting: - { - char limbo_desc[] = "thread exiting"; - stop_desc = limbo_desc; - stop_desc_len = sizeof(limbo_desc); - } - break; - default: - break; - } - - if (stop_desc && stop_desc[0]) - { - if (log) - log->Printf ("SBThread(%p)::GetStopDescription (dst, dst_len) => '%s'", - static_cast(exe_ctx.GetThreadPtr()), - stop_desc); - - if (dst) - return ::snprintf (dst, dst_len, "%s", stop_desc) + 1; // Include the NULL byte - - if (stop_desc_len == 0) - stop_desc_len = ::strlen (stop_desc) + 1; // Include the NULL byte - - return stop_desc_len; - } - } +size_t SBThread::GetStopDescription(char *dst, size_t dst_len) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + + StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo(); + if (stop_info_sp) { + const char *stop_desc = stop_info_sp->GetDescription(); + if (stop_desc) { + if (log) + log->Printf( + "SBThread(%p)::GetStopDescription (dst, dst_len) => \"%s\"", + static_cast(exe_ctx.GetThreadPtr()), stop_desc); + if (dst) + return ::snprintf(dst, dst_len, "%s", stop_desc); + else { + // NULL dst passed in, return the length needed to contain the + // description + return ::strlen(stop_desc) + 1; // Include the NULL byte for size + } + } else { + size_t stop_desc_len = 0; + switch (stop_info_sp->GetStopReason()) { + case eStopReasonTrace: + case eStopReasonPlanComplete: { + static char trace_desc[] = "step"; + stop_desc = trace_desc; + stop_desc_len = + sizeof(trace_desc); // Include the NULL byte for size + } break; + + case eStopReasonBreakpoint: { + static char bp_desc[] = "breakpoint hit"; + stop_desc = bp_desc; + stop_desc_len = sizeof(bp_desc); // Include the NULL byte for size + } break; + + case eStopReasonWatchpoint: { + static char wp_desc[] = "watchpoint hit"; + stop_desc = wp_desc; + stop_desc_len = sizeof(wp_desc); // Include the NULL byte for size + } break; + + case eStopReasonSignal: { + stop_desc = + exe_ctx.GetProcessPtr()->GetUnixSignals()->GetSignalAsCString( + stop_info_sp->GetValue()); + if (stop_desc == NULL || stop_desc[0] == '\0') { + static char signal_desc[] = "signal"; + stop_desc = signal_desc; + stop_desc_len = + sizeof(signal_desc); // Include the NULL byte for size } - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + } break; + + case eStopReasonException: { + char exc_desc[] = "exception"; + stop_desc = exc_desc; + stop_desc_len = sizeof(exc_desc); // Include the NULL byte for size + } break; + + case eStopReasonExec: { + char exc_desc[] = "exec"; + stop_desc = exc_desc; + stop_desc_len = sizeof(exc_desc); // Include the NULL byte for size + } break; + + case eStopReasonThreadExiting: { + char limbo_desc[] = "thread exiting"; + stop_desc = limbo_desc; + stop_desc_len = sizeof(limbo_desc); + } break; + default: + break; + } + + if (stop_desc && stop_desc[0]) { if (log) - log->Printf ("SBThread(%p)::GetStopDescription() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); + log->Printf( + "SBThread(%p)::GetStopDescription (dst, dst_len) => '%s'", + static_cast(exe_ctx.GetThreadPtr()), stop_desc); + + if (dst) + return ::snprintf(dst, dst_len, "%s", stop_desc) + + 1; // Include the NULL byte + + if (stop_desc_len == 0) + stop_desc_len = ::strlen(stop_desc) + 1; // Include the NULL byte + + return stop_desc_len; + } } + } + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf( + "SBThread(%p)::GetStopDescription() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } - if (dst) - *dst = 0; - return 0; + } + if (dst) + *dst = 0; + return 0; } -SBValue -SBThread::GetStopReturnValue () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - ValueObjectSP return_valobj_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo (); - if (stop_info_sp) - { - return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp); - } - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetStopReturnValue() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +SBValue SBThread::GetStopReturnValue() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + ValueObjectSP return_valobj_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + StopInfoSP stop_info_sp = exe_ctx.GetThreadPtr()->GetStopInfo(); + if (stop_info_sp) { + return_valobj_sp = StopInfo::GetReturnValueObject(stop_info_sp); + } + } else { + if (log) + log->Printf( + "SBThread(%p)::GetStopReturnValue() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetStopReturnValue () => %s", - static_cast(exe_ctx.GetThreadPtr()), - return_valobj_sp.get() - ? return_valobj_sp->GetValueAsCString() - : ""); + if (log) + log->Printf("SBThread(%p)::GetStopReturnValue () => %s", + static_cast(exe_ctx.GetThreadPtr()), + return_valobj_sp.get() ? return_valobj_sp->GetValueAsCString() + : ""); - return SBValue (return_valobj_sp); + return SBValue(return_valobj_sp); } -void -SBThread::SetThread (const ThreadSP& lldb_object_sp) -{ - m_opaque_sp->SetThreadSP (lldb_object_sp); +void SBThread::SetThread(const ThreadSP &lldb_object_sp) { + m_opaque_sp->SetThreadSP(lldb_object_sp); } -lldb::tid_t -SBThread::GetThreadID () const -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp->GetID(); - return LLDB_INVALID_THREAD_ID; +lldb::tid_t SBThread::GetThreadID() const { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetID(); + return LLDB_INVALID_THREAD_ID; } -uint32_t -SBThread::GetIndexID () const -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp->GetIndexID(); - return LLDB_INVALID_INDEX32; +uint32_t SBThread::GetIndexID() const { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetIndexID(); + return LLDB_INVALID_INDEX32; } -const char * -SBThread::GetName () const -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *name = NULL; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - name = exe_ctx.GetThreadPtr()->GetName(); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetName() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +const char *SBThread::GetName() const { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *name = NULL; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + name = exe_ctx.GetThreadPtr()->GetName(); + } else { + if (log) + log->Printf("SBThread(%p)::GetName() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetName () => %s", - static_cast(exe_ctx.GetThreadPtr()), - name ? name : "NULL"); + if (log) + log->Printf("SBThread(%p)::GetName () => %s", + static_cast(exe_ctx.GetThreadPtr()), + name ? name : "NULL"); - return name; + return name; } -const char * -SBThread::GetQueueName () const -{ - const char *name = NULL; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - name = exe_ctx.GetThreadPtr()->GetQueueName(); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetQueueName() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +const char *SBThread::GetQueueName() const { + const char *name = NULL; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + name = exe_ctx.GetThreadPtr()->GetQueueName(); + } else { + if (log) + log->Printf("SBThread(%p)::GetQueueName() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetQueueName () => %s", - static_cast(exe_ctx.GetThreadPtr()), - name ? name : "NULL"); + if (log) + log->Printf("SBThread(%p)::GetQueueName () => %s", + static_cast(exe_ctx.GetThreadPtr()), + name ? name : "NULL"); - return name; + return name; } -lldb::queue_id_t -SBThread::GetQueueID () const -{ - queue_id_t id = LLDB_INVALID_QUEUE_ID; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - id = exe_ctx.GetThreadPtr()->GetQueueID(); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetQueueID() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +lldb::queue_id_t SBThread::GetQueueID() const { + queue_id_t id = LLDB_INVALID_QUEUE_ID; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + id = exe_ctx.GetThreadPtr()->GetQueueID(); + } else { + if (log) + log->Printf("SBThread(%p)::GetQueueID() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetQueueID () => 0x%" PRIx64, - static_cast(exe_ctx.GetThreadPtr()), id); + if (log) + log->Printf("SBThread(%p)::GetQueueID () => 0x%" PRIx64, + static_cast(exe_ctx.GetThreadPtr()), id); - return id; + return id; } -bool -SBThread::GetInfoItemByPathAsString (const char *path, SBStream &strm) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool success = false; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - Thread *thread = exe_ctx.GetThreadPtr(); - StructuredData::ObjectSP info_root_sp = thread->GetExtendedInfo(); - if (info_root_sp) - { - StructuredData::ObjectSP node = info_root_sp->GetObjectForDotSeparatedPath (path); - if (node) - { - if (node->GetType() == StructuredData::Type::eTypeString) - { - strm.Printf ("%s", node->GetAsString()->GetValue().c_str()); - success = true; - } - if (node->GetType() == StructuredData::Type::eTypeInteger) - { - strm.Printf ("0x%" PRIx64, node->GetAsInteger()->GetValue()); - success = true; - } - if (node->GetType() == StructuredData::Type::eTypeFloat) - { - strm.Printf ("0x%f", node->GetAsFloat()->GetValue()); - success = true; - } - if (node->GetType() == StructuredData::Type::eTypeBoolean) - { - if (node->GetAsBoolean()->GetValue() == true) - strm.Printf ("true"); - else - strm.Printf ("false"); - success = true; - } - if (node->GetType() == StructuredData::Type::eTypeNull) - { - strm.Printf ("null"); - success = true; - } - } - } - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetInfoItemByPathAsString() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); +bool SBThread::GetInfoItemByPathAsString(const char *path, SBStream &strm) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool success = false; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + StructuredData::ObjectSP info_root_sp = thread->GetExtendedInfo(); + if (info_root_sp) { + StructuredData::ObjectSP node = + info_root_sp->GetObjectForDotSeparatedPath(path); + if (node) { + if (node->GetType() == StructuredData::Type::eTypeString) { + strm.Printf("%s", node->GetAsString()->GetValue().c_str()); + success = true; + } + if (node->GetType() == StructuredData::Type::eTypeInteger) { + strm.Printf("0x%" PRIx64, node->GetAsInteger()->GetValue()); + success = true; + } + if (node->GetType() == StructuredData::Type::eTypeFloat) { + strm.Printf("0x%f", node->GetAsFloat()->GetValue()); + success = true; + } + if (node->GetType() == StructuredData::Type::eTypeBoolean) { + if (node->GetAsBoolean()->GetValue() == true) + strm.Printf("true"); + else + strm.Printf("false"); + success = true; + } + if (node->GetType() == StructuredData::Type::eTypeNull) { + strm.Printf("null"); + success = true; + } } + } + } else { + if (log) + log->Printf("SBThread(%p)::GetInfoItemByPathAsString() => error: " + "process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetInfoItemByPathAsString () => %s", - static_cast(exe_ctx.GetThreadPtr()), - strm.GetData()); + if (log) + log->Printf("SBThread(%p)::GetInfoItemByPathAsString () => %s", + static_cast(exe_ctx.GetThreadPtr()), strm.GetData()); - return success; + return success; } +SBError SBThread::ResumeNewPlan(ExecutionContext &exe_ctx, + ThreadPlan *new_plan) { + SBError sb_error; -SBError -SBThread::ResumeNewPlan (ExecutionContext &exe_ctx, ThreadPlan *new_plan) -{ - SBError sb_error; - - Process *process = exe_ctx.GetProcessPtr(); - if (!process) - { - sb_error.SetErrorString("No process in SBThread::ResumeNewPlan"); - return sb_error; - } + Process *process = exe_ctx.GetProcessPtr(); + if (!process) { + sb_error.SetErrorString("No process in SBThread::ResumeNewPlan"); + return sb_error; + } - Thread *thread = exe_ctx.GetThreadPtr(); - if (!thread) - { - sb_error.SetErrorString("No thread in SBThread::ResumeNewPlan"); - return sb_error; - } - - // User level plans should be Master Plans so they can be interrupted, other plans executed, and - // then a "continue" will resume the plan. - if (new_plan != NULL) - { - new_plan->SetIsMasterPlan(true); - new_plan->SetOkayToDiscard(false); - } - - // Why do we need to set the current thread by ID here??? - process->GetThreadList().SetSelectedThreadByID (thread->GetID()); - - if (process->GetTarget().GetDebugger().GetAsyncExecution ()) - sb_error.ref() = process->Resume (); - else - sb_error.ref() = process->ResumeSynchronous (NULL); - + Thread *thread = exe_ctx.GetThreadPtr(); + if (!thread) { + sb_error.SetErrorString("No thread in SBThread::ResumeNewPlan"); return sb_error; + } + + // User level plans should be Master Plans so they can be interrupted, other + // plans executed, and + // then a "continue" will resume the plan. + if (new_plan != NULL) { + new_plan->SetIsMasterPlan(true); + new_plan->SetOkayToDiscard(false); + } + + // Why do we need to set the current thread by ID here??? + process->GetThreadList().SetSelectedThreadByID(thread->GetID()); + + if (process->GetTarget().GetDebugger().GetAsyncExecution()) + sb_error.ref() = process->Resume(); + else + sb_error.ref() = process->ResumeSynchronous(NULL); + + return sb_error; } -void -SBThread::StepOver (lldb::RunMode stop_other_threads) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::StepOver(lldb::RunMode stop_other_threads) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::StepOver (stop_other_threads='%s')", - static_cast(exe_ctx.GetThreadPtr()), - Thread::RunModeAsCString (stop_other_threads)); - - if (exe_ctx.HasThreadScope()) - { - Thread *thread = exe_ctx.GetThreadPtr(); - bool abort_other_plans = false; - StackFrameSP frame_sp(thread->GetStackFrameAtIndex (0)); - - ThreadPlanSP new_plan_sp; - if (frame_sp) - { - if (frame_sp->HasDebugInformation ()) - { - const LazyBool avoid_no_debug = eLazyBoolCalculate; - SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); - new_plan_sp = thread->QueueThreadPlanForStepOverRange (abort_other_plans, - sc.line_entry, - sc, - stop_other_threads, - avoid_no_debug); - } - else - { - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true, - abort_other_plans, - stop_other_threads); - } - } + if (log) + log->Printf("SBThread(%p)::StepOver (stop_other_threads='%s')", + static_cast(exe_ctx.GetThreadPtr()), + Thread::RunModeAsCString(stop_other_threads)); - // This returns an error, we should use it! - ResumeNewPlan (exe_ctx, new_plan_sp.get()); + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + bool abort_other_plans = false; + StackFrameSP frame_sp(thread->GetStackFrameAtIndex(0)); + + ThreadPlanSP new_plan_sp; + if (frame_sp) { + if (frame_sp->HasDebugInformation()) { + const LazyBool avoid_no_debug = eLazyBoolCalculate; + SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); + new_plan_sp = thread->QueueThreadPlanForStepOverRange( + abort_other_plans, sc.line_entry, sc, stop_other_threads, + avoid_no_debug); + } else { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + true, abort_other_plans, stop_other_threads); + } } + + // This returns an error, we should use it! + ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -void -SBThread::StepInto (lldb::RunMode stop_other_threads) -{ - StepInto (NULL, stop_other_threads); +void SBThread::StepInto(lldb::RunMode stop_other_threads) { + StepInto(NULL, stop_other_threads); } -void -SBThread::StepInto (const char *target_name, lldb::RunMode stop_other_threads) -{ - SBError error; - StepInto(target_name, LLDB_INVALID_LINE_NUMBER, error, stop_other_threads); +void SBThread::StepInto(const char *target_name, + lldb::RunMode stop_other_threads) { + SBError error; + StepInto(target_name, LLDB_INVALID_LINE_NUMBER, error, stop_other_threads); } -void -SBThread::StepInto (const char *target_name, uint32_t end_line, SBError &error, lldb::RunMode stop_other_threads) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::StepInto(const char *target_name, uint32_t end_line, + SBError &error, lldb::RunMode stop_other_threads) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::StepInto (target_name='%s', stop_other_threads='%s')", - static_cast(exe_ctx.GetThreadPtr()), - target_name? target_name: "", - Thread::RunModeAsCString (stop_other_threads)); - - if (exe_ctx.HasThreadScope()) - { - bool abort_other_plans = false; - - Thread *thread = exe_ctx.GetThreadPtr(); - StackFrameSP frame_sp(thread->GetStackFrameAtIndex (0)); - ThreadPlanSP new_plan_sp; - - if (frame_sp && frame_sp->HasDebugInformation ()) - { - SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); - AddressRange range; - if (end_line == LLDB_INVALID_LINE_NUMBER) - range = sc.line_entry.range; - else - { - if (!sc.GetAddressRangeFromHereToEndLine(end_line, range, error.ref())) - return; - } - - const LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate; - const LazyBool step_in_avoids_code_without_debug_info = eLazyBoolCalculate; - new_plan_sp = thread->QueueThreadPlanForStepInRange (abort_other_plans, - range, - sc, - target_name, - stop_other_threads, - step_in_avoids_code_without_debug_info, - step_out_avoids_code_without_debug_info); - } - else - { - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, - abort_other_plans, - stop_other_threads); - } + if (log) + log->Printf( + "SBThread(%p)::StepInto (target_name='%s', stop_other_threads='%s')", + static_cast(exe_ctx.GetThreadPtr()), + target_name ? target_name : "", + Thread::RunModeAsCString(stop_other_threads)); + + if (exe_ctx.HasThreadScope()) { + bool abort_other_plans = false; - error = ResumeNewPlan (exe_ctx, new_plan_sp.get()); + Thread *thread = exe_ctx.GetThreadPtr(); + StackFrameSP frame_sp(thread->GetStackFrameAtIndex(0)); + ThreadPlanSP new_plan_sp; + + if (frame_sp && frame_sp->HasDebugInformation()) { + SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); + AddressRange range; + if (end_line == LLDB_INVALID_LINE_NUMBER) + range = sc.line_entry.range; + else { + if (!sc.GetAddressRangeFromHereToEndLine(end_line, range, error.ref())) + return; + } + + const LazyBool step_out_avoids_code_without_debug_info = + eLazyBoolCalculate; + const LazyBool step_in_avoids_code_without_debug_info = + eLazyBoolCalculate; + new_plan_sp = thread->QueueThreadPlanForStepInRange( + abort_other_plans, range, sc, target_name, stop_other_threads, + step_in_avoids_code_without_debug_info, + step_out_avoids_code_without_debug_info); + } else { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + false, abort_other_plans, stop_other_threads); } + + error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -void -SBThread::StepOut () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::StepOut() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::StepOut ()", - static_cast(exe_ctx.GetThreadPtr())); + if (log) + log->Printf("SBThread(%p)::StepOut ()", + static_cast(exe_ctx.GetThreadPtr())); - if (exe_ctx.HasThreadScope()) - { - bool abort_other_plans = false; - bool stop_other_threads = false; + if (exe_ctx.HasThreadScope()) { + bool abort_other_plans = false; + bool stop_other_threads = false; - Thread *thread = exe_ctx.GetThreadPtr(); + Thread *thread = exe_ctx.GetThreadPtr(); - const LazyBool avoid_no_debug = eLazyBoolCalculate; - ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut (abort_other_plans, - NULL, - false, - stop_other_threads, - eVoteYes, - eVoteNoOpinion, - 0, - avoid_no_debug)); - - // This returns an error, we should use it! - ResumeNewPlan (exe_ctx, new_plan_sp.get()); - } + const LazyBool avoid_no_debug = eLazyBoolCalculate; + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut( + abort_other_plans, NULL, false, stop_other_threads, eVoteYes, + eVoteNoOpinion, 0, avoid_no_debug)); + + // This returns an error, we should use it! + ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -void -SBThread::StepOutOfFrame (lldb::SBFrame &sb_frame) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::StepOutOfFrame(lldb::SBFrame &sb_frame) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (!sb_frame.IsValid()) - { - if (log) - log->Printf("SBThread(%p)::StepOutOfFrame passed an invalid frame, returning.", - static_cast(exe_ctx.GetThreadPtr())); - return; - } - - StackFrameSP frame_sp (sb_frame.GetFrameSP()); + if (!sb_frame.IsValid()) { if (log) - { - SBStream frame_desc_strm; - sb_frame.GetDescription (frame_desc_strm); - log->Printf ("SBThread(%p)::StepOutOfFrame (frame = SBFrame(%p): %s)", - static_cast(exe_ctx.GetThreadPtr()), - static_cast(frame_sp.get()), - frame_desc_strm.GetData()); + log->Printf( + "SBThread(%p)::StepOutOfFrame passed an invalid frame, returning.", + static_cast(exe_ctx.GetThreadPtr())); + return; + } + + StackFrameSP frame_sp(sb_frame.GetFrameSP()); + if (log) { + SBStream frame_desc_strm; + sb_frame.GetDescription(frame_desc_strm); + log->Printf("SBThread(%p)::StepOutOfFrame (frame = SBFrame(%p): %s)", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(frame_sp.get()), frame_desc_strm.GetData()); + } + + if (exe_ctx.HasThreadScope()) { + bool abort_other_plans = false; + bool stop_other_threads = false; + Thread *thread = exe_ctx.GetThreadPtr(); + if (sb_frame.GetThread().GetThreadID() != thread->GetID()) { + log->Printf("SBThread(%p)::StepOutOfFrame passed a frame from another " + "thread (0x%" PRIx64 " vrs. 0x%" PRIx64 ", returning.", + static_cast(exe_ctx.GetThreadPtr()), + sb_frame.GetThread().GetThreadID(), thread->GetID()); } - if (exe_ctx.HasThreadScope()) - { - bool abort_other_plans = false; - bool stop_other_threads = false; - Thread *thread = exe_ctx.GetThreadPtr(); - if (sb_frame.GetThread().GetThreadID() != thread->GetID()) - { - log->Printf("SBThread(%p)::StepOutOfFrame passed a frame from another thread (0x%" PRIx64 " vrs. 0x%" PRIx64 ", returning.", - static_cast(exe_ctx.GetThreadPtr()), - sb_frame.GetThread().GetThreadID(), - thread->GetID()); - } - - ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut (abort_other_plans, - NULL, - false, - stop_other_threads, - eVoteYes, - eVoteNoOpinion, - frame_sp->GetFrameIndex())); + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepOut( + abort_other_plans, NULL, false, stop_other_threads, eVoteYes, + eVoteNoOpinion, frame_sp->GetFrameIndex())); - // This returns an error, we should use it! - ResumeNewPlan (exe_ctx, new_plan_sp.get()); - } + // This returns an error, we should use it! + ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -void -SBThread::StepInstruction (bool step_over) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::StepInstruction(bool step_over) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::StepInstruction (step_over=%i)", - static_cast(exe_ctx.GetThreadPtr()), step_over); + if (log) + log->Printf("SBThread(%p)::StepInstruction (step_over=%i)", + static_cast(exe_ctx.GetThreadPtr()), step_over); - if (exe_ctx.HasThreadScope()) - { - Thread *thread = exe_ctx.GetThreadPtr(); - ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepSingleInstruction (step_over, true, true)); + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + ThreadPlanSP new_plan_sp( + thread->QueueThreadPlanForStepSingleInstruction(step_over, true, true)); - // This returns an error, we should use it! - ResumeNewPlan (exe_ctx, new_plan_sp.get()); - } + // This returns an error, we should use it! + ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -void -SBThread::RunToAddress (lldb::addr_t addr) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +void SBThread::RunToAddress(lldb::addr_t addr) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::RunToAddress (addr=0x%" PRIx64 ")", - static_cast(exe_ctx.GetThreadPtr()), addr); + if (log) + log->Printf("SBThread(%p)::RunToAddress (addr=0x%" PRIx64 ")", + static_cast(exe_ctx.GetThreadPtr()), addr); - if (exe_ctx.HasThreadScope()) - { - bool abort_other_plans = false; - bool stop_other_threads = true; + if (exe_ctx.HasThreadScope()) { + bool abort_other_plans = false; + bool stop_other_threads = true; - Address target_addr (addr); + Address target_addr(addr); - Thread *thread = exe_ctx.GetThreadPtr(); + Thread *thread = exe_ctx.GetThreadPtr(); - ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForRunToAddress (abort_other_plans, - target_addr, - stop_other_threads)); + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForRunToAddress( + abort_other_plans, target_addr, stop_other_threads)); - // This returns an error, we should use it! - ResumeNewPlan (exe_ctx, new_plan_sp.get()); - } + // This returns an error, we should use it! + ResumeNewPlan(exe_ctx, new_plan_sp.get()); + } } -SBError -SBThread::StepOverUntil (lldb::SBFrame &sb_frame, - lldb::SBFileSpec &sb_file_spec, - uint32_t line) -{ - SBError sb_error; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - char path[PATH_MAX]; - - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - StackFrameSP frame_sp (sb_frame.GetFrameSP()); +SBError SBThread::StepOverUntil(lldb::SBFrame &sb_frame, + lldb::SBFileSpec &sb_file_spec, uint32_t line) { + SBError sb_error; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + char path[PATH_MAX]; + + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + StackFrameSP frame_sp(sb_frame.GetFrameSP()); + + if (log) { + SBStream frame_desc_strm; + sb_frame.GetDescription(frame_desc_strm); + sb_file_spec->GetPath(path, sizeof(path)); + log->Printf("SBThread(%p)::StepOverUntil (frame = SBFrame(%p): %s, " + "file+line = %s:%u)", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(frame_sp.get()), frame_desc_strm.GetData(), + path, line); + } + + if (exe_ctx.HasThreadScope()) { + Target *target = exe_ctx.GetTargetPtr(); + Thread *thread = exe_ctx.GetThreadPtr(); - if (log) - { - SBStream frame_desc_strm; - sb_frame.GetDescription (frame_desc_strm); - sb_file_spec->GetPath (path, sizeof(path)); - log->Printf ("SBThread(%p)::StepOverUntil (frame = SBFrame(%p): %s, file+line = %s:%u)", - static_cast(exe_ctx.GetThreadPtr()), - static_cast(frame_sp.get()), - frame_desc_strm.GetData(), path, line); + if (line == 0) { + sb_error.SetErrorString("invalid line argument"); + return sb_error; } - if (exe_ctx.HasThreadScope()) - { - Target *target = exe_ctx.GetTargetPtr(); - Thread *thread = exe_ctx.GetThreadPtr(); - - if (line == 0) - { - sb_error.SetErrorString("invalid line argument"); - return sb_error; - } - - if (!frame_sp) - { - frame_sp = thread->GetSelectedFrame (); - if (!frame_sp) - frame_sp = thread->GetStackFrameAtIndex (0); - } - - SymbolContext frame_sc; - if (!frame_sp) - { - sb_error.SetErrorString("no valid frames in thread to step"); - return sb_error; - } + if (!frame_sp) { + frame_sp = thread->GetSelectedFrame(); + if (!frame_sp) + frame_sp = thread->GetStackFrameAtIndex(0); + } - // If we have a frame, get its line - frame_sc = frame_sp->GetSymbolContext (eSymbolContextCompUnit | - eSymbolContextFunction | - eSymbolContextLineEntry | - eSymbolContextSymbol ); + SymbolContext frame_sc; + if (!frame_sp) { + sb_error.SetErrorString("no valid frames in thread to step"); + return sb_error; + } - if (frame_sc.comp_unit == NULL) - { - sb_error.SetErrorStringWithFormat("frame %u doesn't have debug information", frame_sp->GetFrameIndex()); - return sb_error; - } + // If we have a frame, get its line + frame_sc = frame_sp->GetSymbolContext( + eSymbolContextCompUnit | eSymbolContextFunction | + eSymbolContextLineEntry | eSymbolContextSymbol); - FileSpec step_file_spec; - if (sb_file_spec.IsValid()) - { - // The file spec passed in was valid, so use it - step_file_spec = sb_file_spec.ref(); - } - else - { - if (frame_sc.line_entry.IsValid()) - step_file_spec = frame_sc.line_entry.file; - else - { - sb_error.SetErrorString("invalid file argument or no file for frame"); - return sb_error; - } - } + if (frame_sc.comp_unit == NULL) { + sb_error.SetErrorStringWithFormat( + "frame %u doesn't have debug information", frame_sp->GetFrameIndex()); + return sb_error; + } - // Grab the current function, then we will make sure the "until" address is - // within the function. We discard addresses that are out of the current - // function, and then if there are no addresses remaining, give an appropriate - // error message. - - bool all_in_function = true; - AddressRange fun_range = frame_sc.function->GetAddressRange(); - - std::vector step_over_until_addrs; - const bool abort_other_plans = false; - const bool stop_other_threads = false; - const bool check_inlines = true; - const bool exact = false; - - SymbolContextList sc_list; - const uint32_t num_matches = frame_sc.comp_unit->ResolveSymbolContext (step_file_spec, - line, - check_inlines, - exact, - eSymbolContextLineEntry, - sc_list); - if (num_matches > 0) - { - SymbolContext sc; - for (uint32_t i=0; iGetAddressRange(); + + std::vector step_over_until_addrs; + const bool abort_other_plans = false; + const bool stop_other_threads = false; + const bool check_inlines = true; + const bool exact = false; + + SymbolContextList sc_list; + const uint32_t num_matches = frame_sc.comp_unit->ResolveSymbolContext( + step_file_spec, line, check_inlines, exact, eSymbolContextLineEntry, + sc_list); + if (num_matches > 0) { + SymbolContext sc; + for (uint32_t i = 0; i < num_matches; ++i) { + if (sc_list.GetContextAtIndex(i, sc)) { + addr_t step_addr = + sc.line_entry.range.GetBaseAddress().GetLoadAddress(target); + if (step_addr != LLDB_INVALID_ADDRESS) { + if (fun_range.ContainsLoadAddress(step_addr, target)) + step_over_until_addrs.push_back(step_addr); else - sb_error.SetErrorString ("step until target not in current function"); - } - else - { - ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepUntil (abort_other_plans, - &step_over_until_addrs[0], - step_over_until_addrs.size(), - stop_other_threads, - frame_sp->GetFrameIndex())); - - sb_error = ResumeNewPlan (exe_ctx, new_plan_sp.get()); + all_in_function = false; + } } + } } - else - { - sb_error.SetErrorString("this SBThread object is invalid"); + + if (step_over_until_addrs.empty()) { + if (all_in_function) { + step_file_spec.GetPath(path, sizeof(path)); + sb_error.SetErrorStringWithFormat("No line entries for %s:%u", path, + line); + } else + sb_error.SetErrorString("step until target not in current function"); + } else { + ThreadPlanSP new_plan_sp(thread->QueueThreadPlanForStepUntil( + abort_other_plans, &step_over_until_addrs[0], + step_over_until_addrs.size(), stop_other_threads, + frame_sp->GetFrameIndex())); + + sb_error = ResumeNewPlan(exe_ctx, new_plan_sp.get()); } - return sb_error; + } else { + sb_error.SetErrorString("this SBThread object is invalid"); + } + return sb_error; } -SBError -SBThread::StepUsingScriptedThreadPlan (const char *script_class_name) -{ - return StepUsingScriptedThreadPlan(script_class_name, true); +SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name) { + return StepUsingScriptedThreadPlan(script_class_name, true); } -SBError -SBThread::StepUsingScriptedThreadPlan (const char *script_class_name, bool resume_immediately) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBError sb_error; +SBError SBThread::StepUsingScriptedThreadPlan(const char *script_class_name, + bool resume_immediately) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBError sb_error; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - { - log->Printf ("SBThread(%p)::StepUsingScriptedThreadPlan: class name: %s", - static_cast(exe_ctx.GetThreadPtr()), - script_class_name); - } + if (log) { + log->Printf("SBThread(%p)::StepUsingScriptedThreadPlan: class name: %s", + static_cast(exe_ctx.GetThreadPtr()), script_class_name); + } + if (!exe_ctx.HasThreadScope()) { + sb_error.SetErrorString("this SBThread object is invalid"); + return sb_error; + } - if (!exe_ctx.HasThreadScope()) - { - sb_error.SetErrorString("this SBThread object is invalid"); - return sb_error; - } - - Thread *thread = exe_ctx.GetThreadPtr(); - ThreadPlanSP thread_plan_sp = thread->QueueThreadPlanForStepScripted(false, script_class_name, false); + Thread *thread = exe_ctx.GetThreadPtr(); + ThreadPlanSP thread_plan_sp = + thread->QueueThreadPlanForStepScripted(false, script_class_name, false); - if (!thread_plan_sp) - { - sb_error.SetErrorStringWithFormat("Error queueing thread plan for class: %s", script_class_name); - return sb_error; - } - - if (!resume_immediately) - { - return sb_error; - } - - if (thread_plan_sp) - sb_error = ResumeNewPlan(exe_ctx, thread_plan_sp.get()); - else - { - sb_error.SetErrorStringWithFormat("Error resuming thread plan for class: %s.", script_class_name); - if (log) - log->Printf ("SBThread(%p)::StepUsingScriptedThreadPlan: Error queuing thread plan for class: %s", - static_cast(exe_ctx.GetThreadPtr()), - script_class_name); - } + if (!thread_plan_sp) { + sb_error.SetErrorStringWithFormat( + "Error queueing thread plan for class: %s", script_class_name); + return sb_error; + } + if (!resume_immediately) { return sb_error; -} + } -SBError -SBThread::JumpToLine (lldb::SBFileSpec &file_spec, uint32_t line) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBError sb_error; + if (thread_plan_sp) + sb_error = ResumeNewPlan(exe_ctx, thread_plan_sp.get()); + else { + sb_error.SetErrorStringWithFormat( + "Error resuming thread plan for class: %s.", script_class_name); + if (log) + log->Printf("SBThread(%p)::StepUsingScriptedThreadPlan: Error queuing " + "thread plan for class: %s", + static_cast(exe_ctx.GetThreadPtr()), + script_class_name); + } - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + return sb_error; +} - if (log) - log->Printf ("SBThread(%p)::JumpToLine (file+line = %s:%u)", - static_cast(exe_ctx.GetThreadPtr()), - file_spec->GetPath().c_str(), line); +SBError SBThread::JumpToLine(lldb::SBFileSpec &file_spec, uint32_t line) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBError sb_error; - if (!exe_ctx.HasThreadScope()) - { - sb_error.SetErrorString("this SBThread object is invalid"); - return sb_error; - } + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - Thread *thread = exe_ctx.GetThreadPtr(); + if (log) + log->Printf("SBThread(%p)::JumpToLine (file+line = %s:%u)", + static_cast(exe_ctx.GetThreadPtr()), + file_spec->GetPath().c_str(), line); - Error err = thread->JumpToLine (file_spec.get(), line, true); - sb_error.SetError (err); + if (!exe_ctx.HasThreadScope()) { + sb_error.SetErrorString("this SBThread object is invalid"); return sb_error; + } + + Thread *thread = exe_ctx.GetThreadPtr(); + + Error err = thread->JumpToLine(file_spec.get(), line, true); + sb_error.SetError(err); + return sb_error; } -SBError -SBThread::ReturnFromFrame (SBFrame &frame, SBValue &return_value) -{ - SBError sb_error; +SBError SBThread::ReturnFromFrame(SBFrame &frame, SBValue &return_value) { + SBError sb_error; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::ReturnFromFrame (frame=%d)", - static_cast(exe_ctx.GetThreadPtr()), - frame.GetFrameID()); - - if (exe_ctx.HasThreadScope()) - { - Thread *thread = exe_ctx.GetThreadPtr(); - sb_error.SetError (thread->ReturnFromFrame(frame.GetFrameSP(), return_value.GetSP())); - } + if (log) + log->Printf("SBThread(%p)::ReturnFromFrame (frame=%d)", + static_cast(exe_ctx.GetThreadPtr()), + frame.GetFrameID()); - return sb_error; + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + sb_error.SetError( + thread->ReturnFromFrame(frame.GetFrameSP(), return_value.GetSP())); + } + + return sb_error; } -SBError -SBThread::UnwindInnermostExpression() -{ - SBError sb_error; +SBError SBThread::UnwindInnermostExpression() { + SBError sb_error; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (log) - log->Printf ("SBThread(%p)::UnwindExpressionEvaluation", - static_cast(exe_ctx.GetThreadPtr())); - - if (exe_ctx.HasThreadScope()) - { - Thread *thread = exe_ctx.GetThreadPtr(); - sb_error.SetError (thread->UnwindInnermostExpression()); - if (sb_error.Success()) - thread->SetSelectedFrameByIndex(0, false); - } + if (log) + log->Printf("SBThread(%p)::UnwindExpressionEvaluation", + static_cast(exe_ctx.GetThreadPtr())); - return sb_error; + if (exe_ctx.HasThreadScope()) { + Thread *thread = exe_ctx.GetThreadPtr(); + sb_error.SetError(thread->UnwindInnermostExpression()); + if (sb_error.Success()) + thread->SetSelectedFrameByIndex(0, false); + } + return sb_error; } -bool -SBThread::Suspend() -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - bool result = false; - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - exe_ctx.GetThreadPtr()->SetResumeState (eStateSuspended); - result = true; - } - else - { - if (log) - log->Printf ("SBThread(%p)::Suspend() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +bool SBThread::Suspend() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + bool result = false; + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + exe_ctx.GetThreadPtr()->SetResumeState(eStateSuspended); + result = true; + } else { + if (log) + log->Printf("SBThread(%p)::Suspend() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } - if (log) - log->Printf ("SBThread(%p)::Suspend() => %i", - static_cast(exe_ctx.GetThreadPtr()), result); - return result; + } + if (log) + log->Printf("SBThread(%p)::Suspend() => %i", + static_cast(exe_ctx.GetThreadPtr()), result); + return result; } -bool -SBThread::Resume () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - bool result = false; - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - const bool override_suspend = true; - exe_ctx.GetThreadPtr()->SetResumeState (eStateRunning, override_suspend); - result = true; - } - else - { - if (log) - log->Printf ("SBThread(%p)::Resume() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +bool SBThread::Resume() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + bool result = false; + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + const bool override_suspend = true; + exe_ctx.GetThreadPtr()->SetResumeState(eStateRunning, override_suspend); + result = true; + } else { + if (log) + log->Printf("SBThread(%p)::Resume() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } - if (log) - log->Printf ("SBThread(%p)::Resume() => %i", - static_cast(exe_ctx.GetThreadPtr()), result); - return result; + } + if (log) + log->Printf("SBThread(%p)::Resume() => %i", + static_cast(exe_ctx.GetThreadPtr()), result); + return result; } -bool -SBThread::IsSuspended() -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); +bool SBThread::IsSuspended() { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (exe_ctx.HasThreadScope()) - return exe_ctx.GetThreadPtr()->GetResumeState () == eStateSuspended; - return false; + if (exe_ctx.HasThreadScope()) + return exe_ctx.GetThreadPtr()->GetResumeState() == eStateSuspended; + return false; } -bool -SBThread::IsStopped() -{ - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); +bool SBThread::IsStopped() { + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (exe_ctx.HasThreadScope()) - return StateIsStoppedState(exe_ctx.GetThreadPtr()->GetState(), true); - return false; + if (exe_ctx.HasThreadScope()) + return StateIsStoppedState(exe_ctx.GetThreadPtr()->GetState(), true); + return false; } -SBProcess -SBThread::GetProcess () -{ - SBProcess sb_process; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - // Have to go up to the target so we can get a shared pointer to our process... - sb_process.SetSP (exe_ctx.GetProcessSP()); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - SBStream frame_desc_strm; - sb_process.GetDescription (frame_desc_strm); - log->Printf ("SBThread(%p)::GetProcess () => SBProcess(%p): %s", - static_cast(exe_ctx.GetThreadPtr()), - static_cast(sb_process.GetSP().get()), - frame_desc_strm.GetData()); - } - - return sb_process; +SBProcess SBThread::GetProcess() { + SBProcess sb_process; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + // Have to go up to the target so we can get a shared pointer to our + // process... + sb_process.SetSP(exe_ctx.GetProcessSP()); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + SBStream frame_desc_strm; + sb_process.GetDescription(frame_desc_strm); + log->Printf("SBThread(%p)::GetProcess () => SBProcess(%p): %s", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(sb_process.GetSP().get()), + frame_desc_strm.GetData()); + } + + return sb_process; } -uint32_t -SBThread::GetNumFrames () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - uint32_t num_frames = 0; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - num_frames = exe_ctx.GetThreadPtr()->GetStackFrameCount(); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetNumFrames() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +uint32_t SBThread::GetNumFrames() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + uint32_t num_frames = 0; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + num_frames = exe_ctx.GetThreadPtr()->GetStackFrameCount(); + } else { + if (log) + log->Printf("SBThread(%p)::GetNumFrames() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - log->Printf ("SBThread(%p)::GetNumFrames () => %u", - static_cast(exe_ctx.GetThreadPtr()), num_frames); + if (log) + log->Printf("SBThread(%p)::GetNumFrames () => %u", + static_cast(exe_ctx.GetThreadPtr()), num_frames); - return num_frames; + return num_frames; } -SBFrame -SBThread::GetFrameAtIndex (uint32_t idx) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBFrame sb_frame; - StackFrameSP frame_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - frame_sp = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex (idx); - sb_frame.SetFrameSP (frame_sp); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetFrameAtIndex() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +SBFrame SBThread::GetFrameAtIndex(uint32_t idx) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + frame_sp = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(idx); + sb_frame.SetFrameSP(frame_sp); + } else { + if (log) + log->Printf( + "SBThread(%p)::GetFrameAtIndex() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - { - SBStream frame_desc_strm; - sb_frame.GetDescription (frame_desc_strm); - log->Printf ("SBThread(%p)::GetFrameAtIndex (idx=%d) => SBFrame(%p): %s", - static_cast(exe_ctx.GetThreadPtr()), idx, - static_cast(frame_sp.get()), - frame_desc_strm.GetData()); - } + if (log) { + SBStream frame_desc_strm; + sb_frame.GetDescription(frame_desc_strm); + log->Printf("SBThread(%p)::GetFrameAtIndex (idx=%d) => SBFrame(%p): %s", + static_cast(exe_ctx.GetThreadPtr()), idx, + static_cast(frame_sp.get()), frame_desc_strm.GetData()); + } - return sb_frame; + return sb_frame; } -lldb::SBFrame -SBThread::GetSelectedFrame () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBFrame sb_frame; - StackFrameSP frame_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - frame_sp = exe_ctx.GetThreadPtr()->GetSelectedFrame (); - sb_frame.SetFrameSP (frame_sp); - } - else - { - if (log) - log->Printf ("SBThread(%p)::GetSelectedFrame() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } +lldb::SBFrame SBThread::GetSelectedFrame() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + frame_sp = exe_ctx.GetThreadPtr()->GetSelectedFrame(); + sb_frame.SetFrameSP(frame_sp); + } else { + if (log) + log->Printf( + "SBThread(%p)::GetSelectedFrame() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log) - { - SBStream frame_desc_strm; - sb_frame.GetDescription (frame_desc_strm); - log->Printf ("SBThread(%p)::GetSelectedFrame () => SBFrame(%p): %s", - static_cast(exe_ctx.GetThreadPtr()), - static_cast(frame_sp.get()), - frame_desc_strm.GetData()); - } + if (log) { + SBStream frame_desc_strm; + sb_frame.GetDescription(frame_desc_strm); + log->Printf("SBThread(%p)::GetSelectedFrame () => SBFrame(%p): %s", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(frame_sp.get()), frame_desc_strm.GetData()); + } - return sb_frame; + return sb_frame; } -lldb::SBFrame -SBThread::SetSelectedFrame (uint32_t idx) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - SBFrame sb_frame; - StackFrameSP frame_sp; - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - Thread *thread = exe_ctx.GetThreadPtr(); - frame_sp = thread->GetStackFrameAtIndex (idx); - if (frame_sp) - { - thread->SetSelectedFrame (frame_sp.get()); - sb_frame.SetFrameSP (frame_sp); - } - } - else - { - if (log) - log->Printf ("SBThread(%p)::SetSelectedFrame() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } - } - - if (log) - { - SBStream frame_desc_strm; - sb_frame.GetDescription (frame_desc_strm); - log->Printf ("SBThread(%p)::SetSelectedFrame (idx=%u) => SBFrame(%p): %s", - static_cast(exe_ctx.GetThreadPtr()), idx, - static_cast(frame_sp.get()), - frame_desc_strm.GetData()); +lldb::SBFrame SBThread::SetSelectedFrame(uint32_t idx) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + SBFrame sb_frame; + StackFrameSP frame_sp; + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + Thread *thread = exe_ctx.GetThreadPtr(); + frame_sp = thread->GetStackFrameAtIndex(idx); + if (frame_sp) { + thread->SetSelectedFrame(frame_sp.get()); + sb_frame.SetFrameSP(frame_sp); + } + } else { + if (log) + log->Printf( + "SBThread(%p)::SetSelectedFrame() => error: process is running", + static_cast(exe_ctx.GetThreadPtr())); } - return sb_frame; + } + + if (log) { + SBStream frame_desc_strm; + sb_frame.GetDescription(frame_desc_strm); + log->Printf("SBThread(%p)::SetSelectedFrame (idx=%u) => SBFrame(%p): %s", + static_cast(exe_ctx.GetThreadPtr()), idx, + static_cast(frame_sp.get()), frame_desc_strm.GetData()); + } + return sb_frame; } -bool -SBThread::EventIsThreadEvent (const SBEvent &event) -{ - return Thread::ThreadEventData::GetEventDataFromEvent(event.get()) != NULL; +bool SBThread::EventIsThreadEvent(const SBEvent &event) { + return Thread::ThreadEventData::GetEventDataFromEvent(event.get()) != NULL; } -SBFrame -SBThread::GetStackFrameFromEvent (const SBEvent &event) -{ - return Thread::ThreadEventData::GetStackFrameFromEvent (event.get()); - +SBFrame SBThread::GetStackFrameFromEvent(const SBEvent &event) { + return Thread::ThreadEventData::GetStackFrameFromEvent(event.get()); } -SBThread -SBThread::GetThreadFromEvent (const SBEvent &event) -{ - return Thread::ThreadEventData::GetThreadFromEvent (event.get()); +SBThread SBThread::GetThreadFromEvent(const SBEvent &event) { + return Thread::ThreadEventData::GetThreadFromEvent(event.get()); } -bool -SBThread::operator == (const SBThread &rhs) const -{ - return m_opaque_sp->GetThreadSP().get() == rhs.m_opaque_sp->GetThreadSP().get(); +bool SBThread::operator==(const SBThread &rhs) const { + return m_opaque_sp->GetThreadSP().get() == + rhs.m_opaque_sp->GetThreadSP().get(); } -bool -SBThread::operator != (const SBThread &rhs) const -{ - return m_opaque_sp->GetThreadSP().get() != rhs.m_opaque_sp->GetThreadSP().get(); +bool SBThread::operator!=(const SBThread &rhs) const { + return m_opaque_sp->GetThreadSP().get() != + rhs.m_opaque_sp->GetThreadSP().get(); } -bool -SBThread::GetStatus (SBStream &status) const -{ - Stream &strm = status.ref(); +bool SBThread::GetStatus(SBStream &status) const { + Stream &strm = status.ref(); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (exe_ctx.HasThreadScope()) - { - exe_ctx.GetThreadPtr()->GetStatus(strm, 0, 1, 1); - } - else - strm.PutCString ("No status"); - - return true; + if (exe_ctx.HasThreadScope()) { + exe_ctx.GetThreadPtr()->GetStatus(strm, 0, 1, 1); + } else + strm.PutCString("No status"); + + return true; } -bool -SBThread::GetDescription (SBStream &description) const -{ - Stream &strm = description.ref(); +bool SBThread::GetDescription(SBStream &description) const { + Stream &strm = description.ref(); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - if (exe_ctx.HasThreadScope()) - { - exe_ctx.GetThreadPtr()->DumpUsingSettingsFormat(strm, LLDB_INVALID_THREAD_ID); - //strm.Printf("SBThread: tid = 0x%4.4" PRIx64, exe_ctx.GetThreadPtr()->GetID()); - } - else - strm.PutCString ("No value"); - - return true; + if (exe_ctx.HasThreadScope()) { + exe_ctx.GetThreadPtr()->DumpUsingSettingsFormat(strm, + LLDB_INVALID_THREAD_ID); + // strm.Printf("SBThread: tid = 0x%4.4" PRIx64, + // exe_ctx.GetThreadPtr()->GetID()); + } else + strm.PutCString("No value"); + + return true; } -SBThread -SBThread::GetExtendedBacktraceThread (const char *type) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - std::unique_lock lock; - ExecutionContext exe_ctx(m_opaque_sp.get(), lock); - SBThread sb_origin_thread; - - if (exe_ctx.HasThreadScope()) - { - Process::StopLocker stop_locker; - if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) - { - ThreadSP real_thread(exe_ctx.GetThreadSP()); - if (real_thread) - { - ConstString type_const (type); - Process *process = exe_ctx.GetProcessPtr(); - if (process) - { - SystemRuntime *runtime = process->GetSystemRuntime(); - if (runtime) - { - ThreadSP new_thread_sp (runtime->GetExtendedBacktraceThread (real_thread, type_const)); - if (new_thread_sp) - { - // Save this in the Process' ExtendedThreadList so a strong pointer retains the - // object. - process->GetExtendedThreadList().AddThread (new_thread_sp); - sb_origin_thread.SetThread (new_thread_sp); - if (log) - { - const char *queue_name = new_thread_sp->GetQueueName(); - if (queue_name == NULL) - queue_name = ""; - log->Printf ("SBThread(%p)::GetExtendedBacktraceThread() => new extended Thread " - "created (%p) with queue_id 0x%" PRIx64 " queue name '%s'", - static_cast(exe_ctx.GetThreadPtr()), - static_cast(new_thread_sp.get()), - new_thread_sp->GetQueueID(), - queue_name); - } - } - } - } +SBThread SBThread::GetExtendedBacktraceThread(const char *type) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + std::unique_lock lock; + ExecutionContext exe_ctx(m_opaque_sp.get(), lock); + SBThread sb_origin_thread; + + if (exe_ctx.HasThreadScope()) { + Process::StopLocker stop_locker; + if (stop_locker.TryLock(&exe_ctx.GetProcessPtr()->GetRunLock())) { + ThreadSP real_thread(exe_ctx.GetThreadSP()); + if (real_thread) { + ConstString type_const(type); + Process *process = exe_ctx.GetProcessPtr(); + if (process) { + SystemRuntime *runtime = process->GetSystemRuntime(); + if (runtime) { + ThreadSP new_thread_sp( + runtime->GetExtendedBacktraceThread(real_thread, type_const)); + if (new_thread_sp) { + // Save this in the Process' ExtendedThreadList so a strong + // pointer retains the + // object. + process->GetExtendedThreadList().AddThread(new_thread_sp); + sb_origin_thread.SetThread(new_thread_sp); + if (log) { + const char *queue_name = new_thread_sp->GetQueueName(); + if (queue_name == NULL) + queue_name = ""; + log->Printf("SBThread(%p)::GetExtendedBacktraceThread() => new " + "extended Thread " + "created (%p) with queue_id 0x%" PRIx64 + " queue name '%s'", + static_cast(exe_ctx.GetThreadPtr()), + static_cast(new_thread_sp.get()), + new_thread_sp->GetQueueID(), queue_name); + } } + } } - else - { - if (log) - log->Printf ("SBThread(%p)::GetExtendedBacktraceThread() => error: process is running", - static_cast(exe_ctx.GetThreadPtr())); - } + } + } else { + if (log) + log->Printf("SBThread(%p)::GetExtendedBacktraceThread() => error: " + "process is running", + static_cast(exe_ctx.GetThreadPtr())); } + } - if (log && sb_origin_thread.IsValid() == false) - log->Printf("SBThread(%p)::GetExtendedBacktraceThread() is not returning a Valid thread", - static_cast(exe_ctx.GetThreadPtr())); - return sb_origin_thread; + if (log && sb_origin_thread.IsValid() == false) + log->Printf("SBThread(%p)::GetExtendedBacktraceThread() is not returning a " + "Valid thread", + static_cast(exe_ctx.GetThreadPtr())); + return sb_origin_thread; } -uint32_t -SBThread::GetExtendedBacktraceOriginatingIndexID () -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp->GetExtendedBacktraceOriginatingIndexID(); - return LLDB_INVALID_INDEX32; +uint32_t SBThread::GetExtendedBacktraceOriginatingIndexID() { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->GetExtendedBacktraceOriginatingIndexID(); + return LLDB_INVALID_INDEX32; } -bool -SBThread::SafeToCallFunctions () -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp->SafeToCallFunctions(); - return true; +bool SBThread::SafeToCallFunctions() { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp->SafeToCallFunctions(); + return true; } -lldb_private::Thread * -SBThread::operator->() -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp.get(); - else - return NULL; +lldb_private::Thread *SBThread::operator->() { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp.get(); + else + return NULL; } -lldb_private::Thread * -SBThread::get() -{ - ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); - if (thread_sp) - return thread_sp.get(); - else - return NULL; +lldb_private::Thread *SBThread::get() { + ThreadSP thread_sp(m_opaque_sp->GetThreadSP()); + if (thread_sp) + return thread_sp.get(); + else + return NULL; } - diff --git a/lldb/source/API/SBThreadCollection.cpp b/lldb/source/API/SBThreadCollection.cpp index 841f93253a5..c424d47b409 100644 --- a/lldb/source/API/SBThreadCollection.cpp +++ b/lldb/source/API/SBThreadCollection.cpp @@ -14,84 +14,54 @@ using namespace lldb; using namespace lldb_private; +SBThreadCollection::SBThreadCollection() : m_opaque_sp() {} -SBThreadCollection::SBThreadCollection () : - m_opaque_sp() -{ -} +SBThreadCollection::SBThreadCollection(const SBThreadCollection &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBThreadCollection::SBThreadCollection(const SBThreadCollection &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ +const SBThreadCollection &SBThreadCollection:: +operator=(const SBThreadCollection &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -const SBThreadCollection & -SBThreadCollection::operator = (const SBThreadCollection &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; -} +SBThreadCollection::SBThreadCollection(const ThreadCollectionSP &threads) + : m_opaque_sp(threads) {} -SBThreadCollection::SBThreadCollection (const ThreadCollectionSP &threads) : - m_opaque_sp(threads) -{ -} +SBThreadCollection::~SBThreadCollection() {} -SBThreadCollection::~SBThreadCollection () -{ +void SBThreadCollection::SetOpaque(const lldb::ThreadCollectionSP &threads) { + m_opaque_sp = threads; } -void -SBThreadCollection::SetOpaque (const lldb::ThreadCollectionSP &threads) -{ - m_opaque_sp = threads; +lldb_private::ThreadCollection *SBThreadCollection::get() const { + return m_opaque_sp.get(); } -lldb_private::ThreadCollection * -SBThreadCollection::get() const -{ - return m_opaque_sp.get(); +lldb_private::ThreadCollection *SBThreadCollection::operator->() const { + return m_opaque_sp.operator->(); } -lldb_private::ThreadCollection * -SBThreadCollection::operator->() const -{ - return m_opaque_sp.operator->(); +lldb::ThreadCollectionSP &SBThreadCollection::operator*() { + return m_opaque_sp; } -lldb::ThreadCollectionSP & -SBThreadCollection::operator*() -{ - return m_opaque_sp; +const lldb::ThreadCollectionSP &SBThreadCollection::operator*() const { + return m_opaque_sp; } -const lldb::ThreadCollectionSP & -SBThreadCollection::operator*() const -{ - return m_opaque_sp; -} - - -bool -SBThreadCollection::IsValid () const -{ - return m_opaque_sp.get() != NULL; -} +bool SBThreadCollection::IsValid() const { return m_opaque_sp.get() != NULL; } -size_t -SBThreadCollection::GetSize () -{ - if (m_opaque_sp) - return m_opaque_sp->GetSize(); - return 0; +size_t SBThreadCollection::GetSize() { + if (m_opaque_sp) + return m_opaque_sp->GetSize(); + return 0; } -SBThread -SBThreadCollection::GetThreadAtIndex(size_t idx) -{ - SBThread thread; - if (m_opaque_sp && idx < m_opaque_sp->GetSize()) - thread = m_opaque_sp->GetThreadAtIndex(idx); - return thread; +SBThread SBThreadCollection::GetThreadAtIndex(size_t idx) { + SBThread thread; + if (m_opaque_sp && idx < m_opaque_sp->GetSize()) + thread = m_opaque_sp->GetThreadAtIndex(idx); + return thread; } diff --git a/lldb/source/API/SBThreadPlan.cpp b/lldb/source/API/SBThreadPlan.cpp index 2b0811b1729..9977d199a94 100644 --- a/lldb/source/API/SBThreadPlan.cpp +++ b/lldb/source/API/SBThreadPlan.cpp @@ -9,9 +9,9 @@ #include "lldb/API/SBThread.h" -#include "lldb/API/SBSymbolContext.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBSymbolContext.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/State.h" @@ -19,22 +19,21 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Core/StructuredData.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Target/SystemRuntime.h" -#include "lldb/Target/Thread.h" -#include "lldb/Target/ThreadPlan.h" +#include "lldb/Symbol/CompileUnit.h" +#include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Queue.h" -#include "lldb/Symbol/SymbolContext.h" -#include "lldb/Symbol/CompileUnit.h" #include "lldb/Target/StopInfo.h" +#include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/ThreadPlan.h" #include "lldb/Target/ThreadPlan.h" #include "lldb/Target/ThreadPlanPython.h" +#include "lldb/Target/ThreadPlanStepInRange.h" #include "lldb/Target/ThreadPlanStepInstruction.h" #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Target/ThreadPlanStepRange.h" -#include "lldb/Target/ThreadPlanStepInRange.h" - #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" @@ -50,243 +49,163 @@ using namespace lldb_private; //---------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------- -SBThreadPlan::SBThreadPlan () -{ -} +SBThreadPlan::SBThreadPlan() {} -SBThreadPlan::SBThreadPlan (const ThreadPlanSP& lldb_object_sp) : - m_opaque_sp (lldb_object_sp) -{ -} +SBThreadPlan::SBThreadPlan(const ThreadPlanSP &lldb_object_sp) + : m_opaque_sp(lldb_object_sp) {} -SBThreadPlan::SBThreadPlan (const SBThreadPlan &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ - -} +SBThreadPlan::SBThreadPlan(const SBThreadPlan &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBThreadPlan::SBThreadPlan (lldb::SBThread &sb_thread, const char *class_name) -{ - Thread *thread = sb_thread.get(); - if (thread) - m_opaque_sp.reset(new ThreadPlanPython(*thread, class_name)); +SBThreadPlan::SBThreadPlan(lldb::SBThread &sb_thread, const char *class_name) { + Thread *thread = sb_thread.get(); + if (thread) + m_opaque_sp.reset(new ThreadPlanPython(*thread, class_name)); } //---------------------------------------------------------------------- // Assignment operator //---------------------------------------------------------------------- -const lldb::SBThreadPlan & -SBThreadPlan::operator = (const SBThreadPlan &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const lldb::SBThreadPlan &SBThreadPlan::operator=(const SBThreadPlan &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -SBThreadPlan::~SBThreadPlan() -{ -} +SBThreadPlan::~SBThreadPlan() {} -lldb_private::ThreadPlan * -SBThreadPlan::get() -{ - return m_opaque_sp.get(); -} +lldb_private::ThreadPlan *SBThreadPlan::get() { return m_opaque_sp.get(); } -bool -SBThreadPlan::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} +bool SBThreadPlan::IsValid() const { return m_opaque_sp.get() != NULL; } -void -SBThreadPlan::Clear () -{ - m_opaque_sp.reset(); -} +void SBThreadPlan::Clear() { m_opaque_sp.reset(); } -lldb::StopReason -SBThreadPlan::GetStopReason() -{ - return eStopReasonNone; -} +lldb::StopReason SBThreadPlan::GetStopReason() { return eStopReasonNone; } -size_t -SBThreadPlan::GetStopReasonDataCount() -{ - return 0; -} +size_t SBThreadPlan::GetStopReasonDataCount() { return 0; } -uint64_t -SBThreadPlan::GetStopReasonDataAtIndex(uint32_t idx) -{ - return 0; -} +uint64_t SBThreadPlan::GetStopReasonDataAtIndex(uint32_t idx) { return 0; } -SBThread -SBThreadPlan::GetThread () const -{ - if (m_opaque_sp) - { - return SBThread(m_opaque_sp->GetThread().shared_from_this()); - } - else - return SBThread(); +SBThread SBThreadPlan::GetThread() const { + if (m_opaque_sp) { + return SBThread(m_opaque_sp->GetThread().shared_from_this()); + } else + return SBThread(); } -bool -SBThreadPlan::GetDescription (lldb::SBStream &description) const -{ - if (m_opaque_sp) - { - m_opaque_sp->GetDescription(description.get(), eDescriptionLevelFull); - } - else - { - description.Printf("Empty SBThreadPlan"); - } - return true; +bool SBThreadPlan::GetDescription(lldb::SBStream &description) const { + if (m_opaque_sp) { + m_opaque_sp->GetDescription(description.get(), eDescriptionLevelFull); + } else { + description.Printf("Empty SBThreadPlan"); + } + return true; } -void -SBThreadPlan::SetThreadPlan (const ThreadPlanSP& lldb_object_sp) -{ - m_opaque_sp = lldb_object_sp; +void SBThreadPlan::SetThreadPlan(const ThreadPlanSP &lldb_object_sp) { + m_opaque_sp = lldb_object_sp; } -void -SBThreadPlan::SetPlanComplete (bool success) -{ - if (m_opaque_sp) - m_opaque_sp->SetPlanComplete (success); +void SBThreadPlan::SetPlanComplete(bool success) { + if (m_opaque_sp) + m_opaque_sp->SetPlanComplete(success); } -bool -SBThreadPlan::IsPlanComplete() -{ - if (m_opaque_sp) - return m_opaque_sp->IsPlanComplete(); - else - return true; +bool SBThreadPlan::IsPlanComplete() { + if (m_opaque_sp) + return m_opaque_sp->IsPlanComplete(); + else + return true; } -bool -SBThreadPlan::IsPlanStale() -{ - if (m_opaque_sp) - return m_opaque_sp->IsPlanStale(); - else - return true; +bool SBThreadPlan::IsPlanStale() { + if (m_opaque_sp) + return m_opaque_sp->IsPlanStale(); + else + return true; } -bool -SBThreadPlan::IsValid() -{ - if (m_opaque_sp) - return m_opaque_sp->ValidatePlan(nullptr); - else - return false; +bool SBThreadPlan::IsValid() { + if (m_opaque_sp) + return m_opaque_sp->ValidatePlan(nullptr); + else + return false; } - // This section allows an SBThreadPlan to push another of the common types of plans... - // - // FIXME, you should only be able to queue thread plans from inside the methods of a - // Scripted Thread Plan. Need a way to enforce that. +// This section allows an SBThreadPlan to push another of the common types of +// plans... +// +// FIXME, you should only be able to queue thread plans from inside the methods +// of a +// Scripted Thread Plan. Need a way to enforce that. SBThreadPlan -SBThreadPlan::QueueThreadPlanForStepOverRange (SBAddress &sb_start_address, - lldb::addr_t size) -{ - if (m_opaque_sp) - { - Address *start_address = sb_start_address.get(); - if (!start_address) - { - return SBThreadPlan(); - } - - AddressRange range (*start_address, size); - SymbolContext sc; - start_address->CalculateSymbolContext(&sc); - return SBThreadPlan (m_opaque_sp->GetThread().QueueThreadPlanForStepOverRange (false, - range, - sc, - eAllThreads)); - } - else - { - return SBThreadPlan(); +SBThreadPlan::QueueThreadPlanForStepOverRange(SBAddress &sb_start_address, + lldb::addr_t size) { + if (m_opaque_sp) { + Address *start_address = sb_start_address.get(); + if (!start_address) { + return SBThreadPlan(); } + + AddressRange range(*start_address, size); + SymbolContext sc; + start_address->CalculateSymbolContext(&sc); + return SBThreadPlan( + m_opaque_sp->GetThread().QueueThreadPlanForStepOverRange( + false, range, sc, eAllThreads)); + } else { + return SBThreadPlan(); + } } SBThreadPlan -SBThreadPlan::QueueThreadPlanForStepInRange (SBAddress &sb_start_address, - lldb::addr_t size) -{ - if (m_opaque_sp) - { - Address *start_address = sb_start_address.get(); - if (!start_address) - { - return SBThreadPlan(); - } - - AddressRange range (*start_address, size); - SymbolContext sc; - start_address->CalculateSymbolContext(&sc); - return SBThreadPlan (m_opaque_sp->GetThread().QueueThreadPlanForStepInRange (false, - range, - sc, - NULL, - eAllThreads)); - } - else - { - return SBThreadPlan(); +SBThreadPlan::QueueThreadPlanForStepInRange(SBAddress &sb_start_address, + lldb::addr_t size) { + if (m_opaque_sp) { + Address *start_address = sb_start_address.get(); + if (!start_address) { + return SBThreadPlan(); } + + AddressRange range(*start_address, size); + SymbolContext sc; + start_address->CalculateSymbolContext(&sc); + return SBThreadPlan(m_opaque_sp->GetThread().QueueThreadPlanForStepInRange( + false, range, sc, NULL, eAllThreads)); + } else { + return SBThreadPlan(); + } } SBThreadPlan -SBThreadPlan::QueueThreadPlanForStepOut (uint32_t frame_idx_to_step_to, bool first_insn) -{ - if (m_opaque_sp) - { - SymbolContext sc; - sc = m_opaque_sp->GetThread().GetStackFrameAtIndex(0)->GetSymbolContext(lldb::eSymbolContextEverything); - return SBThreadPlan (m_opaque_sp->GetThread().QueueThreadPlanForStepOut (false, - &sc, - first_insn, - false, - eVoteYes, - eVoteNoOpinion, - frame_idx_to_step_to)); - } - else - { - return SBThreadPlan(); - } +SBThreadPlan::QueueThreadPlanForStepOut(uint32_t frame_idx_to_step_to, + bool first_insn) { + if (m_opaque_sp) { + SymbolContext sc; + sc = m_opaque_sp->GetThread().GetStackFrameAtIndex(0)->GetSymbolContext( + lldb::eSymbolContextEverything); + return SBThreadPlan(m_opaque_sp->GetThread().QueueThreadPlanForStepOut( + false, &sc, first_insn, false, eVoteYes, eVoteNoOpinion, + frame_idx_to_step_to)); + } else { + return SBThreadPlan(); + } } SBThreadPlan -SBThreadPlan::QueueThreadPlanForRunToAddress (SBAddress sb_address) -{ - if (m_opaque_sp) - { - Address *address = sb_address.get(); - if (!address) - return SBThreadPlan(); - - return SBThreadPlan (m_opaque_sp->GetThread().QueueThreadPlanForRunToAddress (false, - *address, - false)); - } - else - { - return SBThreadPlan(); - } +SBThreadPlan::QueueThreadPlanForRunToAddress(SBAddress sb_address) { + if (m_opaque_sp) { + Address *address = sb_address.get(); + if (!address) + return SBThreadPlan(); + + return SBThreadPlan(m_opaque_sp->GetThread().QueueThreadPlanForRunToAddress( + false, *address, false)); + } else { + return SBThreadPlan(); + } } - - diff --git a/lldb/source/API/SBType.cpp b/lldb/source/API/SBType.cpp index a786d32c73c..ca63a875292 100644 --- a/lldb/source/API/SBType.cpp +++ b/lldb/source/API/SBType.cpp @@ -7,10 +7,10 @@ // //===----------------------------------------------------------------------===// -#include "lldb/API/SBDefines.h" #include "lldb/API/SBType.h" -#include "lldb/API/SBTypeEnumMember.h" +#include "lldb/API/SBDefines.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBTypeEnumMember.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/Log.h" #include "lldb/Core/Mangled.h" @@ -24,877 +24,646 @@ using namespace lldb; using namespace lldb_private; -SBType::SBType() : - m_opaque_sp() -{ -} +SBType::SBType() : m_opaque_sp() {} -SBType::SBType (const CompilerType &type) : - m_opaque_sp(new TypeImpl(CompilerType(type.GetTypeSystem(), - type.GetOpaqueQualType()))) -{ -} +SBType::SBType(const CompilerType &type) + : m_opaque_sp(new TypeImpl( + CompilerType(type.GetTypeSystem(), type.GetOpaqueQualType()))) {} -SBType::SBType (const lldb::TypeSP &type_sp) : - m_opaque_sp(new TypeImpl(type_sp)) -{ -} +SBType::SBType(const lldb::TypeSP &type_sp) + : m_opaque_sp(new TypeImpl(type_sp)) {} -SBType::SBType (const lldb::TypeImplSP &type_impl_sp) : - m_opaque_sp(type_impl_sp) -{ -} - +SBType::SBType(const lldb::TypeImplSP &type_impl_sp) + : m_opaque_sp(type_impl_sp) {} -SBType::SBType (const SBType &rhs) : - m_opaque_sp() -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } +SBType::SBType(const SBType &rhs) : m_opaque_sp() { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } } - -//SBType::SBType (TypeImpl* impl) : +// SBType::SBType (TypeImpl* impl) : // m_opaque_ap(impl) //{} // -bool -SBType::operator == (SBType &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - if (rhs.IsValid() == false) - return false; - - return *m_opaque_sp.get() == *rhs.m_opaque_sp.get(); -} - -bool -SBType::operator != (SBType &rhs) -{ - if (IsValid() == false) - return rhs.IsValid(); - - if (rhs.IsValid() == false) - return true; - - return *m_opaque_sp.get() != *rhs.m_opaque_sp.get(); -} - -lldb::TypeImplSP -SBType::GetSP () -{ - return m_opaque_sp; -} - - -void -SBType::SetSP (const lldb::TypeImplSP &type_impl_sp) -{ - m_opaque_sp = type_impl_sp; -} - -SBType & -SBType::operator = (const SBType &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +bool SBType::operator==(SBType &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + if (rhs.IsValid() == false) + return false; + + return *m_opaque_sp.get() == *rhs.m_opaque_sp.get(); } -SBType::~SBType () -{} +bool SBType::operator!=(SBType &rhs) { + if (IsValid() == false) + return rhs.IsValid(); + + if (rhs.IsValid() == false) + return true; -TypeImpl & -SBType::ref () -{ - if (m_opaque_sp.get() == NULL) - m_opaque_sp.reset (new TypeImpl()); - return *m_opaque_sp; + return *m_opaque_sp.get() != *rhs.m_opaque_sp.get(); } -const TypeImpl & -SBType::ref () const -{ - // "const SBAddress &addr" should already have checked "addr.IsValid()" - // prior to calling this function. In case you didn't we will assert - // and die to let you know. - assert (m_opaque_sp.get()); - return *m_opaque_sp; +lldb::TypeImplSP SBType::GetSP() { return m_opaque_sp; } + +void SBType::SetSP(const lldb::TypeImplSP &type_impl_sp) { + m_opaque_sp = type_impl_sp; } -bool -SBType::IsValid() const -{ - if (m_opaque_sp.get() == NULL) - return false; - - return m_opaque_sp->IsValid(); +SBType &SBType::operator=(const SBType &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -uint64_t -SBType::GetByteSize() -{ - if (!IsValid()) - return 0; - - return m_opaque_sp->GetCompilerType(false).GetByteSize(nullptr); - -} - -bool -SBType::IsPointerType() -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsPointerType(); -} - -bool -SBType::IsArrayType() -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsArrayType(nullptr, nullptr, nullptr); -} - -bool -SBType::IsVectorType() -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsVectorType(nullptr, nullptr); -} - -bool -SBType::IsReferenceType() -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsReferenceType(); -} - -SBType -SBType::GetPointerType() -{ - if (!IsValid()) - return SBType(); - - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointerType()))); -} - -SBType -SBType::GetPointeeType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointeeType()))); -} - -SBType -SBType::GetReferenceType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetReferenceType()))); -} - -SBType -SBType::GetTypedefedType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetTypedefedType()))); -} - -SBType -SBType::GetDereferencedType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetDereferencedType()))); -} - -SBType -SBType::GetArrayElementType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayElementType()))); +SBType::~SBType() {} + +TypeImpl &SBType::ref() { + if (m_opaque_sp.get() == NULL) + m_opaque_sp.reset(new TypeImpl()); + return *m_opaque_sp; } - -SBType -SBType::GetArrayType (uint64_t size) -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayType(size)))); + +const TypeImpl &SBType::ref() const { + // "const SBAddress &addr" should already have checked "addr.IsValid()" + // prior to calling this function. In case you didn't we will assert + // and die to let you know. + assert(m_opaque_sp.get()); + return *m_opaque_sp; } -SBType -SBType::GetVectorElementType () -{ - SBType type_sb; - if (IsValid()) - { - CompilerType vector_element_type; - if (m_opaque_sp->GetCompilerType(true).IsVectorType(&vector_element_type, nullptr)) - type_sb.SetSP(TypeImplSP(new TypeImpl(vector_element_type))); - } - return type_sb; +bool SBType::IsValid() const { + if (m_opaque_sp.get() == NULL) + return false; + + return m_opaque_sp->IsValid(); } -bool -SBType::IsFunctionType () -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsFunctionType(); +uint64_t SBType::GetByteSize() { + if (!IsValid()) + return 0; + + return m_opaque_sp->GetCompilerType(false).GetByteSize(nullptr); } -bool -SBType::IsPolymorphicClass () -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsPolymorphicClass(); +bool SBType::IsPointerType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsPointerType(); } -bool -SBType::IsTypedefType () -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsTypedefType(); +bool SBType::IsArrayType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsArrayType(nullptr, nullptr, + nullptr); } -bool -SBType::IsAnonymousType () -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(true).IsAnonymousType(); +bool SBType::IsVectorType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsVectorType(nullptr, nullptr); } -lldb::SBType -SBType::GetFunctionReturnType () -{ - if (IsValid()) - { - CompilerType return_type (m_opaque_sp->GetCompilerType(true).GetFunctionReturnType()); - if (return_type.IsValid()) - return SBType(return_type); - } - return lldb::SBType(); -} - -lldb::SBTypeList -SBType::GetFunctionArgumentTypes () -{ - SBTypeList sb_type_list; - if (IsValid()) - { - CompilerType func_type(m_opaque_sp->GetCompilerType(true)); - size_t count = func_type.GetNumberOfFunctionArguments(); - for (size_t i = 0; - i < count; - i++) - { - sb_type_list.Append(SBType(func_type.GetFunctionArgumentAtIndex(i))); - } - } - return sb_type_list; +bool SBType::IsReferenceType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsReferenceType(); } -uint32_t -SBType::GetNumberOfMemberFunctions () -{ - if (IsValid()) - { - return m_opaque_sp->GetCompilerType(true).GetNumMemberFunctions(); - } - return 0; +SBType SBType::GetPointerType() { + if (!IsValid()) + return SBType(); + + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointerType()))); } -lldb::SBTypeMemberFunction -SBType::GetMemberFunctionAtIndex (uint32_t idx) -{ - SBTypeMemberFunction sb_func_type; - if (IsValid()) - sb_func_type.reset(new TypeMemberFunctionImpl(m_opaque_sp->GetCompilerType(true).GetMemberFunctionAtIndex(idx))); - return sb_func_type; +SBType SBType::GetPointeeType() { + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetPointeeType()))); } -lldb::SBType -SBType::GetUnqualifiedType() -{ - if (!IsValid()) - return SBType(); - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetUnqualifiedType()))); +SBType SBType::GetReferenceType() { + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetReferenceType()))); } -lldb::SBType -SBType::GetCanonicalType() -{ - if (IsValid()) - return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCanonicalType()))); +SBType SBType::GetTypedefedType() { + if (!IsValid()) return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetTypedefedType()))); } +SBType SBType::GetDereferencedType() { + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetDereferencedType()))); +} -lldb::BasicType -SBType::GetBasicType() -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(false).GetBasicTypeEnumeration (); - return eBasicTypeInvalid; +SBType SBType::GetArrayElementType() { + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP( + new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayElementType()))); } -SBType -SBType::GetBasicType(lldb::BasicType basic_type) -{ - if (IsValid() && m_opaque_sp->IsValid()) - return SBType(m_opaque_sp->GetTypeSystem(false)->GetBasicTypeFromAST(basic_type)); +SBType SBType::GetArrayType(uint64_t size) { + if (!IsValid()) return SBType(); + return SBType(TypeImplSP( + new TypeImpl(m_opaque_sp->GetCompilerType(true).GetArrayType(size)))); } -uint32_t -SBType::GetNumberOfDirectBaseClasses () -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(true).GetNumDirectBaseClasses(); - return 0; +SBType SBType::GetVectorElementType() { + SBType type_sb; + if (IsValid()) { + CompilerType vector_element_type; + if (m_opaque_sp->GetCompilerType(true).IsVectorType(&vector_element_type, + nullptr)) + type_sb.SetSP(TypeImplSP(new TypeImpl(vector_element_type))); + } + return type_sb; } -uint32_t -SBType::GetNumberOfVirtualBaseClasses () -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(true).GetNumVirtualBaseClasses(); - return 0; +bool SBType::IsFunctionType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsFunctionType(); } -uint32_t -SBType::GetNumberOfFields () -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(true).GetNumFields(); - return 0; +bool SBType::IsPolymorphicClass() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsPolymorphicClass(); } -bool -SBType::GetDescription (SBStream &description, lldb::DescriptionLevel description_level) -{ - Stream &strm = description.ref(); +bool SBType::IsTypedefType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsTypedefType(); +} - if (m_opaque_sp) - { - m_opaque_sp->GetDescription (strm, description_level); +bool SBType::IsAnonymousType() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(true).IsAnonymousType(); +} + +lldb::SBType SBType::GetFunctionReturnType() { + if (IsValid()) { + CompilerType return_type( + m_opaque_sp->GetCompilerType(true).GetFunctionReturnType()); + if (return_type.IsValid()) + return SBType(return_type); + } + return lldb::SBType(); +} + +lldb::SBTypeList SBType::GetFunctionArgumentTypes() { + SBTypeList sb_type_list; + if (IsValid()) { + CompilerType func_type(m_opaque_sp->GetCompilerType(true)); + size_t count = func_type.GetNumberOfFunctionArguments(); + for (size_t i = 0; i < count; i++) { + sb_type_list.Append(SBType(func_type.GetFunctionArgumentAtIndex(i))); } - else - strm.PutCString ("No value"); - - return true; + } + return sb_type_list; } +uint32_t SBType::GetNumberOfMemberFunctions() { + if (IsValid()) { + return m_opaque_sp->GetCompilerType(true).GetNumMemberFunctions(); + } + return 0; +} - -SBTypeMember -SBType::GetDirectBaseClassAtIndex (uint32_t idx) -{ - SBTypeMember sb_type_member; - if (IsValid()) - { - uint32_t bit_offset = 0; - CompilerType base_class_type = m_opaque_sp->GetCompilerType (true).GetDirectBaseClassAtIndex(idx, &bit_offset); - if (base_class_type.IsValid()) - sb_type_member.reset (new TypeMemberImpl (TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); - } - return sb_type_member; - +lldb::SBTypeMemberFunction SBType::GetMemberFunctionAtIndex(uint32_t idx) { + SBTypeMemberFunction sb_func_type; + if (IsValid()) + sb_func_type.reset(new TypeMemberFunctionImpl( + m_opaque_sp->GetCompilerType(true).GetMemberFunctionAtIndex(idx))); + return sb_func_type; } -SBTypeMember -SBType::GetVirtualBaseClassAtIndex (uint32_t idx) -{ - SBTypeMember sb_type_member; - if (IsValid()) - { - uint32_t bit_offset = 0; - CompilerType base_class_type = m_opaque_sp->GetCompilerType (true).GetVirtualBaseClassAtIndex(idx, &bit_offset); - if (base_class_type.IsValid()) - sb_type_member.reset (new TypeMemberImpl (TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); - } - return sb_type_member; -} - -SBTypeEnumMemberList -SBType::GetEnumMembers () -{ - SBTypeEnumMemberList sb_enum_member_list; - if (IsValid()) - { - CompilerType this_type (m_opaque_sp->GetCompilerType (true)); - if (this_type.IsValid()) - { - this_type.ForEachEnumerator([&sb_enum_member_list] (const CompilerType &integer_type, const ConstString &name, const llvm::APSInt &value) -> bool { - SBTypeEnumMember enum_member (lldb::TypeEnumMemberImplSP (new TypeEnumMemberImpl(lldb::TypeImplSP(new TypeImpl(integer_type)), name, value))); - sb_enum_member_list.Append(enum_member); - return true; // Keep iterating - }); - } +lldb::SBType SBType::GetUnqualifiedType() { + if (!IsValid()) + return SBType(); + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetUnqualifiedType()))); +} + +lldb::SBType SBType::GetCanonicalType() { + if (IsValid()) + return SBType(TypeImplSP(new TypeImpl(m_opaque_sp->GetCanonicalType()))); + return SBType(); +} + +lldb::BasicType SBType::GetBasicType() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(false).GetBasicTypeEnumeration(); + return eBasicTypeInvalid; +} + +SBType SBType::GetBasicType(lldb::BasicType basic_type) { + if (IsValid() && m_opaque_sp->IsValid()) + return SBType( + m_opaque_sp->GetTypeSystem(false)->GetBasicTypeFromAST(basic_type)); + return SBType(); +} + +uint32_t SBType::GetNumberOfDirectBaseClasses() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumDirectBaseClasses(); + return 0; +} + +uint32_t SBType::GetNumberOfVirtualBaseClasses() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumVirtualBaseClasses(); + return 0; +} + +uint32_t SBType::GetNumberOfFields() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetNumFields(); + return 0; +} + +bool SBType::GetDescription(SBStream &description, + lldb::DescriptionLevel description_level) { + Stream &strm = description.ref(); + + if (m_opaque_sp) { + m_opaque_sp->GetDescription(strm, description_level); + } else + strm.PutCString("No value"); + + return true; +} + +SBTypeMember SBType::GetDirectBaseClassAtIndex(uint32_t idx) { + SBTypeMember sb_type_member; + if (IsValid()) { + uint32_t bit_offset = 0; + CompilerType base_class_type = + m_opaque_sp->GetCompilerType(true).GetDirectBaseClassAtIndex( + idx, &bit_offset); + if (base_class_type.IsValid()) + sb_type_member.reset(new TypeMemberImpl( + TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); + } + return sb_type_member; +} + +SBTypeMember SBType::GetVirtualBaseClassAtIndex(uint32_t idx) { + SBTypeMember sb_type_member; + if (IsValid()) { + uint32_t bit_offset = 0; + CompilerType base_class_type = + m_opaque_sp->GetCompilerType(true).GetVirtualBaseClassAtIndex( + idx, &bit_offset); + if (base_class_type.IsValid()) + sb_type_member.reset(new TypeMemberImpl( + TypeImplSP(new TypeImpl(base_class_type)), bit_offset)); + } + return sb_type_member; +} + +SBTypeEnumMemberList SBType::GetEnumMembers() { + SBTypeEnumMemberList sb_enum_member_list; + if (IsValid()) { + CompilerType this_type(m_opaque_sp->GetCompilerType(true)); + if (this_type.IsValid()) { + this_type.ForEachEnumerator([&sb_enum_member_list]( + const CompilerType &integer_type, + const ConstString &name, + const llvm::APSInt &value) -> bool { + SBTypeEnumMember enum_member( + lldb::TypeEnumMemberImplSP(new TypeEnumMemberImpl( + lldb::TypeImplSP(new TypeImpl(integer_type)), name, value))); + sb_enum_member_list.Append(enum_member); + return true; // Keep iterating + }); } - return sb_enum_member_list; -} - -SBTypeMember -SBType::GetFieldAtIndex (uint32_t idx) -{ - SBTypeMember sb_type_member; - if (IsValid()) - { - CompilerType this_type (m_opaque_sp->GetCompilerType (false)); - if (this_type.IsValid()) - { - uint64_t bit_offset = 0; - uint32_t bitfield_bit_size = 0; - bool is_bitfield = false; - std::string name_sstr; - CompilerType field_type (this_type.GetFieldAtIndex (idx, - name_sstr, - &bit_offset, - &bitfield_bit_size, - &is_bitfield)); - if (field_type.IsValid()) - { - ConstString name; - if (!name_sstr.empty()) - name.SetCString(name_sstr.c_str()); - sb_type_member.reset (new TypeMemberImpl (TypeImplSP (new TypeImpl(field_type)), - bit_offset, - name, - bitfield_bit_size, - is_bitfield)); - } - } + } + return sb_enum_member_list; +} + +SBTypeMember SBType::GetFieldAtIndex(uint32_t idx) { + SBTypeMember sb_type_member; + if (IsValid()) { + CompilerType this_type(m_opaque_sp->GetCompilerType(false)); + if (this_type.IsValid()) { + uint64_t bit_offset = 0; + uint32_t bitfield_bit_size = 0; + bool is_bitfield = false; + std::string name_sstr; + CompilerType field_type(this_type.GetFieldAtIndex( + idx, name_sstr, &bit_offset, &bitfield_bit_size, &is_bitfield)); + if (field_type.IsValid()) { + ConstString name; + if (!name_sstr.empty()) + name.SetCString(name_sstr.c_str()); + sb_type_member.reset( + new TypeMemberImpl(TypeImplSP(new TypeImpl(field_type)), bit_offset, + name, bitfield_bit_size, is_bitfield)); + } } - return sb_type_member; + } + return sb_type_member; } -bool -SBType::IsTypeComplete() -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetCompilerType(false).IsCompleteType(); -} - -uint32_t -SBType::GetTypeFlags () -{ - if (!IsValid()) - return 0; - return m_opaque_sp->GetCompilerType(true).GetTypeInfo(); +bool SBType::IsTypeComplete() { + if (!IsValid()) + return false; + return m_opaque_sp->GetCompilerType(false).IsCompleteType(); } -const char* -SBType::GetName() -{ - if (!IsValid()) - return ""; - return m_opaque_sp->GetName().GetCString(); +uint32_t SBType::GetTypeFlags() { + if (!IsValid()) + return 0; + return m_opaque_sp->GetCompilerType(true).GetTypeInfo(); } -const char * -SBType::GetDisplayTypeName () -{ - if (!IsValid()) - return ""; - return m_opaque_sp->GetDisplayTypeName().GetCString(); +const char *SBType::GetName() { + if (!IsValid()) + return ""; + return m_opaque_sp->GetName().GetCString(); } -lldb::TypeClass -SBType::GetTypeClass () -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(true).GetTypeClass(); - return lldb::eTypeClassInvalid; +const char *SBType::GetDisplayTypeName() { + if (!IsValid()) + return ""; + return m_opaque_sp->GetDisplayTypeName().GetCString(); } -uint32_t -SBType::GetNumberOfTemplateArguments () -{ - if (IsValid()) - return m_opaque_sp->GetCompilerType(false).GetNumTemplateArguments(); - return 0; +lldb::TypeClass SBType::GetTypeClass() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(true).GetTypeClass(); + return lldb::eTypeClassInvalid; } -lldb::SBType -SBType::GetTemplateArgumentType (uint32_t idx) -{ - if (IsValid()) - { - TemplateArgumentKind kind = eTemplateArgumentKindNull; - CompilerType template_arg_type = m_opaque_sp->GetCompilerType(false).GetTemplateArgument(idx, kind); - if (template_arg_type.IsValid()) - return SBType(template_arg_type); - } - return SBType(); +uint32_t SBType::GetNumberOfTemplateArguments() { + if (IsValid()) + return m_opaque_sp->GetCompilerType(false).GetNumTemplateArguments(); + return 0; } - -lldb::TemplateArgumentKind -SBType::GetTemplateArgumentKind (uint32_t idx) -{ +lldb::SBType SBType::GetTemplateArgumentType(uint32_t idx) { + if (IsValid()) { TemplateArgumentKind kind = eTemplateArgumentKindNull; - if (IsValid()) + CompilerType template_arg_type = m_opaque_sp->GetCompilerType(false).GetTemplateArgument(idx, kind); - return kind; + if (template_arg_type.IsValid()) + return SBType(template_arg_type); + } + return SBType(); } - -SBTypeList::SBTypeList() : - m_opaque_ap(new TypeListImpl()) -{ +lldb::TemplateArgumentKind SBType::GetTemplateArgumentKind(uint32_t idx) { + TemplateArgumentKind kind = eTemplateArgumentKindNull; + if (IsValid()) + m_opaque_sp->GetCompilerType(false).GetTemplateArgument(idx, kind); + return kind; } -SBTypeList::SBTypeList(const SBTypeList& rhs) : - m_opaque_ap(new TypeListImpl()) -{ - for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); i < rhs_size; i++) - Append(const_cast(rhs).GetTypeAtIndex(i)); -} +SBTypeList::SBTypeList() : m_opaque_ap(new TypeListImpl()) {} -bool -SBTypeList::IsValid () -{ - return (m_opaque_ap.get() != NULL); +SBTypeList::SBTypeList(const SBTypeList &rhs) + : m_opaque_ap(new TypeListImpl()) { + for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast(rhs).GetTypeAtIndex(i)); } -SBTypeList& -SBTypeList::operator = (const SBTypeList& rhs) -{ - if (this != &rhs) - { - m_opaque_ap.reset (new TypeListImpl()); - for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); i < rhs_size; i++) - Append(const_cast(rhs).GetTypeAtIndex(i)); - } - return *this; -} +bool SBTypeList::IsValid() { return (m_opaque_ap.get() != NULL); } -void -SBTypeList::Append (SBType type) -{ - if (type.IsValid()) - m_opaque_ap->Append (type.m_opaque_sp); +SBTypeList &SBTypeList::operator=(const SBTypeList &rhs) { + if (this != &rhs) { + m_opaque_ap.reset(new TypeListImpl()); + for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast(rhs).GetTypeAtIndex(i)); + } + return *this; } -SBType -SBTypeList::GetTypeAtIndex(uint32_t index) -{ - if (m_opaque_ap.get()) - return SBType(m_opaque_ap->GetTypeAtIndex(index)); - return SBType(); +void SBTypeList::Append(SBType type) { + if (type.IsValid()) + m_opaque_ap->Append(type.m_opaque_sp); } -uint32_t -SBTypeList::GetSize() -{ - return m_opaque_ap->GetSize(); +SBType SBTypeList::GetTypeAtIndex(uint32_t index) { + if (m_opaque_ap.get()) + return SBType(m_opaque_ap->GetTypeAtIndex(index)); + return SBType(); } -SBTypeList::~SBTypeList() -{ -} +uint32_t SBTypeList::GetSize() { return m_opaque_ap->GetSize(); } -SBTypeMember::SBTypeMember() : - m_opaque_ap() -{ -} +SBTypeList::~SBTypeList() {} -SBTypeMember::~SBTypeMember() -{ -} +SBTypeMember::SBTypeMember() : m_opaque_ap() {} -SBTypeMember::SBTypeMember (const SBTypeMember& rhs) : - m_opaque_ap() -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); - } -} +SBTypeMember::~SBTypeMember() {} -lldb::SBTypeMember& -SBTypeMember::operator = (const lldb::SBTypeMember& rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); - } - return *this; +SBTypeMember::SBTypeMember(const SBTypeMember &rhs) : m_opaque_ap() { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); + } } -bool -SBTypeMember::IsValid() const -{ - return m_opaque_ap.get(); +lldb::SBTypeMember &SBTypeMember::operator=(const lldb::SBTypeMember &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_ap.reset(new TypeMemberImpl(rhs.ref())); + } + return *this; } -const char * -SBTypeMember::GetName () -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetName().GetCString(); - return NULL; -} +bool SBTypeMember::IsValid() const { return m_opaque_ap.get(); } -SBType -SBTypeMember::GetType () -{ - SBType sb_type; - if (m_opaque_ap.get()) - { - sb_type.SetSP (m_opaque_ap->GetTypeImpl()); - } - return sb_type; +const char *SBTypeMember::GetName() { + if (m_opaque_ap.get()) + return m_opaque_ap->GetName().GetCString(); + return NULL; +} +SBType SBTypeMember::GetType() { + SBType sb_type; + if (m_opaque_ap.get()) { + sb_type.SetSP(m_opaque_ap->GetTypeImpl()); + } + return sb_type; } -uint64_t -SBTypeMember::GetOffsetInBytes() -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetBitOffset() / 8u; - return 0; +uint64_t SBTypeMember::GetOffsetInBytes() { + if (m_opaque_ap.get()) + return m_opaque_ap->GetBitOffset() / 8u; + return 0; } -uint64_t -SBTypeMember::GetOffsetInBits() -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetBitOffset(); - return 0; +uint64_t SBTypeMember::GetOffsetInBits() { + if (m_opaque_ap.get()) + return m_opaque_ap->GetBitOffset(); + return 0; } -bool -SBTypeMember::IsBitfield() -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetIsBitfield(); - return false; +bool SBTypeMember::IsBitfield() { + if (m_opaque_ap.get()) + return m_opaque_ap->GetIsBitfield(); + return false; } -uint32_t -SBTypeMember::GetBitfieldSizeInBits() -{ - if (m_opaque_ap.get()) - return m_opaque_ap->GetBitfieldBitSize(); - return 0; +uint32_t SBTypeMember::GetBitfieldSizeInBits() { + if (m_opaque_ap.get()) + return m_opaque_ap->GetBitfieldBitSize(); + return 0; } +bool SBTypeMember::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + Stream &strm = description.ref(); -bool -SBTypeMember::GetDescription (lldb::SBStream &description, lldb::DescriptionLevel description_level) -{ - Stream &strm = description.ref(); - - if (m_opaque_ap.get()) - { - const uint32_t bit_offset = m_opaque_ap->GetBitOffset(); - const uint32_t byte_offset = bit_offset / 8u; - const uint32_t byte_bit_offset = bit_offset % 8u; - const char *name = m_opaque_ap->GetName().GetCString(); - if (byte_bit_offset) - strm.Printf ("+%u + %u bits: (", byte_offset, byte_bit_offset); - else - strm.Printf ("+%u: (", byte_offset); - - TypeImplSP type_impl_sp (m_opaque_ap->GetTypeImpl()); - if (type_impl_sp) - type_impl_sp->GetDescription(strm, description_level); - - strm.Printf (") %s", name); - if (m_opaque_ap->GetIsBitfield()) - { - const uint32_t bitfield_bit_size = m_opaque_ap->GetBitfieldBitSize(); - strm.Printf (" : %u", bitfield_bit_size); - } - } + if (m_opaque_ap.get()) { + const uint32_t bit_offset = m_opaque_ap->GetBitOffset(); + const uint32_t byte_offset = bit_offset / 8u; + const uint32_t byte_bit_offset = bit_offset % 8u; + const char *name = m_opaque_ap->GetName().GetCString(); + if (byte_bit_offset) + strm.Printf("+%u + %u bits: (", byte_offset, byte_bit_offset); else - { - strm.PutCString ("No value"); - } - return true; -} + strm.Printf("+%u: (", byte_offset); + TypeImplSP type_impl_sp(m_opaque_ap->GetTypeImpl()); + if (type_impl_sp) + type_impl_sp->GetDescription(strm, description_level); -void -SBTypeMember::reset(TypeMemberImpl *type_member_impl) -{ - m_opaque_ap.reset(type_member_impl); + strm.Printf(") %s", name); + if (m_opaque_ap->GetIsBitfield()) { + const uint32_t bitfield_bit_size = m_opaque_ap->GetBitfieldBitSize(); + strm.Printf(" : %u", bitfield_bit_size); + } + } else { + strm.PutCString("No value"); + } + return true; } -TypeMemberImpl & -SBTypeMember::ref () -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new TypeMemberImpl()); - return *m_opaque_ap.get(); +void SBTypeMember::reset(TypeMemberImpl *type_member_impl) { + m_opaque_ap.reset(type_member_impl); } -const TypeMemberImpl & -SBTypeMember::ref () const -{ - return *m_opaque_ap.get(); +TypeMemberImpl &SBTypeMember::ref() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new TypeMemberImpl()); + return *m_opaque_ap.get(); } -SBTypeMemberFunction::SBTypeMemberFunction() : -m_opaque_sp() -{ -} +const TypeMemberImpl &SBTypeMember::ref() const { return *m_opaque_ap.get(); } -SBTypeMemberFunction::~SBTypeMemberFunction() -{ -} +SBTypeMemberFunction::SBTypeMemberFunction() : m_opaque_sp() {} -SBTypeMemberFunction::SBTypeMemberFunction (const SBTypeMemberFunction& rhs) : - m_opaque_sp(rhs.m_opaque_sp) -{ -} +SBTypeMemberFunction::~SBTypeMemberFunction() {} -lldb::SBTypeMemberFunction& -SBTypeMemberFunction::operator = (const lldb::SBTypeMemberFunction& rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; -} +SBTypeMemberFunction::SBTypeMemberFunction(const SBTypeMemberFunction &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -bool -SBTypeMemberFunction::IsValid() const -{ - return m_opaque_sp.get(); +lldb::SBTypeMemberFunction &SBTypeMemberFunction:: +operator=(const lldb::SBTypeMemberFunction &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } -const char * -SBTypeMemberFunction::GetName () -{ - if (m_opaque_sp) - return m_opaque_sp->GetName().GetCString(); - return NULL; +bool SBTypeMemberFunction::IsValid() const { return m_opaque_sp.get(); } + +const char *SBTypeMemberFunction::GetName() { + if (m_opaque_sp) + return m_opaque_sp->GetName().GetCString(); + return NULL; } -const char * -SBTypeMemberFunction::GetDemangledName () -{ - if (m_opaque_sp) - { - ConstString mangled_str = m_opaque_sp->GetMangledName(); - if (mangled_str) - { - Mangled mangled(mangled_str, true); - return mangled.GetDemangledName(mangled.GuessLanguage()).GetCString(); - } +const char *SBTypeMemberFunction::GetDemangledName() { + if (m_opaque_sp) { + ConstString mangled_str = m_opaque_sp->GetMangledName(); + if (mangled_str) { + Mangled mangled(mangled_str, true); + return mangled.GetDemangledName(mangled.GuessLanguage()).GetCString(); } - return NULL; + } + return NULL; } -const char * -SBTypeMemberFunction::GetMangledName() -{ - if (m_opaque_sp) - return m_opaque_sp->GetMangledName().GetCString(); - return NULL; +const char *SBTypeMemberFunction::GetMangledName() { + if (m_opaque_sp) + return m_opaque_sp->GetMangledName().GetCString(); + return NULL; } +SBType SBTypeMemberFunction::GetType() { + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetType()))); + } + return sb_type; +} -SBType -SBTypeMemberFunction::GetType () -{ - SBType sb_type; - if (m_opaque_sp) - { - sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetType()))); - } - return sb_type; +lldb::SBType SBTypeMemberFunction::GetReturnType() { + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetReturnType()))); + } + return sb_type; } -lldb::SBType -SBTypeMemberFunction::GetReturnType () -{ - SBType sb_type; - if (m_opaque_sp) - { - sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetReturnType()))); - } - return sb_type; +uint32_t SBTypeMemberFunction::GetNumberOfArguments() { + if (m_opaque_sp) + return m_opaque_sp->GetNumArguments(); + return 0; } -uint32_t -SBTypeMemberFunction::GetNumberOfArguments () -{ - if (m_opaque_sp) - return m_opaque_sp->GetNumArguments(); - return 0; +lldb::SBType SBTypeMemberFunction::GetArgumentTypeAtIndex(uint32_t i) { + SBType sb_type; + if (m_opaque_sp) { + sb_type.SetSP( + lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetArgumentAtIndex(i)))); + } + return sb_type; } -lldb::SBType -SBTypeMemberFunction::GetArgumentTypeAtIndex (uint32_t i) -{ - SBType sb_type; - if (m_opaque_sp) - { - sb_type.SetSP(lldb::TypeImplSP(new TypeImpl(m_opaque_sp->GetArgumentAtIndex(i)))); - } - return sb_type; -} - -lldb::MemberFunctionKind -SBTypeMemberFunction::GetKind () -{ - if (m_opaque_sp) - return m_opaque_sp->GetKind(); - return lldb::eMemberFunctionKindUnknown; - -} - -bool -SBTypeMemberFunction::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - Stream &strm = description.ref(); - - if (m_opaque_sp) - return m_opaque_sp->GetDescription(strm); - - return false; +lldb::MemberFunctionKind SBTypeMemberFunction::GetKind() { + if (m_opaque_sp) + return m_opaque_sp->GetKind(); + return lldb::eMemberFunctionKindUnknown; +} + +bool SBTypeMemberFunction::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + Stream &strm = description.ref(); + + if (m_opaque_sp) + return m_opaque_sp->GetDescription(strm); + + return false; } -void -SBTypeMemberFunction::reset(TypeMemberFunctionImpl *type_member_impl) -{ - m_opaque_sp.reset(type_member_impl); +void SBTypeMemberFunction::reset(TypeMemberFunctionImpl *type_member_impl) { + m_opaque_sp.reset(type_member_impl); } -TypeMemberFunctionImpl & -SBTypeMemberFunction::ref () -{ - if (!m_opaque_sp) - m_opaque_sp.reset (new TypeMemberFunctionImpl()); - return *m_opaque_sp.get(); +TypeMemberFunctionImpl &SBTypeMemberFunction::ref() { + if (!m_opaque_sp) + m_opaque_sp.reset(new TypeMemberFunctionImpl()); + return *m_opaque_sp.get(); } -const TypeMemberFunctionImpl & -SBTypeMemberFunction::ref () const -{ - return *m_opaque_sp.get(); +const TypeMemberFunctionImpl &SBTypeMemberFunction::ref() const { + return *m_opaque_sp.get(); } diff --git a/lldb/source/API/SBTypeCategory.cpp b/lldb/source/API/SBTypeCategory.cpp index 33dada8da39..9482e013eea 100644 --- a/lldb/source/API/SBTypeCategory.cpp +++ b/lldb/source/API/SBTypeCategory.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeCategory.cpp ----------------------------------------*- C++ -*-===// +//===-- SBTypeCategory.cpp ----------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -9,12 +10,12 @@ #include "lldb/API/SBTypeCategory.h" +#include "lldb/API/SBStream.h" #include "lldb/API/SBTypeFilter.h" #include "lldb/API/SBTypeFormat.h" +#include "lldb/API/SBTypeNameSpecifier.h" #include "lldb/API/SBTypeSummary.h" #include "lldb/API/SBTypeSynthetic.h" -#include "lldb/API/SBTypeNameSpecifier.h" -#include "lldb/API/SBStream.h" #include "lldb/Core/Debugger.h" #include "lldb/DataFormatters/DataVisualization.h" @@ -24,581 +25,537 @@ using namespace lldb; using namespace lldb_private; -typedef std::pair ImplType; +typedef std::pair ImplType; -SBTypeCategory::SBTypeCategory() : -m_opaque_sp() -{ -} +SBTypeCategory::SBTypeCategory() : m_opaque_sp() {} -SBTypeCategory::SBTypeCategory (const char* name) : -m_opaque_sp() -{ - DataVisualization::Categories::GetCategory(ConstString(name), m_opaque_sp); +SBTypeCategory::SBTypeCategory(const char *name) : m_opaque_sp() { + DataVisualization::Categories::GetCategory(ConstString(name), m_opaque_sp); } -SBTypeCategory::SBTypeCategory (const lldb::SBTypeCategory &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{ -} +SBTypeCategory::SBTypeCategory(const lldb::SBTypeCategory &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBTypeCategory::~SBTypeCategory () -{ -} +SBTypeCategory::~SBTypeCategory() {} -bool -SBTypeCategory::IsValid() const -{ - return (m_opaque_sp.get() != NULL); -} +bool SBTypeCategory::IsValid() const { return (m_opaque_sp.get() != NULL); } -bool -SBTypeCategory::GetEnabled () -{ - if (!IsValid()) - return false; - return m_opaque_sp->IsEnabled(); +bool SBTypeCategory::GetEnabled() { + if (!IsValid()) + return false; + return m_opaque_sp->IsEnabled(); } -void -SBTypeCategory::SetEnabled (bool enabled) -{ - if (!IsValid()) - return; - if (enabled) - DataVisualization::Categories::Enable(m_opaque_sp); - else - DataVisualization::Categories::Disable(m_opaque_sp); +void SBTypeCategory::SetEnabled(bool enabled) { + if (!IsValid()) + return; + if (enabled) + DataVisualization::Categories::Enable(m_opaque_sp); + else + DataVisualization::Categories::Disable(m_opaque_sp); } -const char* -SBTypeCategory::GetName() -{ - if (!IsValid()) - return NULL; - return m_opaque_sp->GetName(); +const char *SBTypeCategory::GetName() { + if (!IsValid()) + return NULL; + return m_opaque_sp->GetName(); } -lldb::LanguageType -SBTypeCategory::GetLanguageAtIndex (uint32_t idx) -{ - if (IsValid()) - return m_opaque_sp->GetLanguageAtIndex(idx); - return lldb::eLanguageTypeUnknown; +lldb::LanguageType SBTypeCategory::GetLanguageAtIndex(uint32_t idx) { + if (IsValid()) + return m_opaque_sp->GetLanguageAtIndex(idx); + return lldb::eLanguageTypeUnknown; } -uint32_t -SBTypeCategory::GetNumLanguages () -{ - if (IsValid()) - return m_opaque_sp->GetNumLanguages(); - return 0; +uint32_t SBTypeCategory::GetNumLanguages() { + if (IsValid()) + return m_opaque_sp->GetNumLanguages(); + return 0; } -void -SBTypeCategory::AddLanguage (lldb::LanguageType language) -{ - if (IsValid()) - m_opaque_sp->AddLanguage(language); +void SBTypeCategory::AddLanguage(lldb::LanguageType language) { + if (IsValid()) + m_opaque_sp->AddLanguage(language); } -uint32_t -SBTypeCategory::GetNumFormats () -{ - if (!IsValid()) - return 0; - - return m_opaque_sp->GetTypeFormatsContainer()->GetCount() + m_opaque_sp->GetRegexTypeFormatsContainer()->GetCount(); +uint32_t SBTypeCategory::GetNumFormats() { + if (!IsValid()) + return 0; + + return m_opaque_sp->GetTypeFormatsContainer()->GetCount() + + m_opaque_sp->GetRegexTypeFormatsContainer()->GetCount(); } -uint32_t -SBTypeCategory::GetNumSummaries () -{ - if (!IsValid()) - return 0; - return m_opaque_sp->GetTypeSummariesContainer()->GetCount() + m_opaque_sp->GetRegexTypeSummariesContainer()->GetCount(); +uint32_t SBTypeCategory::GetNumSummaries() { + if (!IsValid()) + return 0; + return m_opaque_sp->GetTypeSummariesContainer()->GetCount() + + m_opaque_sp->GetRegexTypeSummariesContainer()->GetCount(); } -uint32_t -SBTypeCategory::GetNumFilters () -{ - if (!IsValid()) - return 0; - return m_opaque_sp->GetTypeFiltersContainer()->GetCount() + m_opaque_sp->GetRegexTypeFiltersContainer()->GetCount(); +uint32_t SBTypeCategory::GetNumFilters() { + if (!IsValid()) + return 0; + return m_opaque_sp->GetTypeFiltersContainer()->GetCount() + + m_opaque_sp->GetRegexTypeFiltersContainer()->GetCount(); } #ifndef LLDB_DISABLE_PYTHON -uint32_t -SBTypeCategory::GetNumSynthetics () -{ - if (!IsValid()) - return 0; - return m_opaque_sp->GetTypeSyntheticsContainer()->GetCount() + m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetCount(); +uint32_t SBTypeCategory::GetNumSynthetics() { + if (!IsValid()) + return 0; + return m_opaque_sp->GetTypeSyntheticsContainer()->GetCount() + + m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetCount(); } #endif lldb::SBTypeNameSpecifier -SBTypeCategory::GetTypeNameSpecifierForFilterAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index)); +SBTypeCategory::GetTypeNameSpecifierForFilterAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index)); } lldb::SBTypeNameSpecifier -SBTypeCategory::GetTypeNameSpecifierForFormatAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForFormatAtIndex(index)); +SBTypeCategory::GetTypeNameSpecifierForFormatAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForFormatAtIndex(index)); } lldb::SBTypeNameSpecifier -SBTypeCategory::GetTypeNameSpecifierForSummaryAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index)); +SBTypeCategory::GetTypeNameSpecifierForSummaryAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index)); } #ifndef LLDB_DISABLE_PYTHON lldb::SBTypeNameSpecifier -SBTypeCategory::GetTypeNameSpecifierForSyntheticAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeNameSpecifier(); - return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index)); +SBTypeCategory::GetTypeNameSpecifierForSyntheticAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeNameSpecifier(); + return SBTypeNameSpecifier( + m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index)); } #endif -SBTypeFilter -SBTypeCategory::GetFilterForType (SBTypeNameSpecifier spec) -{ - if (!IsValid()) - return SBTypeFilter(); - - if (!spec.IsValid()) - return SBTypeFilter(); - - lldb::TypeFilterImplSP children_sp; - - if (spec.IsRegex()) - m_opaque_sp->GetRegexTypeFiltersContainer()->GetExact(ConstString(spec.GetName()), children_sp); - else - m_opaque_sp->GetTypeFiltersContainer()->GetExact(ConstString(spec.GetName()), children_sp); - - if (!children_sp) - return lldb::SBTypeFilter(); - - TypeFilterImplSP filter_sp = std::static_pointer_cast(children_sp); - - return lldb::SBTypeFilter(filter_sp); - -} -SBTypeFormat -SBTypeCategory::GetFormatForType (SBTypeNameSpecifier spec) -{ - if (!IsValid()) - return SBTypeFormat(); - - if (!spec.IsValid()) - return SBTypeFormat(); - - lldb::TypeFormatImplSP format_sp; - - if (spec.IsRegex()) - m_opaque_sp->GetRegexTypeFormatsContainer()->GetExact(ConstString(spec.GetName()), format_sp); - else - m_opaque_sp->GetTypeFormatsContainer()->GetExact(ConstString(spec.GetName()), format_sp); - - if (!format_sp) - return lldb::SBTypeFormat(); - - return lldb::SBTypeFormat(format_sp); +SBTypeFilter SBTypeCategory::GetFilterForType(SBTypeNameSpecifier spec) { + if (!IsValid()) + return SBTypeFilter(); + + if (!spec.IsValid()) + return SBTypeFilter(); + + lldb::TypeFilterImplSP children_sp; + + if (spec.IsRegex()) + m_opaque_sp->GetRegexTypeFiltersContainer()->GetExact( + ConstString(spec.GetName()), children_sp); + else + m_opaque_sp->GetTypeFiltersContainer()->GetExact( + ConstString(spec.GetName()), children_sp); + + if (!children_sp) + return lldb::SBTypeFilter(); + + TypeFilterImplSP filter_sp = + std::static_pointer_cast(children_sp); + + return lldb::SBTypeFilter(filter_sp); +} +SBTypeFormat SBTypeCategory::GetFormatForType(SBTypeNameSpecifier spec) { + if (!IsValid()) + return SBTypeFormat(); + + if (!spec.IsValid()) + return SBTypeFormat(); + + lldb::TypeFormatImplSP format_sp; + + if (spec.IsRegex()) + m_opaque_sp->GetRegexTypeFormatsContainer()->GetExact( + ConstString(spec.GetName()), format_sp); + else + m_opaque_sp->GetTypeFormatsContainer()->GetExact( + ConstString(spec.GetName()), format_sp); + + if (!format_sp) + return lldb::SBTypeFormat(); + + return lldb::SBTypeFormat(format_sp); } #ifndef LLDB_DISABLE_PYTHON -SBTypeSummary -SBTypeCategory::GetSummaryForType (SBTypeNameSpecifier spec) -{ - if (!IsValid()) - return SBTypeSummary(); - - if (!spec.IsValid()) - return SBTypeSummary(); - - lldb::TypeSummaryImplSP summary_sp; - - if (spec.IsRegex()) - m_opaque_sp->GetRegexTypeSummariesContainer()->GetExact(ConstString(spec.GetName()), summary_sp); - else - m_opaque_sp->GetTypeSummariesContainer()->GetExact(ConstString(spec.GetName()), summary_sp); - - if (!summary_sp) - return lldb::SBTypeSummary(); - - return lldb::SBTypeSummary(summary_sp); +SBTypeSummary SBTypeCategory::GetSummaryForType(SBTypeNameSpecifier spec) { + if (!IsValid()) + return SBTypeSummary(); + + if (!spec.IsValid()) + return SBTypeSummary(); + + lldb::TypeSummaryImplSP summary_sp; + + if (spec.IsRegex()) + m_opaque_sp->GetRegexTypeSummariesContainer()->GetExact( + ConstString(spec.GetName()), summary_sp); + else + m_opaque_sp->GetTypeSummariesContainer()->GetExact( + ConstString(spec.GetName()), summary_sp); + + if (!summary_sp) + return lldb::SBTypeSummary(); + + return lldb::SBTypeSummary(summary_sp); } #endif // LLDB_DISABLE_PYTHON #ifndef LLDB_DISABLE_PYTHON -SBTypeSynthetic -SBTypeCategory::GetSyntheticForType (SBTypeNameSpecifier spec) -{ - if (!IsValid()) - return SBTypeSynthetic(); - - if (!spec.IsValid()) - return SBTypeSynthetic(); - - lldb::SyntheticChildrenSP children_sp; - - if (spec.IsRegex()) - m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetExact(ConstString(spec.GetName()), children_sp); - else - m_opaque_sp->GetTypeSyntheticsContainer()->GetExact(ConstString(spec.GetName()), children_sp); - - if (!children_sp) - return lldb::SBTypeSynthetic(); - - ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast(children_sp); - - return lldb::SBTypeSynthetic(synth_sp); +SBTypeSynthetic SBTypeCategory::GetSyntheticForType(SBTypeNameSpecifier spec) { + if (!IsValid()) + return SBTypeSynthetic(); + + if (!spec.IsValid()) + return SBTypeSynthetic(); + + lldb::SyntheticChildrenSP children_sp; + + if (spec.IsRegex()) + m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetExact( + ConstString(spec.GetName()), children_sp); + else + m_opaque_sp->GetTypeSyntheticsContainer()->GetExact( + ConstString(spec.GetName()), children_sp); + + if (!children_sp) + return lldb::SBTypeSynthetic(); + + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast(children_sp); + + return lldb::SBTypeSynthetic(synth_sp); } #endif #ifndef LLDB_DISABLE_PYTHON -SBTypeFilter -SBTypeCategory::GetFilterAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeFilter(); - lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); - - if (!children_sp.get()) - return lldb::SBTypeFilter(); - - TypeFilterImplSP filter_sp = std::static_pointer_cast(children_sp); - - return lldb::SBTypeFilter(filter_sp); +SBTypeFilter SBTypeCategory::GetFilterAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeFilter(); + lldb::SyntheticChildrenSP children_sp = + m_opaque_sp->GetSyntheticAtIndex((index)); + + if (!children_sp.get()) + return lldb::SBTypeFilter(); + + TypeFilterImplSP filter_sp = + std::static_pointer_cast(children_sp); + + return lldb::SBTypeFilter(filter_sp); } #endif -SBTypeFormat -SBTypeCategory::GetFormatAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeFormat(); - return SBTypeFormat(m_opaque_sp->GetFormatAtIndex((index))); +SBTypeFormat SBTypeCategory::GetFormatAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeFormat(); + return SBTypeFormat(m_opaque_sp->GetFormatAtIndex((index))); } #ifndef LLDB_DISABLE_PYTHON -SBTypeSummary -SBTypeCategory::GetSummaryAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeSummary(); - return SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index))); +SBTypeSummary SBTypeCategory::GetSummaryAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeSummary(); + return SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index))); } #endif #ifndef LLDB_DISABLE_PYTHON -SBTypeSynthetic -SBTypeCategory::GetSyntheticAtIndex (uint32_t index) -{ - if (!IsValid()) - return SBTypeSynthetic(); - lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); - - if (!children_sp.get()) - return lldb::SBTypeSynthetic(); - - ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast(children_sp); - - return lldb::SBTypeSynthetic(synth_sp); +SBTypeSynthetic SBTypeCategory::GetSyntheticAtIndex(uint32_t index) { + if (!IsValid()) + return SBTypeSynthetic(); + lldb::SyntheticChildrenSP children_sp = + m_opaque_sp->GetSyntheticAtIndex((index)); + + if (!children_sp.get()) + return lldb::SBTypeSynthetic(); + + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast(children_sp); + + return lldb::SBTypeSynthetic(synth_sp); } #endif -bool -SBTypeCategory::AddTypeFormat (SBTypeNameSpecifier type_name, - SBTypeFormat format) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (!format.IsValid()) - return false; - - if (type_name.IsRegex()) - m_opaque_sp->GetRegexTypeFormatsContainer()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), format.GetSP()); - else - m_opaque_sp->GetTypeFormatsContainer()->Add(ConstString(type_name.GetName()), format.GetSP()); - - return true; -} - -bool -SBTypeCategory::DeleteTypeFormat (SBTypeNameSpecifier type_name) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (type_name.IsRegex()) - return m_opaque_sp->GetRegexTypeFormatsContainer()->Delete(ConstString(type_name.GetName())); - else - return m_opaque_sp->GetTypeFormatsContainer()->Delete(ConstString(type_name.GetName())); +bool SBTypeCategory::AddTypeFormat(SBTypeNameSpecifier type_name, + SBTypeFormat format) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!format.IsValid()) + return false; + + if (type_name.IsRegex()) + m_opaque_sp->GetRegexTypeFormatsContainer()->Add( + lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), + format.GetSP()); + else + m_opaque_sp->GetTypeFormatsContainer()->Add( + ConstString(type_name.GetName()), format.GetSP()); + + return true; +} + +bool SBTypeCategory::DeleteTypeFormat(SBTypeNameSpecifier type_name) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (type_name.IsRegex()) + return m_opaque_sp->GetRegexTypeFormatsContainer()->Delete( + ConstString(type_name.GetName())); + else + return m_opaque_sp->GetTypeFormatsContainer()->Delete( + ConstString(type_name.GetName())); } #ifndef LLDB_DISABLE_PYTHON -bool -SBTypeCategory::AddTypeSummary (SBTypeNameSpecifier type_name, - SBTypeSummary summary) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (!summary.IsValid()) - return false; - - // FIXME: we need to iterate over all the Debugger objects and have each of them contain a copy of the function - // since we currently have formatters live in a global space, while Python code lives in a specific Debugger-related environment - // this should eventually be fixed by deciding a final location in the LLDB object space for formatters - if (summary.IsFunctionCode()) - { - const void *name_token = (const void*)ConstString(type_name.GetName()).GetCString(); - const char* script = summary.GetData(); - StringList input; input.SplitIntoLines(script, strlen(script)); - uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); - bool need_set = true; - for (uint32_t j = 0; - j < num_debuggers; - j++) - { - DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); - if (debugger_sp) - { - ScriptInterpreter* interpreter_ptr = debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); - if (interpreter_ptr) - { - std::string output; - if (interpreter_ptr->GenerateTypeScriptFunction(input, output, name_token) && !output.empty()) - { - if (need_set) - { - need_set = false; - summary.SetFunctionName(output.c_str()); - } - } - } +bool SBTypeCategory::AddTypeSummary(SBTypeNameSpecifier type_name, + SBTypeSummary summary) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!summary.IsValid()) + return false; + + // FIXME: we need to iterate over all the Debugger objects and have each of + // them contain a copy of the function + // since we currently have formatters live in a global space, while Python + // code lives in a specific Debugger-related environment + // this should eventually be fixed by deciding a final location in the LLDB + // object space for formatters + if (summary.IsFunctionCode()) { + const void *name_token = + (const void *)ConstString(type_name.GetName()).GetCString(); + const char *script = summary.GetData(); + StringList input; + input.SplitIntoLines(script, strlen(script)); + uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); + bool need_set = true; + for (uint32_t j = 0; j < num_debuggers; j++) { + DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); + if (debugger_sp) { + ScriptInterpreter *interpreter_ptr = + debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); + if (interpreter_ptr) { + std::string output; + if (interpreter_ptr->GenerateTypeScriptFunction(input, output, + name_token) && + !output.empty()) { + if (need_set) { + need_set = false; + summary.SetFunctionName(output.c_str()); } + } } + } } - - if (type_name.IsRegex()) - m_opaque_sp->GetRegexTypeSummariesContainer()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), summary.GetSP()); - else - m_opaque_sp->GetTypeSummariesContainer()->Add(ConstString(type_name.GetName()), summary.GetSP()); - - return true; + } + + if (type_name.IsRegex()) + m_opaque_sp->GetRegexTypeSummariesContainer()->Add( + lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), + summary.GetSP()); + else + m_opaque_sp->GetTypeSummariesContainer()->Add( + ConstString(type_name.GetName()), summary.GetSP()); + + return true; } #endif -bool -SBTypeCategory::DeleteTypeSummary (SBTypeNameSpecifier type_name) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (type_name.IsRegex()) - return m_opaque_sp->GetRegexTypeSummariesContainer()->Delete(ConstString(type_name.GetName())); - else - return m_opaque_sp->GetTypeSummariesContainer()->Delete(ConstString(type_name.GetName())); -} - -bool -SBTypeCategory::AddTypeFilter (SBTypeNameSpecifier type_name, - SBTypeFilter filter) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (!filter.IsValid()) - return false; - - if (type_name.IsRegex()) - m_opaque_sp->GetRegexTypeFiltersContainer()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), filter.GetSP()); - else - m_opaque_sp->GetTypeFiltersContainer()->Add(ConstString(type_name.GetName()), filter.GetSP()); - - return true; -} - -bool -SBTypeCategory::DeleteTypeFilter (SBTypeNameSpecifier type_name) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (type_name.IsRegex()) - return m_opaque_sp->GetRegexTypeFiltersContainer()->Delete(ConstString(type_name.GetName())); - else - return m_opaque_sp->GetTypeFiltersContainer()->Delete(ConstString(type_name.GetName())); +bool SBTypeCategory::DeleteTypeSummary(SBTypeNameSpecifier type_name) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (type_name.IsRegex()) + return m_opaque_sp->GetRegexTypeSummariesContainer()->Delete( + ConstString(type_name.GetName())); + else + return m_opaque_sp->GetTypeSummariesContainer()->Delete( + ConstString(type_name.GetName())); +} + +bool SBTypeCategory::AddTypeFilter(SBTypeNameSpecifier type_name, + SBTypeFilter filter) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!filter.IsValid()) + return false; + + if (type_name.IsRegex()) + m_opaque_sp->GetRegexTypeFiltersContainer()->Add( + lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), + filter.GetSP()); + else + m_opaque_sp->GetTypeFiltersContainer()->Add( + ConstString(type_name.GetName()), filter.GetSP()); + + return true; +} + +bool SBTypeCategory::DeleteTypeFilter(SBTypeNameSpecifier type_name) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (type_name.IsRegex()) + return m_opaque_sp->GetRegexTypeFiltersContainer()->Delete( + ConstString(type_name.GetName())); + else + return m_opaque_sp->GetTypeFiltersContainer()->Delete( + ConstString(type_name.GetName())); } #ifndef LLDB_DISABLE_PYTHON -bool -SBTypeCategory::AddTypeSynthetic (SBTypeNameSpecifier type_name, - SBTypeSynthetic synth) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (!synth.IsValid()) - return false; - - // FIXME: we need to iterate over all the Debugger objects and have each of them contain a copy of the function - // since we currently have formatters live in a global space, while Python code lives in a specific Debugger-related environment - // this should eventually be fixed by deciding a final location in the LLDB object space for formatters - if (synth.IsClassCode()) - { - const void *name_token = (const void*)ConstString(type_name.GetName()).GetCString(); - const char* script = synth.GetData(); - StringList input; input.SplitIntoLines(script, strlen(script)); - uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); - bool need_set = true; - for (uint32_t j = 0; - j < num_debuggers; - j++) - { - DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); - if (debugger_sp) - { - ScriptInterpreter* interpreter_ptr = debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); - if (interpreter_ptr) - { - std::string output; - if (interpreter_ptr->GenerateTypeSynthClass(input, output, name_token) && !output.empty()) - { - if (need_set) - { - need_set = false; - synth.SetClassName(output.c_str()); - } - } - } +bool SBTypeCategory::AddTypeSynthetic(SBTypeNameSpecifier type_name, + SBTypeSynthetic synth) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (!synth.IsValid()) + return false; + + // FIXME: we need to iterate over all the Debugger objects and have each of + // them contain a copy of the function + // since we currently have formatters live in a global space, while Python + // code lives in a specific Debugger-related environment + // this should eventually be fixed by deciding a final location in the LLDB + // object space for formatters + if (synth.IsClassCode()) { + const void *name_token = + (const void *)ConstString(type_name.GetName()).GetCString(); + const char *script = synth.GetData(); + StringList input; + input.SplitIntoLines(script, strlen(script)); + uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); + bool need_set = true; + for (uint32_t j = 0; j < num_debuggers; j++) { + DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); + if (debugger_sp) { + ScriptInterpreter *interpreter_ptr = + debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); + if (interpreter_ptr) { + std::string output; + if (interpreter_ptr->GenerateTypeSynthClass(input, output, + name_token) && + !output.empty()) { + if (need_set) { + need_set = false; + synth.SetClassName(output.c_str()); } + } } + } } - - if (type_name.IsRegex()) - m_opaque_sp->GetRegexTypeSyntheticsContainer()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), synth.GetSP()); - else - m_opaque_sp->GetTypeSyntheticsContainer()->Add(ConstString(type_name.GetName()), synth.GetSP()); - - return true; -} - -bool -SBTypeCategory::DeleteTypeSynthetic (SBTypeNameSpecifier type_name) -{ - if (!IsValid()) - return false; - - if (!type_name.IsValid()) - return false; - - if (type_name.IsRegex()) - return m_opaque_sp->GetRegexTypeSyntheticsContainer()->Delete(ConstString(type_name.GetName())); - else - return m_opaque_sp->GetTypeSyntheticsContainer()->Delete(ConstString(type_name.GetName())); + } + + if (type_name.IsRegex()) + m_opaque_sp->GetRegexTypeSyntheticsContainer()->Add( + lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), + synth.GetSP()); + else + m_opaque_sp->GetTypeSyntheticsContainer()->Add( + ConstString(type_name.GetName()), synth.GetSP()); + + return true; } -#endif // LLDB_DISABLE_PYTHON -bool -SBTypeCategory::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (!IsValid()) - return false; - description.Printf("Category name: %s\n",GetName()); - return true; -} - -lldb::SBTypeCategory & -SBTypeCategory::operator = (const lldb::SBTypeCategory &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +bool SBTypeCategory::DeleteTypeSynthetic(SBTypeNameSpecifier type_name) { + if (!IsValid()) + return false; + + if (!type_name.IsValid()) + return false; + + if (type_name.IsRegex()) + return m_opaque_sp->GetRegexTypeSyntheticsContainer()->Delete( + ConstString(type_name.GetName())); + else + return m_opaque_sp->GetTypeSyntheticsContainer()->Delete( + ConstString(type_name.GetName())); } +#endif // LLDB_DISABLE_PYTHON -bool -SBTypeCategory::operator == (lldb::SBTypeCategory &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - return m_opaque_sp.get() == rhs.m_opaque_sp.get(); - +bool SBTypeCategory::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + if (!IsValid()) + return false; + description.Printf("Category name: %s\n", GetName()); + return true; } -bool -SBTypeCategory::operator != (lldb::SBTypeCategory &rhs) -{ - if (IsValid() == false) - return rhs.IsValid(); - - return m_opaque_sp.get() != rhs.m_opaque_sp.get(); +lldb::SBTypeCategory &SBTypeCategory:: +operator=(const lldb::SBTypeCategory &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -lldb::TypeCategoryImplSP -SBTypeCategory::GetSP () -{ - if (!IsValid()) - return lldb::TypeCategoryImplSP(); - return m_opaque_sp; +bool SBTypeCategory::operator==(lldb::SBTypeCategory &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + return m_opaque_sp.get() == rhs.m_opaque_sp.get(); } -void -SBTypeCategory::SetSP (const lldb::TypeCategoryImplSP &typecategory_impl_sp) -{ - m_opaque_sp = typecategory_impl_sp; +bool SBTypeCategory::operator!=(lldb::SBTypeCategory &rhs) { + if (IsValid() == false) + return rhs.IsValid(); + + return m_opaque_sp.get() != rhs.m_opaque_sp.get(); } -SBTypeCategory::SBTypeCategory (const lldb::TypeCategoryImplSP &typecategory_impl_sp) : -m_opaque_sp(typecategory_impl_sp) -{ +lldb::TypeCategoryImplSP SBTypeCategory::GetSP() { + if (!IsValid()) + return lldb::TypeCategoryImplSP(); + return m_opaque_sp; } -bool -SBTypeCategory::IsDefaultCategory() -{ - if (!IsValid()) - return false; - - return (strcmp(m_opaque_sp->GetName(),"default") == 0); +void SBTypeCategory::SetSP( + const lldb::TypeCategoryImplSP &typecategory_impl_sp) { + m_opaque_sp = typecategory_impl_sp; } +SBTypeCategory::SBTypeCategory( + const lldb::TypeCategoryImplSP &typecategory_impl_sp) + : m_opaque_sp(typecategory_impl_sp) {} + +bool SBTypeCategory::IsDefaultCategory() { + if (!IsValid()) + return false; + + return (strcmp(m_opaque_sp->GetName(), "default") == 0); +} diff --git a/lldb/source/API/SBTypeEnumMember.cpp b/lldb/source/API/SBTypeEnumMember.cpp index c23f7ea8c6c..787a46b1760 100644 --- a/lldb/source/API/SBTypeEnumMember.cpp +++ b/lldb/source/API/SBTypeEnumMember.cpp @@ -7,10 +7,10 @@ // //===----------------------------------------------------------------------===// -#include "lldb/API/SBDefines.h" #include "lldb/API/SBType.h" -#include "lldb/API/SBTypeEnumMember.h" +#include "lldb/API/SBDefines.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBTypeEnumMember.h" #include "lldb/Core/Stream.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Symbol/Type.h" @@ -18,174 +18,124 @@ using namespace lldb; using namespace lldb_private; -SBTypeEnumMember::SBTypeEnumMember() : - m_opaque_sp() -{ -} +SBTypeEnumMember::SBTypeEnumMember() : m_opaque_sp() {} -SBTypeEnumMember::~SBTypeEnumMember() -{ -} -SBTypeEnumMember::SBTypeEnumMember (const lldb::TypeEnumMemberImplSP &enum_member_sp) : - m_opaque_sp(enum_member_sp) -{ -} +SBTypeEnumMember::~SBTypeEnumMember() {} +SBTypeEnumMember::SBTypeEnumMember( + const lldb::TypeEnumMemberImplSP &enum_member_sp) + : m_opaque_sp(enum_member_sp) {} -SBTypeEnumMember::SBTypeEnumMember (const SBTypeEnumMember& rhs) : - m_opaque_sp() -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); - } +SBTypeEnumMember::SBTypeEnumMember(const SBTypeEnumMember &rhs) + : m_opaque_sp() { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); + } } -SBTypeEnumMember& -SBTypeEnumMember::operator = (const SBTypeEnumMember& rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); - } - return *this; +SBTypeEnumMember &SBTypeEnumMember::operator=(const SBTypeEnumMember &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_sp.reset(new TypeEnumMemberImpl(rhs.ref())); + } + return *this; } -bool -SBTypeEnumMember::IsValid() const -{ - return m_opaque_sp.get(); -} +bool SBTypeEnumMember::IsValid() const { return m_opaque_sp.get(); } -const char * -SBTypeEnumMember::GetName () -{ - if (m_opaque_sp.get()) - return m_opaque_sp->GetName().GetCString(); - return NULL; +const char *SBTypeEnumMember::GetName() { + if (m_opaque_sp.get()) + return m_opaque_sp->GetName().GetCString(); + return NULL; } -int64_t -SBTypeEnumMember::GetValueAsSigned() -{ - if (m_opaque_sp.get()) - return m_opaque_sp->GetValueAsSigned(); - return 0; +int64_t SBTypeEnumMember::GetValueAsSigned() { + if (m_opaque_sp.get()) + return m_opaque_sp->GetValueAsSigned(); + return 0; } -uint64_t -SBTypeEnumMember::GetValueAsUnsigned() -{ - if (m_opaque_sp.get()) - return m_opaque_sp->GetValueAsUnsigned(); - return 0; +uint64_t SBTypeEnumMember::GetValueAsUnsigned() { + if (m_opaque_sp.get()) + return m_opaque_sp->GetValueAsUnsigned(); + return 0; } -SBType -SBTypeEnumMember::GetType () -{ - SBType sb_type; - if (m_opaque_sp.get()) - { - sb_type.SetSP(m_opaque_sp->GetIntegerType()); - } - return sb_type; - +SBType SBTypeEnumMember::GetType() { + SBType sb_type; + if (m_opaque_sp.get()) { + sb_type.SetSP(m_opaque_sp->GetIntegerType()); + } + return sb_type; } -void -SBTypeEnumMember::reset(TypeEnumMemberImpl *type_member_impl) -{ - m_opaque_sp.reset(type_member_impl); +void SBTypeEnumMember::reset(TypeEnumMemberImpl *type_member_impl) { + m_opaque_sp.reset(type_member_impl); } -TypeEnumMemberImpl & -SBTypeEnumMember::ref () -{ - if (m_opaque_sp.get() == NULL) - m_opaque_sp.reset (new TypeEnumMemberImpl()); - return *m_opaque_sp.get(); +TypeEnumMemberImpl &SBTypeEnumMember::ref() { + if (m_opaque_sp.get() == NULL) + m_opaque_sp.reset(new TypeEnumMemberImpl()); + return *m_opaque_sp.get(); } -const TypeEnumMemberImpl & -SBTypeEnumMember::ref () const -{ - return *m_opaque_sp.get(); +const TypeEnumMemberImpl &SBTypeEnumMember::ref() const { + return *m_opaque_sp.get(); } +SBTypeEnumMemberList::SBTypeEnumMemberList() + : m_opaque_ap(new TypeEnumMemberListImpl()) {} -SBTypeEnumMemberList::SBTypeEnumMemberList() : - m_opaque_ap(new TypeEnumMemberListImpl()) -{ +SBTypeEnumMemberList::SBTypeEnumMemberList(const SBTypeEnumMemberList &rhs) + : m_opaque_ap(new TypeEnumMemberListImpl()) { + for (uint32_t i = 0, + rhs_size = const_cast(rhs).GetSize(); + i < rhs_size; i++) + Append(const_cast(rhs).GetTypeEnumMemberAtIndex(i)); } -SBTypeEnumMemberList::SBTypeEnumMemberList(const SBTypeEnumMemberList& rhs) : - m_opaque_ap(new TypeEnumMemberListImpl()) -{ - for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); i < rhs_size; i++) - Append(const_cast(rhs).GetTypeEnumMemberAtIndex(i)); -} - -bool -SBTypeEnumMemberList::IsValid () -{ - return (m_opaque_ap.get() != NULL); -} +bool SBTypeEnumMemberList::IsValid() { return (m_opaque_ap.get() != NULL); } -SBTypeEnumMemberList& -SBTypeEnumMemberList::operator = (const SBTypeEnumMemberList& rhs) -{ - if (this != &rhs) - { - m_opaque_ap.reset (new TypeEnumMemberListImpl()); - for (uint32_t i = 0, rhs_size = const_cast(rhs).GetSize(); i < rhs_size; i++) - Append(const_cast(rhs).GetTypeEnumMemberAtIndex(i)); - } - return *this; +SBTypeEnumMemberList &SBTypeEnumMemberList:: +operator=(const SBTypeEnumMemberList &rhs) { + if (this != &rhs) { + m_opaque_ap.reset(new TypeEnumMemberListImpl()); + for (uint32_t i = 0, + rhs_size = const_cast(rhs).GetSize(); + i < rhs_size; i++) + Append( + const_cast(rhs).GetTypeEnumMemberAtIndex(i)); + } + return *this; } -void -SBTypeEnumMemberList::Append (SBTypeEnumMember enum_member) -{ - if (enum_member.IsValid()) - m_opaque_ap->Append (enum_member.m_opaque_sp); +void SBTypeEnumMemberList::Append(SBTypeEnumMember enum_member) { + if (enum_member.IsValid()) + m_opaque_ap->Append(enum_member.m_opaque_sp); } SBTypeEnumMember -SBTypeEnumMemberList::GetTypeEnumMemberAtIndex(uint32_t index) -{ - if (m_opaque_ap.get()) - return SBTypeEnumMember(m_opaque_ap->GetTypeEnumMemberAtIndex(index)); - return SBTypeEnumMember(); +SBTypeEnumMemberList::GetTypeEnumMemberAtIndex(uint32_t index) { + if (m_opaque_ap.get()) + return SBTypeEnumMember(m_opaque_ap->GetTypeEnumMemberAtIndex(index)); + return SBTypeEnumMember(); } -uint32_t -SBTypeEnumMemberList::GetSize() -{ - return m_opaque_ap->GetSize(); -} +uint32_t SBTypeEnumMemberList::GetSize() { return m_opaque_ap->GetSize(); } -SBTypeEnumMemberList::~SBTypeEnumMemberList() -{ -} +SBTypeEnumMemberList::~SBTypeEnumMemberList() {} -bool -SBTypeEnumMember::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - Stream &strm = description.ref(); - - if (m_opaque_sp.get()) - { - if( m_opaque_sp->GetIntegerType()->GetDescription(strm, description_level) ) - { - strm.Printf(" %s", m_opaque_sp->GetName().GetCString()); - } - } - else - { - strm.PutCString ("No value"); +bool SBTypeEnumMember::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + Stream &strm = description.ref(); + + if (m_opaque_sp.get()) { + if (m_opaque_sp->GetIntegerType()->GetDescription(strm, + description_level)) { + strm.Printf(" %s", m_opaque_sp->GetName().GetCString()); } - return true; + } else { + strm.PutCString("No value"); + } + return true; } diff --git a/lldb/source/API/SBTypeFilter.cpp b/lldb/source/API/SBTypeFilter.cpp index 8af3e1ff864..8fa32221138 100644 --- a/lldb/source/API/SBTypeFilter.cpp +++ b/lldb/source/API/SBTypeFilter.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeFilter.cpp ------------------------------------------*- C++ -*-===// +//===-- SBTypeFilter.cpp ------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -16,182 +17,129 @@ using namespace lldb; using namespace lldb_private; -SBTypeFilter::SBTypeFilter() : -m_opaque_sp() -{ -} +SBTypeFilter::SBTypeFilter() : m_opaque_sp() {} -SBTypeFilter::SBTypeFilter (uint32_t options) -: m_opaque_sp(TypeFilterImplSP(new TypeFilterImpl(options))) -{ -} +SBTypeFilter::SBTypeFilter(uint32_t options) + : m_opaque_sp(TypeFilterImplSP(new TypeFilterImpl(options))) {} -SBTypeFilter::SBTypeFilter (const lldb::SBTypeFilter &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{ -} +SBTypeFilter::SBTypeFilter(const lldb::SBTypeFilter &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBTypeFilter::~SBTypeFilter () -{ -} +SBTypeFilter::~SBTypeFilter() {} -bool -SBTypeFilter::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} +bool SBTypeFilter::IsValid() const { return m_opaque_sp.get() != NULL; } -uint32_t -SBTypeFilter::GetOptions() -{ - if (IsValid()) - return m_opaque_sp->GetOptions(); - return 0; +uint32_t SBTypeFilter::GetOptions() { + if (IsValid()) + return m_opaque_sp->GetOptions(); + return 0; } -void -SBTypeFilter::SetOptions (uint32_t value) -{ - if (CopyOnWrite_Impl()) - m_opaque_sp->SetOptions(value); +void SBTypeFilter::SetOptions(uint32_t value) { + if (CopyOnWrite_Impl()) + m_opaque_sp->SetOptions(value); } -bool -SBTypeFilter::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (!IsValid()) - return false; - else { - description.Printf("%s\n", - m_opaque_sp->GetDescription().c_str()); - return true; - } +bool SBTypeFilter::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + if (!IsValid()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } } -void -SBTypeFilter::Clear() -{ - if (CopyOnWrite_Impl()) - m_opaque_sp->Clear(); +void SBTypeFilter::Clear() { + if (CopyOnWrite_Impl()) + m_opaque_sp->Clear(); } -uint32_t -SBTypeFilter::GetNumberOfExpressionPaths() -{ - if (IsValid()) - return m_opaque_sp->GetCount(); - return 0; +uint32_t SBTypeFilter::GetNumberOfExpressionPaths() { + if (IsValid()) + return m_opaque_sp->GetCount(); + return 0; } -const char* -SBTypeFilter::GetExpressionPathAtIndex (uint32_t i) -{ - if (IsValid()) - { - const char* item = m_opaque_sp->GetExpressionPathAtIndex(i); - if (item && *item == '.') - item++; - return item; - } - return NULL; +const char *SBTypeFilter::GetExpressionPathAtIndex(uint32_t i) { + if (IsValid()) { + const char *item = m_opaque_sp->GetExpressionPathAtIndex(i); + if (item && *item == '.') + item++; + return item; + } + return NULL; } -bool -SBTypeFilter::ReplaceExpressionPathAtIndex (uint32_t i, const char* item) -{ - if (CopyOnWrite_Impl()) - return m_opaque_sp->SetExpressionPathAtIndex(i, item); - else - return false; +bool SBTypeFilter::ReplaceExpressionPathAtIndex(uint32_t i, const char *item) { + if (CopyOnWrite_Impl()) + return m_opaque_sp->SetExpressionPathAtIndex(i, item); + else + return false; } -void -SBTypeFilter::AppendExpressionPath (const char* item) -{ - if (CopyOnWrite_Impl()) - m_opaque_sp->AddExpressionPath(item); +void SBTypeFilter::AppendExpressionPath(const char *item) { + if (CopyOnWrite_Impl()) + m_opaque_sp->AddExpressionPath(item); } -lldb::SBTypeFilter & -SBTypeFilter::operator = (const lldb::SBTypeFilter &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +lldb::SBTypeFilter &SBTypeFilter::operator=(const lldb::SBTypeFilter &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -bool -SBTypeFilter::operator == (lldb::SBTypeFilter &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - return m_opaque_sp == rhs.m_opaque_sp; -} +bool SBTypeFilter::operator==(lldb::SBTypeFilter &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); -bool -SBTypeFilter::IsEqualTo (lldb::SBTypeFilter &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - if (GetNumberOfExpressionPaths() != rhs.GetNumberOfExpressionPaths()) - return false; - - for (uint32_t j = 0; - j < GetNumberOfExpressionPaths(); - j++) - if ( strcmp(GetExpressionPathAtIndex(j),rhs.GetExpressionPathAtIndex(j)) != 0) - return false; - - return GetOptions() == rhs.GetOptions(); + return m_opaque_sp == rhs.m_opaque_sp; } -bool -SBTypeFilter::operator != (lldb::SBTypeFilter &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - return m_opaque_sp != rhs.m_opaque_sp; -} +bool SBTypeFilter::IsEqualTo(lldb::SBTypeFilter &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + if (GetNumberOfExpressionPaths() != rhs.GetNumberOfExpressionPaths()) + return false; -lldb::TypeFilterImplSP -SBTypeFilter::GetSP () -{ - return m_opaque_sp; + for (uint32_t j = 0; j < GetNumberOfExpressionPaths(); j++) + if (strcmp(GetExpressionPathAtIndex(j), rhs.GetExpressionPathAtIndex(j)) != + 0) + return false; + + return GetOptions() == rhs.GetOptions(); } -void -SBTypeFilter::SetSP (const lldb::TypeFilterImplSP &typefilter_impl_sp) -{ - m_opaque_sp = typefilter_impl_sp; +bool SBTypeFilter::operator!=(lldb::SBTypeFilter &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + return m_opaque_sp != rhs.m_opaque_sp; } -SBTypeFilter::SBTypeFilter (const lldb::TypeFilterImplSP &typefilter_impl_sp) : -m_opaque_sp(typefilter_impl_sp) -{ +lldb::TypeFilterImplSP SBTypeFilter::GetSP() { return m_opaque_sp; } + +void SBTypeFilter::SetSP(const lldb::TypeFilterImplSP &typefilter_impl_sp) { + m_opaque_sp = typefilter_impl_sp; } -bool -SBTypeFilter::CopyOnWrite_Impl() -{ - if (!IsValid()) - return false; - if (m_opaque_sp.unique()) - return true; - - TypeFilterImplSP new_sp(new TypeFilterImpl(GetOptions())); - - for (uint32_t j = 0; - j < GetNumberOfExpressionPaths(); - j++) - new_sp->AddExpressionPath(GetExpressionPathAtIndex(j)); - - SetSP(new_sp); - +SBTypeFilter::SBTypeFilter(const lldb::TypeFilterImplSP &typefilter_impl_sp) + : m_opaque_sp(typefilter_impl_sp) {} + +bool SBTypeFilter::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + if (m_opaque_sp.unique()) return true; + + TypeFilterImplSP new_sp(new TypeFilterImpl(GetOptions())); + + for (uint32_t j = 0; j < GetNumberOfExpressionPaths(); j++) + new_sp->AddExpressionPath(GetExpressionPathAtIndex(j)); + + SetSP(new_sp); + + return true; } diff --git a/lldb/source/API/SBTypeFormat.cpp b/lldb/source/API/SBTypeFormat.cpp index 9548fe904cd..6fe7625831d 100644 --- a/lldb/source/API/SBTypeFormat.cpp +++ b/lldb/source/API/SBTypeFormat.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeFormat.cpp ------------------------------------------*- C++ -*-===// +//===-- SBTypeFormat.cpp ------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -16,176 +17,132 @@ using namespace lldb; using namespace lldb_private; -SBTypeFormat::SBTypeFormat() : -m_opaque_sp() -{ -} +SBTypeFormat::SBTypeFormat() : m_opaque_sp() {} -SBTypeFormat::SBTypeFormat (lldb::Format format, - uint32_t options) -: m_opaque_sp(TypeFormatImplSP(new TypeFormatImpl_Format(format,options))) -{ -} +SBTypeFormat::SBTypeFormat(lldb::Format format, uint32_t options) + : m_opaque_sp( + TypeFormatImplSP(new TypeFormatImpl_Format(format, options))) {} -SBTypeFormat::SBTypeFormat (const char* type, - uint32_t options) -: m_opaque_sp(TypeFormatImplSP(new TypeFormatImpl_EnumType(ConstString(type ? type : ""),options))) -{ -} +SBTypeFormat::SBTypeFormat(const char *type, uint32_t options) + : m_opaque_sp(TypeFormatImplSP(new TypeFormatImpl_EnumType( + ConstString(type ? type : ""), options))) {} -SBTypeFormat::SBTypeFormat (const lldb::SBTypeFormat &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{ -} +SBTypeFormat::SBTypeFormat(const lldb::SBTypeFormat &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBTypeFormat::~SBTypeFormat () -{ -} +SBTypeFormat::~SBTypeFormat() {} -bool -SBTypeFormat::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} +bool SBTypeFormat::IsValid() const { return m_opaque_sp.get() != NULL; } -lldb::Format -SBTypeFormat::GetFormat () -{ - if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) - return ((TypeFormatImpl_Format*)m_opaque_sp.get())->GetFormat(); - return lldb::eFormatInvalid; +lldb::Format SBTypeFormat::GetFormat() { + if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) + return ((TypeFormatImpl_Format *)m_opaque_sp.get())->GetFormat(); + return lldb::eFormatInvalid; } -const char* -SBTypeFormat::GetTypeName () -{ - if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum) - return ((TypeFormatImpl_EnumType*)m_opaque_sp.get())->GetTypeName().AsCString(""); - return ""; +const char *SBTypeFormat::GetTypeName() { + if (IsValid() && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum) + return ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) + ->GetTypeName() + .AsCString(""); + return ""; } -uint32_t -SBTypeFormat::GetOptions() -{ - if (IsValid()) - return m_opaque_sp->GetOptions(); - return 0; +uint32_t SBTypeFormat::GetOptions() { + if (IsValid()) + return m_opaque_sp->GetOptions(); + return 0; } -void -SBTypeFormat::SetFormat (lldb::Format fmt) -{ - if (CopyOnWrite_Impl(Type::eTypeFormat)) - ((TypeFormatImpl_Format*)m_opaque_sp.get())->SetFormat(fmt); +void SBTypeFormat::SetFormat(lldb::Format fmt) { + if (CopyOnWrite_Impl(Type::eTypeFormat)) + ((TypeFormatImpl_Format *)m_opaque_sp.get())->SetFormat(fmt); } -void -SBTypeFormat::SetTypeName (const char* type) -{ - if (CopyOnWrite_Impl(Type::eTypeEnum)) - ((TypeFormatImpl_EnumType*)m_opaque_sp.get())->SetTypeName(ConstString(type ? type : "")); +void SBTypeFormat::SetTypeName(const char *type) { + if (CopyOnWrite_Impl(Type::eTypeEnum)) + ((TypeFormatImpl_EnumType *)m_opaque_sp.get()) + ->SetTypeName(ConstString(type ? type : "")); } -void -SBTypeFormat::SetOptions (uint32_t value) -{ - if (CopyOnWrite_Impl(Type::eTypeKeepSame)) - m_opaque_sp->SetOptions(value); +void SBTypeFormat::SetOptions(uint32_t value) { + if (CopyOnWrite_Impl(Type::eTypeKeepSame)) + m_opaque_sp->SetOptions(value); } -bool -SBTypeFormat::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (!IsValid()) - return false; - else { - description.Printf("%s\n", - m_opaque_sp->GetDescription().c_str()); - return true; - } +bool SBTypeFormat::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + if (!IsValid()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } } -lldb::SBTypeFormat & -SBTypeFormat::operator = (const lldb::SBTypeFormat &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +lldb::SBTypeFormat &SBTypeFormat::operator=(const lldb::SBTypeFormat &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -bool -SBTypeFormat::operator == (lldb::SBTypeFormat &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp == rhs.m_opaque_sp; +bool SBTypeFormat::operator==(lldb::SBTypeFormat &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; } -bool -SBTypeFormat::IsEqualTo (lldb::SBTypeFormat &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - if (GetFormat() == rhs.GetFormat()) - return GetOptions() == rhs.GetOptions(); - else - return false; -} +bool SBTypeFormat::IsEqualTo(lldb::SBTypeFormat &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); -bool -SBTypeFormat::operator != (lldb::SBTypeFormat &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp != rhs.m_opaque_sp; + if (GetFormat() == rhs.GetFormat()) + return GetOptions() == rhs.GetOptions(); + else + return false; } -lldb::TypeFormatImplSP -SBTypeFormat::GetSP () -{ - return m_opaque_sp; +bool SBTypeFormat::operator!=(lldb::SBTypeFormat &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; } -void -SBTypeFormat::SetSP (const lldb::TypeFormatImplSP &typeformat_impl_sp) -{ - m_opaque_sp = typeformat_impl_sp; -} +lldb::TypeFormatImplSP SBTypeFormat::GetSP() { return m_opaque_sp; } -SBTypeFormat::SBTypeFormat (const lldb::TypeFormatImplSP &typeformat_impl_sp) : - m_opaque_sp(typeformat_impl_sp) -{ +void SBTypeFormat::SetSP(const lldb::TypeFormatImplSP &typeformat_impl_sp) { + m_opaque_sp = typeformat_impl_sp; } -bool -SBTypeFormat::CopyOnWrite_Impl(Type type) -{ - if (!IsValid()) - return false; - - if (m_opaque_sp.unique() && - ((type == Type::eTypeKeepSame) || - (type == Type::eTypeFormat && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) || - (type == Type::eTypeEnum && m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum)) - ) - return true; - - if (type == Type::eTypeKeepSame) - { - if (m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) - type = Type::eTypeFormat; - else - type = Type::eTypeEnum; - } - - if (type == Type::eTypeFormat) - SetSP(TypeFormatImplSP(new TypeFormatImpl_Format(GetFormat(),GetOptions()))); - else - SetSP(TypeFormatImplSP(new TypeFormatImpl_EnumType(ConstString(GetTypeName()),GetOptions()))); - +SBTypeFormat::SBTypeFormat(const lldb::TypeFormatImplSP &typeformat_impl_sp) + : m_opaque_sp(typeformat_impl_sp) {} + +bool SBTypeFormat::CopyOnWrite_Impl(Type type) { + if (!IsValid()) + return false; + + if (m_opaque_sp.unique() && + ((type == Type::eTypeKeepSame) || + (type == Type::eTypeFormat && + m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) || + (type == Type::eTypeEnum && + m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeEnum))) return true; + + if (type == Type::eTypeKeepSame) { + if (m_opaque_sp->GetType() == TypeFormatImpl::Type::eTypeFormat) + type = Type::eTypeFormat; + else + type = Type::eTypeEnum; + } + + if (type == Type::eTypeFormat) + SetSP( + TypeFormatImplSP(new TypeFormatImpl_Format(GetFormat(), GetOptions()))); + else + SetSP(TypeFormatImplSP( + new TypeFormatImpl_EnumType(ConstString(GetTypeName()), GetOptions()))); + + return true; } diff --git a/lldb/source/API/SBTypeNameSpecifier.cpp b/lldb/source/API/SBTypeNameSpecifier.cpp index 6f6801099b7..2f9deafb68c 100644 --- a/lldb/source/API/SBTypeNameSpecifier.cpp +++ b/lldb/source/API/SBTypeNameSpecifier.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeNameSpecifier.cpp ------------------------------------*- C++ -*-===// +//===-- SBTypeNameSpecifier.cpp ------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -17,132 +18,100 @@ using namespace lldb; using namespace lldb_private; -SBTypeNameSpecifier::SBTypeNameSpecifier() : -m_opaque_sp() -{ -} +SBTypeNameSpecifier::SBTypeNameSpecifier() : m_opaque_sp() {} -SBTypeNameSpecifier::SBTypeNameSpecifier (const char* name, - bool is_regex) : -m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) -{ - if (name == NULL || (*name) == 0) - m_opaque_sp.reset(); +SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex) + : m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) { + if (name == NULL || (*name) == 0) + m_opaque_sp.reset(); } -SBTypeNameSpecifier::SBTypeNameSpecifier (SBType type) : -m_opaque_sp() -{ - if (type.IsValid()) - m_opaque_sp = TypeNameSpecifierImplSP(new TypeNameSpecifierImpl(type.m_opaque_sp->GetCompilerType(true))); +SBTypeNameSpecifier::SBTypeNameSpecifier(SBType type) : m_opaque_sp() { + if (type.IsValid()) + m_opaque_sp = TypeNameSpecifierImplSP( + new TypeNameSpecifierImpl(type.m_opaque_sp->GetCompilerType(true))); } -SBTypeNameSpecifier::SBTypeNameSpecifier (const lldb::SBTypeNameSpecifier &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{} +SBTypeNameSpecifier::SBTypeNameSpecifier(const lldb::SBTypeNameSpecifier &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -SBTypeNameSpecifier::~SBTypeNameSpecifier () -{ -} +SBTypeNameSpecifier::~SBTypeNameSpecifier() {} -bool -SBTypeNameSpecifier::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} +bool SBTypeNameSpecifier::IsValid() const { return m_opaque_sp.get() != NULL; } + +const char *SBTypeNameSpecifier::GetName() { + if (!IsValid()) + return NULL; -const char* -SBTypeNameSpecifier::GetName () -{ - if (!IsValid()) - return NULL; - - return m_opaque_sp->GetName(); + return m_opaque_sp->GetName(); } -SBType -SBTypeNameSpecifier::GetType () -{ - if (!IsValid()) - return SBType(); - lldb_private::CompilerType c_type = m_opaque_sp->GetCompilerType(); - if (c_type.IsValid()) - return SBType(c_type); +SBType SBTypeNameSpecifier::GetType() { + if (!IsValid()) return SBType(); + lldb_private::CompilerType c_type = m_opaque_sp->GetCompilerType(); + if (c_type.IsValid()) + return SBType(c_type); + return SBType(); } -bool -SBTypeNameSpecifier::IsRegex () -{ - if (!IsValid()) - return false; +bool SBTypeNameSpecifier::IsRegex() { + if (!IsValid()) + return false; - return m_opaque_sp->IsRegex(); + return m_opaque_sp->IsRegex(); } -bool -SBTypeNameSpecifier::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (!IsValid()) - return false; - description.Printf("SBTypeNameSpecifier(%s,%s)", GetName(), IsRegex() ? "regex" : "plain"); - return true; +bool SBTypeNameSpecifier::GetDescription( + lldb::SBStream &description, lldb::DescriptionLevel description_level) { + if (!IsValid()) + return false; + description.Printf("SBTypeNameSpecifier(%s,%s)", GetName(), + IsRegex() ? "regex" : "plain"); + return true; } -lldb::SBTypeNameSpecifier & -SBTypeNameSpecifier::operator = (const lldb::SBTypeNameSpecifier &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; +lldb::SBTypeNameSpecifier &SBTypeNameSpecifier:: +operator=(const lldb::SBTypeNameSpecifier &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -bool -SBTypeNameSpecifier::operator == (lldb::SBTypeNameSpecifier &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp == rhs.m_opaque_sp; +bool SBTypeNameSpecifier::operator==(lldb::SBTypeNameSpecifier &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; } -bool -SBTypeNameSpecifier::IsEqualTo (lldb::SBTypeNameSpecifier &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - if (IsRegex() != rhs.IsRegex()) - return false; - if (GetName() == NULL || rhs.GetName() == NULL) - return false; - - return (strcmp(GetName(), rhs.GetName()) == 0); -} +bool SBTypeNameSpecifier::IsEqualTo(lldb::SBTypeNameSpecifier &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + if (IsRegex() != rhs.IsRegex()) + return false; + if (GetName() == NULL || rhs.GetName() == NULL) + return false; -bool -SBTypeNameSpecifier::operator != (lldb::SBTypeNameSpecifier &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp != rhs.m_opaque_sp; + return (strcmp(GetName(), rhs.GetName()) == 0); } -lldb::TypeNameSpecifierImplSP -SBTypeNameSpecifier::GetSP () -{ - return m_opaque_sp; +bool SBTypeNameSpecifier::operator!=(lldb::SBTypeNameSpecifier &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; } -void -SBTypeNameSpecifier::SetSP (const lldb::TypeNameSpecifierImplSP &type_namespec_sp) -{ - m_opaque_sp = type_namespec_sp; +lldb::TypeNameSpecifierImplSP SBTypeNameSpecifier::GetSP() { + return m_opaque_sp; } -SBTypeNameSpecifier::SBTypeNameSpecifier (const lldb::TypeNameSpecifierImplSP &type_namespec_sp) : -m_opaque_sp(type_namespec_sp) -{ +void SBTypeNameSpecifier::SetSP( + const lldb::TypeNameSpecifierImplSP &type_namespec_sp) { + m_opaque_sp = type_namespec_sp; } + +SBTypeNameSpecifier::SBTypeNameSpecifier( + const lldb::TypeNameSpecifierImplSP &type_namespec_sp) + : m_opaque_sp(type_namespec_sp) {} diff --git a/lldb/source/API/SBTypeSummary.cpp b/lldb/source/API/SBTypeSummary.cpp index 2985b765954..cd4edd17f67 100644 --- a/lldb/source/API/SBTypeSummary.cpp +++ b/lldb/source/API/SBTypeSummary.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeSummary.cpp -----------------------------------------*- C++ -*-===// +//===-- SBTypeSummary.cpp -----------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -17,441 +18,361 @@ using namespace lldb; using namespace lldb_private; -SBTypeSummaryOptions::SBTypeSummaryOptions() -{ +SBTypeSummaryOptions::SBTypeSummaryOptions() { + m_opaque_ap.reset(new TypeSummaryOptions()); +} + +SBTypeSummaryOptions::SBTypeSummaryOptions( + const lldb::SBTypeSummaryOptions &rhs) { + if (rhs.m_opaque_ap) + m_opaque_ap.reset(new TypeSummaryOptions(*rhs.m_opaque_ap.get())); + else m_opaque_ap.reset(new TypeSummaryOptions()); } -SBTypeSummaryOptions::SBTypeSummaryOptions (const lldb::SBTypeSummaryOptions &rhs) -{ - if (rhs.m_opaque_ap) - m_opaque_ap.reset(new TypeSummaryOptions(*rhs.m_opaque_ap.get())); - else - m_opaque_ap.reset(new TypeSummaryOptions()); +SBTypeSummaryOptions::~SBTypeSummaryOptions() {} + +bool SBTypeSummaryOptions::IsValid() { return m_opaque_ap.get(); } + +lldb::LanguageType SBTypeSummaryOptions::GetLanguage() { + if (IsValid()) + return m_opaque_ap->GetLanguage(); + return lldb::eLanguageTypeUnknown; } -SBTypeSummaryOptions::~SBTypeSummaryOptions () -{ +lldb::TypeSummaryCapping SBTypeSummaryOptions::GetCapping() { + if (IsValid()) + return m_opaque_ap->GetCapping(); + return eTypeSummaryCapped; } -bool -SBTypeSummaryOptions::IsValid() -{ - return m_opaque_ap.get(); +void SBTypeSummaryOptions::SetLanguage(lldb::LanguageType l) { + if (IsValid()) + m_opaque_ap->SetLanguage(l); } -lldb::LanguageType -SBTypeSummaryOptions::GetLanguage () -{ - if (IsValid()) - return m_opaque_ap->GetLanguage(); - return lldb::eLanguageTypeUnknown; +void SBTypeSummaryOptions::SetCapping(lldb::TypeSummaryCapping c) { + if (IsValid()) + m_opaque_ap->SetCapping(c); } -lldb::TypeSummaryCapping -SBTypeSummaryOptions::GetCapping () -{ - if (IsValid()) - return m_opaque_ap->GetCapping(); - return eTypeSummaryCapped; +lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::operator->() { + return m_opaque_ap.get(); } -void -SBTypeSummaryOptions::SetLanguage (lldb::LanguageType l) -{ - if (IsValid()) - m_opaque_ap->SetLanguage(l); +const lldb_private::TypeSummaryOptions *SBTypeSummaryOptions:: +operator->() const { + return m_opaque_ap.get(); } -void -SBTypeSummaryOptions::SetCapping (lldb::TypeSummaryCapping c) -{ - if (IsValid()) - m_opaque_ap->SetCapping(c); +lldb_private::TypeSummaryOptions *SBTypeSummaryOptions::get() { + return m_opaque_ap.get(); } -lldb_private::TypeSummaryOptions * -SBTypeSummaryOptions::operator->() -{ - return m_opaque_ap.get(); +lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() { + return *m_opaque_ap.get(); } -const lldb_private::TypeSummaryOptions * -SBTypeSummaryOptions::operator->() const -{ - return m_opaque_ap.get(); +const lldb_private::TypeSummaryOptions &SBTypeSummaryOptions::ref() const { + return *m_opaque_ap.get(); } -lldb_private::TypeSummaryOptions * -SBTypeSummaryOptions::get () -{ - return m_opaque_ap.get(); +SBTypeSummaryOptions::SBTypeSummaryOptions( + const lldb_private::TypeSummaryOptions *lldb_object_ptr) { + SetOptions(lldb_object_ptr); } -lldb_private::TypeSummaryOptions & -SBTypeSummaryOptions::ref() -{ - return *m_opaque_ap.get(); +void SBTypeSummaryOptions::SetOptions( + const lldb_private::TypeSummaryOptions *lldb_object_ptr) { + if (lldb_object_ptr) + m_opaque_ap.reset(new TypeSummaryOptions(*lldb_object_ptr)); + else + m_opaque_ap.reset(new TypeSummaryOptions()); } -const lldb_private::TypeSummaryOptions & -SBTypeSummaryOptions::ref() const -{ - return *m_opaque_ap.get(); +SBTypeSummary::SBTypeSummary() : m_opaque_sp() {} + +SBTypeSummary SBTypeSummary::CreateWithSummaryString(const char *data, + uint32_t options) { + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new StringSummaryFormat(options, data))); } -SBTypeSummaryOptions::SBTypeSummaryOptions (const lldb_private::TypeSummaryOptions *lldb_object_ptr) -{ - SetOptions(lldb_object_ptr); +SBTypeSummary SBTypeSummary::CreateWithFunctionName(const char *data, + uint32_t options) { + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new ScriptSummaryFormat(options, data))); } -void -SBTypeSummaryOptions::SetOptions (const lldb_private::TypeSummaryOptions *lldb_object_ptr) -{ - if (lldb_object_ptr) - m_opaque_ap.reset(new TypeSummaryOptions(*lldb_object_ptr)); - else - m_opaque_ap.reset(new TypeSummaryOptions()); -} - -SBTypeSummary::SBTypeSummary() : -m_opaque_sp() -{ -} - -SBTypeSummary -SBTypeSummary::CreateWithSummaryString (const char* data, uint32_t options) -{ - if (!data || data[0] == 0) - return SBTypeSummary(); - - return SBTypeSummary(TypeSummaryImplSP(new StringSummaryFormat(options, data))); -} - -SBTypeSummary -SBTypeSummary::CreateWithFunctionName (const char* data, uint32_t options) -{ - if (!data || data[0] == 0) - return SBTypeSummary(); - - return SBTypeSummary(TypeSummaryImplSP(new ScriptSummaryFormat(options, data))); -} - -SBTypeSummary -SBTypeSummary::CreateWithScriptCode (const char* data, uint32_t options) -{ - if (!data || data[0] == 0) - return SBTypeSummary(); - - return SBTypeSummary(TypeSummaryImplSP(new ScriptSummaryFormat(options, "", data))); -} - -SBTypeSummary -SBTypeSummary::CreateWithCallback (FormatCallback cb, uint32_t options, const char* description) -{ - SBTypeSummary retval; - if (cb) - { - retval.SetSP(TypeSummaryImplSP(new CXXFunctionSummaryFormat(options, - [cb] (ValueObject& valobj, Stream& stm, const TypeSummaryOptions& opt) -> bool { - SBStream stream; - SBValue sb_value(valobj.GetSP()); - SBTypeSummaryOptions options(&opt); - if (!cb(sb_value, options, stream)) - return false; - stm.Write(stream.GetData(), stream.GetSize()); - return true; - }, - description ? description : "callback summary formatter"))); - } - - return retval; -} - -SBTypeSummary::SBTypeSummary (const lldb::SBTypeSummary &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{ -} - -SBTypeSummary::~SBTypeSummary () -{ -} - -bool -SBTypeSummary::IsValid() const -{ - return m_opaque_sp.get() != NULL; -} - -bool -SBTypeSummary::IsFunctionCode() -{ - if (!IsValid()) - return false; - if (ScriptSummaryFormat* script_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - const char* ftext = script_summary_ptr->GetPythonScript(); - return (ftext && *ftext != 0); - } +SBTypeSummary SBTypeSummary::CreateWithScriptCode(const char *data, + uint32_t options) { + if (!data || data[0] == 0) + return SBTypeSummary(); + + return SBTypeSummary( + TypeSummaryImplSP(new ScriptSummaryFormat(options, "", data))); +} + +SBTypeSummary SBTypeSummary::CreateWithCallback(FormatCallback cb, + uint32_t options, + const char *description) { + SBTypeSummary retval; + if (cb) { + retval.SetSP(TypeSummaryImplSP(new CXXFunctionSummaryFormat( + options, + [cb](ValueObject &valobj, Stream &stm, + const TypeSummaryOptions &opt) -> bool { + SBStream stream; + SBValue sb_value(valobj.GetSP()); + SBTypeSummaryOptions options(&opt); + if (!cb(sb_value, options, stream)) + return false; + stm.Write(stream.GetData(), stream.GetSize()); + return true; + }, + description ? description : "callback summary formatter"))); + } + + return retval; +} + +SBTypeSummary::SBTypeSummary(const lldb::SBTypeSummary &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} + +SBTypeSummary::~SBTypeSummary() {} + +bool SBTypeSummary::IsValid() const { return m_opaque_sp.get() != NULL; } + +bool SBTypeSummary::IsFunctionCode() { + if (!IsValid()) return false; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + const char *ftext = script_summary_ptr->GetPythonScript(); + return (ftext && *ftext != 0); + } + return false; } -bool -SBTypeSummary::IsFunctionName() -{ - if (!IsValid()) - return false; - if (ScriptSummaryFormat* script_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - const char* ftext = script_summary_ptr->GetPythonScript(); - return (!ftext || *ftext == 0); - } +bool SBTypeSummary::IsFunctionName() { + if (!IsValid()) return false; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + const char *ftext = script_summary_ptr->GetPythonScript(); + return (!ftext || *ftext == 0); + } + return false; } -bool -SBTypeSummary::IsSummaryString() -{ - if (!IsValid()) - return false; - - return m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eSummaryString; -} - -const char* -SBTypeSummary::GetData () -{ - if (!IsValid()) - return NULL; - if (ScriptSummaryFormat* script_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - const char* fname = script_summary_ptr->GetFunctionName(); - const char* ftext = script_summary_ptr->GetPythonScript(); - if (ftext && *ftext) - return ftext; - return fname; - } - else if (StringSummaryFormat* string_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - return string_summary_ptr->GetSummaryString(); - return nullptr; -} - -uint32_t -SBTypeSummary::GetOptions () -{ - if (!IsValid()) - return lldb::eTypeOptionNone; - return m_opaque_sp->GetOptions(); -} - -void -SBTypeSummary::SetOptions (uint32_t value) -{ - if (!CopyOnWrite_Impl()) - return; - m_opaque_sp->SetOptions(value); -} - -void -SBTypeSummary::SetSummaryString (const char* data) -{ - if (!IsValid()) - return; - if (!llvm::isa(m_opaque_sp.get())) - ChangeSummaryType(false); - if (StringSummaryFormat* string_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - string_summary_ptr->SetSummaryString(data); -} - -void -SBTypeSummary::SetFunctionName (const char* data) -{ - if (!IsValid()) - return; - if (!llvm::isa(m_opaque_sp.get())) - ChangeSummaryType(true); - if (ScriptSummaryFormat* script_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - script_summary_ptr->SetFunctionName(data); -} - -void -SBTypeSummary::SetFunctionCode (const char* data) -{ - if (!IsValid()) - return; - if (!llvm::isa(m_opaque_sp.get())) - ChangeSummaryType(true); - if (ScriptSummaryFormat* script_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - script_summary_ptr->SetPythonScript(data); -} - -bool -SBTypeSummary::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (!CopyOnWrite_Impl()) - return false; - else { - description.Printf("%s\n", - m_opaque_sp->GetDescription().c_str()); - return true; - } -} - -bool -SBTypeSummary::DoesPrintValue (lldb::SBValue value) -{ - if (!IsValid()) - return false; - lldb::ValueObjectSP value_sp = value.GetSP(); - return m_opaque_sp->DoesPrintValue(value_sp.get()); -} - -lldb::SBTypeSummary & -SBTypeSummary::operator = (const lldb::SBTypeSummary &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; -} - -bool -SBTypeSummary::operator == (lldb::SBTypeSummary &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp == rhs.m_opaque_sp; -} - -bool -SBTypeSummary::IsEqualTo (lldb::SBTypeSummary &rhs) -{ - if (IsValid()) - { - // valid and invalid are different - if (!rhs.IsValid()) - return false; - } +bool SBTypeSummary::IsSummaryString() { + if (!IsValid()) + return false; + + return m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eSummaryString; +} + +const char *SBTypeSummary::GetData() { + if (!IsValid()) + return NULL; + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + const char *fname = script_summary_ptr->GetFunctionName(); + const char *ftext = script_summary_ptr->GetPythonScript(); + if (ftext && *ftext) + return ftext; + return fname; + } else if (StringSummaryFormat *string_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) + return string_summary_ptr->GetSummaryString(); + return nullptr; +} + +uint32_t SBTypeSummary::GetOptions() { + if (!IsValid()) + return lldb::eTypeOptionNone; + return m_opaque_sp->GetOptions(); +} + +void SBTypeSummary::SetOptions(uint32_t value) { + if (!CopyOnWrite_Impl()) + return; + m_opaque_sp->SetOptions(value); +} + +void SBTypeSummary::SetSummaryString(const char *data) { + if (!IsValid()) + return; + if (!llvm::isa(m_opaque_sp.get())) + ChangeSummaryType(false); + if (StringSummaryFormat *string_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) + string_summary_ptr->SetSummaryString(data); +} + +void SBTypeSummary::SetFunctionName(const char *data) { + if (!IsValid()) + return; + if (!llvm::isa(m_opaque_sp.get())) + ChangeSummaryType(true); + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) + script_summary_ptr->SetFunctionName(data); +} + +void SBTypeSummary::SetFunctionCode(const char *data) { + if (!IsValid()) + return; + if (!llvm::isa(m_opaque_sp.get())) + ChangeSummaryType(true); + if (ScriptSummaryFormat *script_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) + script_summary_ptr->SetPythonScript(data); +} + +bool SBTypeSummary::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + if (!CopyOnWrite_Impl()) + return false; + else { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } +} + +bool SBTypeSummary::DoesPrintValue(lldb::SBValue value) { + if (!IsValid()) + return false; + lldb::ValueObjectSP value_sp = value.GetSP(); + return m_opaque_sp->DoesPrintValue(value_sp.get()); +} + +lldb::SBTypeSummary &SBTypeSummary::operator=(const lldb::SBTypeSummary &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; +} + +bool SBTypeSummary::operator==(lldb::SBTypeSummary &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; +} + +bool SBTypeSummary::IsEqualTo(lldb::SBTypeSummary &rhs) { + if (IsValid()) { + // valid and invalid are different + if (!rhs.IsValid()) + return false; + } else { + // invalid and valid are different + if (rhs.IsValid()) + return false; else - { - // invalid and valid are different - if (rhs.IsValid()) - return false; - else - // both invalid are the same - return true; - } - - if (m_opaque_sp->GetKind() != rhs.m_opaque_sp->GetKind()) - return false; - - switch (m_opaque_sp->GetKind()) - { - case TypeSummaryImpl::Kind::eCallback: - return llvm::dyn_cast(m_opaque_sp.get()) == llvm::dyn_cast(rhs.m_opaque_sp.get()); - case TypeSummaryImpl::Kind::eScript: - if (IsFunctionCode() != rhs.IsFunctionCode()) - return false; - if (IsFunctionName() != rhs.IsFunctionName()) - return false; - return GetOptions() == rhs.GetOptions(); - case TypeSummaryImpl::Kind::eSummaryString: - if (IsSummaryString() != rhs.IsSummaryString()) - return false; - return GetOptions() == rhs.GetOptions(); - case TypeSummaryImpl::Kind::eInternal: - return (m_opaque_sp.get() == rhs.m_opaque_sp.get()); - } - + // both invalid are the same + return true; + } + + if (m_opaque_sp->GetKind() != rhs.m_opaque_sp->GetKind()) return false; + + switch (m_opaque_sp->GetKind()) { + case TypeSummaryImpl::Kind::eCallback: + return llvm::dyn_cast(m_opaque_sp.get()) == + llvm::dyn_cast(rhs.m_opaque_sp.get()); + case TypeSummaryImpl::Kind::eScript: + if (IsFunctionCode() != rhs.IsFunctionCode()) + return false; + if (IsFunctionName() != rhs.IsFunctionName()) + return false; + return GetOptions() == rhs.GetOptions(); + case TypeSummaryImpl::Kind::eSummaryString: + if (IsSummaryString() != rhs.IsSummaryString()) + return false; + return GetOptions() == rhs.GetOptions(); + case TypeSummaryImpl::Kind::eInternal: + return (m_opaque_sp.get() == rhs.m_opaque_sp.get()); + } + + return false; } -bool -SBTypeSummary::operator != (lldb::SBTypeSummary &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp != rhs.m_opaque_sp; -} - -lldb::TypeSummaryImplSP -SBTypeSummary::GetSP () -{ - return m_opaque_sp; -} - -void -SBTypeSummary::SetSP (const lldb::TypeSummaryImplSP &typesummary_impl_sp) -{ - m_opaque_sp = typesummary_impl_sp; -} - -SBTypeSummary::SBTypeSummary (const lldb::TypeSummaryImplSP &typesummary_impl_sp) : -m_opaque_sp(typesummary_impl_sp) -{ -} - -bool -SBTypeSummary::CopyOnWrite_Impl() -{ - if (!IsValid()) - return false; - - if (m_opaque_sp.unique()) - return true; - - TypeSummaryImplSP new_sp; - - if (CXXFunctionSummaryFormat* current_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - new_sp = TypeSummaryImplSP(new CXXFunctionSummaryFormat(GetOptions(), - current_summary_ptr->m_impl, - current_summary_ptr->m_description.c_str())); - } - else if (ScriptSummaryFormat* current_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - new_sp = TypeSummaryImplSP(new ScriptSummaryFormat(GetOptions(), - current_summary_ptr->GetFunctionName(), - current_summary_ptr->GetPythonScript())); - } - else if (StringSummaryFormat* current_summary_ptr = llvm::dyn_cast(m_opaque_sp.get())) - { - new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), - current_summary_ptr->GetSummaryString())); - } - - SetSP(new_sp); - - return nullptr != new_sp.get(); -} - -bool -SBTypeSummary::ChangeSummaryType (bool want_script) -{ - if (!IsValid()) - return false; - - TypeSummaryImplSP new_sp; - - if (want_script == (m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eScript)) - { - if (m_opaque_sp->GetKind() == lldb_private::TypeSummaryImpl::Kind::eCallback && !want_script) - new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); - else - return CopyOnWrite_Impl(); - } - - if (!new_sp) - { - if (want_script) - new_sp = TypeSummaryImplSP(new ScriptSummaryFormat(GetOptions(), "", "")); - else - new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); - } - - SetSP(new_sp); - +bool SBTypeSummary::operator!=(lldb::SBTypeSummary &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::TypeSummaryImplSP SBTypeSummary::GetSP() { return m_opaque_sp; } + +void SBTypeSummary::SetSP(const lldb::TypeSummaryImplSP &typesummary_impl_sp) { + m_opaque_sp = typesummary_impl_sp; +} + +SBTypeSummary::SBTypeSummary(const lldb::TypeSummaryImplSP &typesummary_impl_sp) + : m_opaque_sp(typesummary_impl_sp) {} + +bool SBTypeSummary::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + + if (m_opaque_sp.unique()) return true; + + TypeSummaryImplSP new_sp; + + if (CXXFunctionSummaryFormat *current_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new CXXFunctionSummaryFormat( + GetOptions(), current_summary_ptr->m_impl, + current_summary_ptr->m_description.c_str())); + } else if (ScriptSummaryFormat *current_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new ScriptSummaryFormat( + GetOptions(), current_summary_ptr->GetFunctionName(), + current_summary_ptr->GetPythonScript())); + } else if (StringSummaryFormat *current_summary_ptr = + llvm::dyn_cast(m_opaque_sp.get())) { + new_sp = TypeSummaryImplSP(new StringSummaryFormat( + GetOptions(), current_summary_ptr->GetSummaryString())); + } + + SetSP(new_sp); + + return nullptr != new_sp.get(); +} + +bool SBTypeSummary::ChangeSummaryType(bool want_script) { + if (!IsValid()) + return false; + + TypeSummaryImplSP new_sp; + + if (want_script == + (m_opaque_sp->GetKind() == TypeSummaryImpl::Kind::eScript)) { + if (m_opaque_sp->GetKind() == + lldb_private::TypeSummaryImpl::Kind::eCallback && + !want_script) + new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); + else + return CopyOnWrite_Impl(); + } + + if (!new_sp) { + if (want_script) + new_sp = TypeSummaryImplSP(new ScriptSummaryFormat(GetOptions(), "", "")); + else + new_sp = TypeSummaryImplSP(new StringSummaryFormat(GetOptions(), "")); + } + + SetSP(new_sp); + + return true; } diff --git a/lldb/source/API/SBTypeSynthetic.cpp b/lldb/source/API/SBTypeSynthetic.cpp index 6f9951dc555..37b6086f855 100644 --- a/lldb/source/API/SBTypeSynthetic.cpp +++ b/lldb/source/API/SBTypeSynthetic.cpp @@ -1,4 +1,5 @@ -//===-- SBTypeSynthetic.cpp -----------------------------------------*- C++ -*-===// +//===-- SBTypeSynthetic.cpp -----------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -18,190 +19,146 @@ using namespace lldb_private; #ifndef LLDB_DISABLE_PYTHON -SBTypeSynthetic::SBTypeSynthetic() : -m_opaque_sp() -{ -} +SBTypeSynthetic::SBTypeSynthetic() : m_opaque_sp() {} -SBTypeSynthetic -SBTypeSynthetic::CreateWithClassName (const char* data, uint32_t options) -{ - if (!data || data[0] == 0) - return SBTypeSynthetic(); - return SBTypeSynthetic(ScriptedSyntheticChildrenSP(new ScriptedSyntheticChildren(options, data, ""))); +SBTypeSynthetic SBTypeSynthetic::CreateWithClassName(const char *data, + uint32_t options) { + if (!data || data[0] == 0) + return SBTypeSynthetic(); + return SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, data, ""))); } -SBTypeSynthetic -SBTypeSynthetic::CreateWithScriptCode (const char* data, uint32_t options) -{ - if (!data || data[0] == 0) - return SBTypeSynthetic(); - return SBTypeSynthetic(ScriptedSyntheticChildrenSP(new ScriptedSyntheticChildren(options, "", data))); +SBTypeSynthetic SBTypeSynthetic::CreateWithScriptCode(const char *data, + uint32_t options) { + if (!data || data[0] == 0) + return SBTypeSynthetic(); + return SBTypeSynthetic(ScriptedSyntheticChildrenSP( + new ScriptedSyntheticChildren(options, "", data))); } -SBTypeSynthetic::SBTypeSynthetic (const lldb::SBTypeSynthetic &rhs) : -m_opaque_sp(rhs.m_opaque_sp) -{ +SBTypeSynthetic::SBTypeSynthetic(const lldb::SBTypeSynthetic &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} + +SBTypeSynthetic::~SBTypeSynthetic() {} + +bool SBTypeSynthetic::IsValid() const { return m_opaque_sp.get() != NULL; } + +bool SBTypeSynthetic::IsClassCode() { + if (!IsValid()) + return false; + const char *code = m_opaque_sp->GetPythonCode(); + return (code && *code); } -SBTypeSynthetic::~SBTypeSynthetic () -{ +bool SBTypeSynthetic::IsClassName() { + if (!IsValid()) + return false; + return !IsClassCode(); } -bool -SBTypeSynthetic::IsValid() const -{ - return m_opaque_sp.get() != NULL; +const char *SBTypeSynthetic::GetData() { + if (!IsValid()) + return NULL; + if (IsClassCode()) + return m_opaque_sp->GetPythonCode(); + else + return m_opaque_sp->GetPythonClassName(); } -bool -SBTypeSynthetic::IsClassCode() -{ - if (!IsValid()) - return false; - const char* code = m_opaque_sp->GetPythonCode(); - return (code && *code); +void SBTypeSynthetic::SetClassName(const char *data) { + if (IsValid() && data && *data) + m_opaque_sp->SetPythonClassName(data); } -bool -SBTypeSynthetic::IsClassName() -{ - if (!IsValid()) - return false; - return !IsClassCode(); +void SBTypeSynthetic::SetClassCode(const char *data) { + if (IsValid() && data && *data) + m_opaque_sp->SetPythonCode(data); } -const char* -SBTypeSynthetic::GetData () -{ - if (!IsValid()) - return NULL; - if (IsClassCode()) - return m_opaque_sp->GetPythonCode(); - else - return m_opaque_sp->GetPythonClassName(); +uint32_t SBTypeSynthetic::GetOptions() { + if (!IsValid()) + return lldb::eTypeOptionNone; + return m_opaque_sp->GetOptions(); } -void -SBTypeSynthetic::SetClassName (const char* data) -{ - if (IsValid() && data && *data) - m_opaque_sp->SetPythonClassName(data); +void SBTypeSynthetic::SetOptions(uint32_t value) { + if (!CopyOnWrite_Impl()) + return; + m_opaque_sp->SetOptions(value); } -void -SBTypeSynthetic::SetClassCode (const char* data) -{ - if (IsValid() && data && *data) - m_opaque_sp->SetPythonCode(data); +bool SBTypeSynthetic::GetDescription(lldb::SBStream &description, + lldb::DescriptionLevel description_level) { + if (m_opaque_sp) { + description.Printf("%s\n", m_opaque_sp->GetDescription().c_str()); + return true; + } + return false; } -uint32_t -SBTypeSynthetic::GetOptions () -{ - if (!IsValid()) - return lldb::eTypeOptionNone; - return m_opaque_sp->GetOptions(); +lldb::SBTypeSynthetic &SBTypeSynthetic:: +operator=(const lldb::SBTypeSynthetic &rhs) { + if (this != &rhs) { + m_opaque_sp = rhs.m_opaque_sp; + } + return *this; } -void -SBTypeSynthetic::SetOptions (uint32_t value) -{ - if (!CopyOnWrite_Impl()) - return; - m_opaque_sp->SetOptions(value); +bool SBTypeSynthetic::operator==(lldb::SBTypeSynthetic &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp == rhs.m_opaque_sp; } -bool -SBTypeSynthetic::GetDescription (lldb::SBStream &description, - lldb::DescriptionLevel description_level) -{ - if (m_opaque_sp) - { - description.Printf("%s\n", - m_opaque_sp->GetDescription().c_str()); - return true; - } +bool SBTypeSynthetic::IsEqualTo(lldb::SBTypeSynthetic &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + + if (m_opaque_sp->IsScripted() != rhs.m_opaque_sp->IsScripted()) + return false; + + if (IsClassCode() != rhs.IsClassCode()) + return false; + + if (strcmp(GetData(), rhs.GetData())) return false; + + return GetOptions() == rhs.GetOptions(); +} + +bool SBTypeSynthetic::operator!=(lldb::SBTypeSynthetic &rhs) { + if (IsValid() == false) + return !rhs.IsValid(); + return m_opaque_sp != rhs.m_opaque_sp; +} + +lldb::ScriptedSyntheticChildrenSP SBTypeSynthetic::GetSP() { + return m_opaque_sp; +} + +void SBTypeSynthetic::SetSP( + const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) { + m_opaque_sp = TypeSynthetic_impl_sp; } -lldb::SBTypeSynthetic & -SBTypeSynthetic::operator = (const lldb::SBTypeSynthetic &rhs) -{ - if (this != &rhs) - { - m_opaque_sp = rhs.m_opaque_sp; - } - return *this; -} - -bool -SBTypeSynthetic::operator == (lldb::SBTypeSynthetic &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp == rhs.m_opaque_sp; -} - -bool -SBTypeSynthetic::IsEqualTo (lldb::SBTypeSynthetic &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - - if (m_opaque_sp->IsScripted() != rhs.m_opaque_sp->IsScripted()) - return false; - - if (IsClassCode() != rhs.IsClassCode()) - return false; - - if ( strcmp(GetData(), rhs.GetData()) ) - return false; - - return GetOptions() == rhs.GetOptions(); - -} - -bool -SBTypeSynthetic::operator != (lldb::SBTypeSynthetic &rhs) -{ - if (IsValid() == false) - return !rhs.IsValid(); - return m_opaque_sp != rhs.m_opaque_sp; -} - -lldb::ScriptedSyntheticChildrenSP -SBTypeSynthetic::GetSP () -{ - return m_opaque_sp; -} - -void -SBTypeSynthetic::SetSP (const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) -{ - m_opaque_sp = TypeSynthetic_impl_sp; -} - -SBTypeSynthetic::SBTypeSynthetic (const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) : -m_opaque_sp(TypeSynthetic_impl_sp) -{ -} - -bool -SBTypeSynthetic::CopyOnWrite_Impl() -{ - if (!IsValid()) - return false; - if (m_opaque_sp.unique()) - return true; - - ScriptedSyntheticChildrenSP new_sp(new ScriptedSyntheticChildren(m_opaque_sp->GetOptions(), - m_opaque_sp->GetPythonClassName(), - m_opaque_sp->GetPythonCode())); - - SetSP(new_sp); - +SBTypeSynthetic::SBTypeSynthetic( + const lldb::ScriptedSyntheticChildrenSP &TypeSynthetic_impl_sp) + : m_opaque_sp(TypeSynthetic_impl_sp) {} + +bool SBTypeSynthetic::CopyOnWrite_Impl() { + if (!IsValid()) + return false; + if (m_opaque_sp.unique()) return true; + + ScriptedSyntheticChildrenSP new_sp(new ScriptedSyntheticChildren( + m_opaque_sp->GetOptions(), m_opaque_sp->GetPythonClassName(), + m_opaque_sp->GetPythonCode())); + + SetSP(new_sp); + + return true; } #endif // LLDB_DISABLE_PYTHON diff --git a/lldb/source/API/SBUnixSignals.cpp b/lldb/source/API/SBUnixSignals.cpp index 531c9782973..bb85912c23d 100644 --- a/lldb/source/API/SBUnixSignals.cpp +++ b/lldb/source/API/SBUnixSignals.cpp @@ -1,4 +1,5 @@ -//===-- SBUnixSignals.cpp -------------------------------------------*- C++ -*-===// +//===-- SBUnixSignals.cpp -------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -7,190 +8,136 @@ // //===----------------------------------------------------------------------===// -#include "lldb/lldb-defines.h" -#include "lldb/Target/Process.h" +#include "lldb/Core/Log.h" #include "lldb/Target/Platform.h" +#include "lldb/Target/Process.h" #include "lldb/Target/UnixSignals.h" -#include "lldb/Core/Log.h" +#include "lldb/lldb-defines.h" #include "lldb/API/SBUnixSignals.h" using namespace lldb; using namespace lldb_private; -SBUnixSignals::SBUnixSignals () -{} +SBUnixSignals::SBUnixSignals() {} -SBUnixSignals::SBUnixSignals (const SBUnixSignals &rhs) : - m_opaque_wp(rhs.m_opaque_wp) -{ -} +SBUnixSignals::SBUnixSignals(const SBUnixSignals &rhs) + : m_opaque_wp(rhs.m_opaque_wp) {} -SBUnixSignals::SBUnixSignals(ProcessSP &process_sp) : - m_opaque_wp(process_sp ? process_sp->GetUnixSignals() : nullptr) -{ -} +SBUnixSignals::SBUnixSignals(ProcessSP &process_sp) + : m_opaque_wp(process_sp ? process_sp->GetUnixSignals() : nullptr) {} -SBUnixSignals::SBUnixSignals(PlatformSP &platform_sp) : - m_opaque_wp(platform_sp ? platform_sp->GetUnixSignals() : nullptr) -{ -} +SBUnixSignals::SBUnixSignals(PlatformSP &platform_sp) + : m_opaque_wp(platform_sp ? platform_sp->GetUnixSignals() : nullptr) {} -const SBUnixSignals& -SBUnixSignals::operator = (const SBUnixSignals& rhs) -{ - if (this != &rhs) - m_opaque_wp = rhs.m_opaque_wp; - return *this; +const SBUnixSignals &SBUnixSignals::operator=(const SBUnixSignals &rhs) { + if (this != &rhs) + m_opaque_wp = rhs.m_opaque_wp; + return *this; } -SBUnixSignals::~SBUnixSignals() -{ -} +SBUnixSignals::~SBUnixSignals() {} -UnixSignalsSP -SBUnixSignals::GetSP() const -{ - return m_opaque_wp.lock(); -} +UnixSignalsSP SBUnixSignals::GetSP() const { return m_opaque_wp.lock(); } -void -SBUnixSignals::SetSP(const UnixSignalsSP &signals_sp) -{ - m_opaque_wp = signals_sp; +void SBUnixSignals::SetSP(const UnixSignalsSP &signals_sp) { + m_opaque_wp = signals_sp; } -void -SBUnixSignals::Clear () -{ - m_opaque_wp.reset(); -} +void SBUnixSignals::Clear() { m_opaque_wp.reset(); } -bool -SBUnixSignals::IsValid() const -{ - return static_cast(GetSP()); -} +bool SBUnixSignals::IsValid() const { return static_cast(GetSP()); } -const char * -SBUnixSignals::GetSignalAsCString (int32_t signo) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetSignalAsCString(signo); +const char *SBUnixSignals::GetSignalAsCString(int32_t signo) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetSignalAsCString(signo); - return nullptr; + return nullptr; } -int32_t -SBUnixSignals::GetSignalNumberFromName (const char *name) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetSignalNumberFromName(name); +int32_t SBUnixSignals::GetSignalNumberFromName(const char *name) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetSignalNumberFromName(name); - return LLDB_INVALID_SIGNAL_NUMBER; + return LLDB_INVALID_SIGNAL_NUMBER; } -bool -SBUnixSignals::GetShouldSuppress (int32_t signo) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetShouldSuppress(signo); +bool SBUnixSignals::GetShouldSuppress(int32_t signo) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldSuppress(signo); - return false; + return false; } -bool -SBUnixSignals::SetShouldSuppress (int32_t signo, bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); +bool SBUnixSignals::SetShouldSuppress(int32_t signo, bool value) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + auto signals_sp = GetSP(); - if (log) - { - log->Printf ("SBUnixSignals(%p)::SetShouldSuppress (signo=%d, value=%d)", - static_cast(signals_sp.get()), - signo, - value); - } + if (log) { + log->Printf("SBUnixSignals(%p)::SetShouldSuppress (signo=%d, value=%d)", + static_cast(signals_sp.get()), signo, value); + } - if (signals_sp) - return signals_sp->SetShouldSuppress(signo, value); + if (signals_sp) + return signals_sp->SetShouldSuppress(signo, value); - return false; + return false; } -bool -SBUnixSignals::GetShouldStop (int32_t signo) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetShouldStop(signo); +bool SBUnixSignals::GetShouldStop(int32_t signo) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldStop(signo); - return false; + return false; } -bool -SBUnixSignals::SetShouldStop (int32_t signo, bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); +bool SBUnixSignals::SetShouldStop(int32_t signo, bool value) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + auto signals_sp = GetSP(); - if (log) - { - log->Printf ("SBUnixSignals(%p)::SetShouldStop (signo=%d, value=%d)", - static_cast(signals_sp.get()), - signo, - value); - } + if (log) { + log->Printf("SBUnixSignals(%p)::SetShouldStop (signo=%d, value=%d)", + static_cast(signals_sp.get()), signo, value); + } - if (signals_sp) - return signals_sp->SetShouldStop(signo, value); + if (signals_sp) + return signals_sp->SetShouldStop(signo, value); - return false; + return false; } -bool -SBUnixSignals::GetShouldNotify (int32_t signo) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetShouldNotify(signo); +bool SBUnixSignals::GetShouldNotify(int32_t signo) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetShouldNotify(signo); - return false; + return false; } -bool -SBUnixSignals::SetShouldNotify (int32_t signo, bool value) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - auto signals_sp = GetSP(); +bool SBUnixSignals::SetShouldNotify(int32_t signo, bool value) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + auto signals_sp = GetSP(); - if (log) - { - log->Printf ("SBUnixSignals(%p)::SetShouldNotify (signo=%d, value=%d)", - static_cast(signals_sp.get()), - signo, - value); - } + if (log) { + log->Printf("SBUnixSignals(%p)::SetShouldNotify (signo=%d, value=%d)", + static_cast(signals_sp.get()), signo, value); + } - if (signals_sp) - return signals_sp->SetShouldNotify(signo, value); + if (signals_sp) + return signals_sp->SetShouldNotify(signo, value); - return false; + return false; } -int32_t -SBUnixSignals::GetNumSignals () const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetNumSignals(); +int32_t SBUnixSignals::GetNumSignals() const { + if (auto signals_sp = GetSP()) + return signals_sp->GetNumSignals(); - return -1; + return -1; } -int32_t -SBUnixSignals::GetSignalAtIndex (int32_t index) const -{ - if (auto signals_sp = GetSP()) - return signals_sp->GetSignalAtIndex(index); +int32_t SBUnixSignals::GetSignalAtIndex(int32_t index) const { + if (auto signals_sp = GetSP()) + return signals_sp->GetSignalAtIndex(index); - return LLDB_INVALID_SIGNAL_NUMBER; + return LLDB_INVALID_SIGNAL_NUMBER; } diff --git a/lldb/source/API/SBValue.cpp b/lldb/source/API/SBValue.cpp index 4fdcb0d5ecb..0531a3fe7d7 100644 --- a/lldb/source/API/SBValue.cpp +++ b/lldb/source/API/SBValue.cpp @@ -50,1864 +50,1558 @@ using namespace lldb; using namespace lldb_private; -class ValueImpl -{ +class ValueImpl { public: - ValueImpl () - { + ValueImpl() {} + + ValueImpl(lldb::ValueObjectSP in_valobj_sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic, + const char *name = NULL) + : m_valobj_sp(), m_use_dynamic(use_dynamic), + m_use_synthetic(use_synthetic), m_name(name) { + if (in_valobj_sp) { + if ((m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable( + lldb::eNoDynamicValues, false))) { + if (!m_name.IsEmpty()) + m_valobj_sp->SetName(m_name); + } } + } - ValueImpl (lldb::ValueObjectSP in_valobj_sp, - lldb::DynamicValueType use_dynamic, - bool use_synthetic, - const char *name = NULL) : - m_valobj_sp(), - m_use_dynamic(use_dynamic), - m_use_synthetic(use_synthetic), - m_name (name) - { - if (in_valobj_sp) - { - if ( (m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(lldb::eNoDynamicValues, false)) ) - { - if (!m_name.IsEmpty()) - m_valobj_sp->SetName(m_name); - } - } - } + ValueImpl(const ValueImpl &rhs) + : m_valobj_sp(rhs.m_valobj_sp), m_use_dynamic(rhs.m_use_dynamic), + m_use_synthetic(rhs.m_use_synthetic), m_name(rhs.m_name) {} - ValueImpl (const ValueImpl& rhs) : - m_valobj_sp(rhs.m_valobj_sp), - m_use_dynamic(rhs.m_use_dynamic), - m_use_synthetic(rhs.m_use_synthetic), - m_name (rhs.m_name) - { + ValueImpl &operator=(const ValueImpl &rhs) { + if (this != &rhs) { + m_valobj_sp = rhs.m_valobj_sp; + m_use_dynamic = rhs.m_use_dynamic; + m_use_synthetic = rhs.m_use_synthetic; + m_name = rhs.m_name; } - - ValueImpl & - operator = (const ValueImpl &rhs) - { - if (this != &rhs) - { - m_valobj_sp = rhs.m_valobj_sp; - m_use_dynamic = rhs.m_use_dynamic; - m_use_synthetic = rhs.m_use_synthetic; - m_name = rhs.m_name; - } - return *this; + return *this; + } + + bool IsValid() { + if (m_valobj_sp.get() == NULL) + return false; + else { + // FIXME: This check is necessary but not sufficient. We for sure don't + // want to touch SBValues whose owning + // targets have gone away. This check is a little weak in that it + // enforces that restriction when you call + // IsValid, but since IsValid doesn't lock the target, you have no + // guarantee that the SBValue won't go + // invalid after you call this... + // Also, an SBValue could depend on data from one of the modules in the + // target, and those could go away + // independently of the target, for instance if a module is unloaded. But + // right now, neither SBValues + // nor ValueObjects know which modules they depend on. So I have no good + // way to make that check without + // tracking that in all the ValueObject subclasses. + TargetSP target_sp = m_valobj_sp->GetTargetSP(); + if (target_sp && target_sp->IsValid()) + return true; + else + return false; } + } - bool - IsValid () - { - if (m_valobj_sp.get() == NULL) - return false; - else - { - // FIXME: This check is necessary but not sufficient. We for sure don't want to touch SBValues whose owning - // targets have gone away. This check is a little weak in that it enforces that restriction when you call - // IsValid, but since IsValid doesn't lock the target, you have no guarantee that the SBValue won't go - // invalid after you call this... - // Also, an SBValue could depend on data from one of the modules in the target, and those could go away - // independently of the target, for instance if a module is unloaded. But right now, neither SBValues - // nor ValueObjects know which modules they depend on. So I have no good way to make that check without - // tracking that in all the ValueObject subclasses. - TargetSP target_sp = m_valobj_sp->GetTargetSP(); - if (target_sp && target_sp->IsValid()) - return true; - else - return false; - } - } + lldb::ValueObjectSP GetRootSP() { return m_valobj_sp; } - lldb::ValueObjectSP - GetRootSP () - { - return m_valobj_sp; + lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, + std::unique_lock &lock, + Error &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (!m_valobj_sp) { + error.SetErrorString("invalid value object"); + return m_valobj_sp; } - lldb::ValueObjectSP - GetSP(Process::StopLocker &stop_locker, std::unique_lock &lock, Error &error) - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (!m_valobj_sp) - { - error.SetErrorString("invalid value object"); - return m_valobj_sp; - } - - lldb::ValueObjectSP value_sp = m_valobj_sp; + lldb::ValueObjectSP value_sp = m_valobj_sp; - Target *target = value_sp->GetTargetSP().get(); - if (!target) - return ValueObjectSP(); + Target *target = value_sp->GetTargetSP().get(); + if (!target) + return ValueObjectSP(); - lock = std::unique_lock(target->GetAPIMutex()); + lock = std::unique_lock(target->GetAPIMutex()); - ProcessSP process_sp(value_sp->GetProcessSP()); - if (process_sp && !stop_locker.TryLock (&process_sp->GetRunLock())) - { - // We don't allow people to play around with ValueObject if the process is running. - // If you want to look at values, pause the process, then look. - if (log) - log->Printf ("SBValue(%p)::GetSP() => error: process is running", - static_cast(value_sp.get())); - error.SetErrorString ("process must be stopped."); - return ValueObjectSP(); - } + ProcessSP process_sp(value_sp->GetProcessSP()); + if (process_sp && !stop_locker.TryLock(&process_sp->GetRunLock())) { + // We don't allow people to play around with ValueObject if the process is + // running. + // If you want to look at values, pause the process, then look. + if (log) + log->Printf("SBValue(%p)::GetSP() => error: process is running", + static_cast(value_sp.get())); + error.SetErrorString("process must be stopped."); + return ValueObjectSP(); + } - if (m_use_dynamic != eNoDynamicValues) - { - ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic); - if (dynamic_sp) - value_sp = dynamic_sp; - } + if (m_use_dynamic != eNoDynamicValues) { + ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic); + if (dynamic_sp) + value_sp = dynamic_sp; + } - if (m_use_synthetic) - { - ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue(m_use_synthetic); - if (synthetic_sp) - value_sp = synthetic_sp; - } + if (m_use_synthetic) { + ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue(m_use_synthetic); + if (synthetic_sp) + value_sp = synthetic_sp; + } - if (!value_sp) - error.SetErrorString("invalid value object"); - if (!m_name.IsEmpty()) - value_sp->SetName(m_name); + if (!value_sp) + error.SetErrorString("invalid value object"); + if (!m_name.IsEmpty()) + value_sp->SetName(m_name); - return value_sp; - } + return value_sp; + } - void - SetUseDynamic (lldb::DynamicValueType use_dynamic) - { - m_use_dynamic = use_dynamic; - } + void SetUseDynamic(lldb::DynamicValueType use_dynamic) { + m_use_dynamic = use_dynamic; + } - void - SetUseSynthetic (bool use_synthetic) - { - m_use_synthetic = use_synthetic; - } + void SetUseSynthetic(bool use_synthetic) { m_use_synthetic = use_synthetic; } - lldb::DynamicValueType - GetUseDynamic () - { - return m_use_dynamic; - } + lldb::DynamicValueType GetUseDynamic() { return m_use_dynamic; } - bool - GetUseSynthetic () - { - return m_use_synthetic; - } + bool GetUseSynthetic() { return m_use_synthetic; } - // All the derived values that we would make from the m_valobj_sp will share - // the ExecutionContext with m_valobj_sp, so we don't need to do the calculations - // in GetSP to return the Target, Process, Thread or Frame. It is convenient to - // provide simple accessors for these, which I do here. - TargetSP - GetTargetSP () - { - if (m_valobj_sp) - return m_valobj_sp->GetTargetSP(); - else - return TargetSP(); - } + // All the derived values that we would make from the m_valobj_sp will share + // the ExecutionContext with m_valobj_sp, so we don't need to do the + // calculations + // in GetSP to return the Target, Process, Thread or Frame. It is convenient + // to + // provide simple accessors for these, which I do here. + TargetSP GetTargetSP() { + if (m_valobj_sp) + return m_valobj_sp->GetTargetSP(); + else + return TargetSP(); + } - ProcessSP - GetProcessSP () - { - if (m_valobj_sp) - return m_valobj_sp->GetProcessSP(); - else - return ProcessSP(); - } + ProcessSP GetProcessSP() { + if (m_valobj_sp) + return m_valobj_sp->GetProcessSP(); + else + return ProcessSP(); + } - ThreadSP - GetThreadSP () - { - if (m_valobj_sp) - return m_valobj_sp->GetThreadSP(); - else - return ThreadSP(); - } + ThreadSP GetThreadSP() { + if (m_valobj_sp) + return m_valobj_sp->GetThreadSP(); + else + return ThreadSP(); + } - StackFrameSP - GetFrameSP () - { - if (m_valobj_sp) - return m_valobj_sp->GetFrameSP(); - else - return StackFrameSP(); - } + StackFrameSP GetFrameSP() { + if (m_valobj_sp) + return m_valobj_sp->GetFrameSP(); + else + return StackFrameSP(); + } private: - lldb::ValueObjectSP m_valobj_sp; - lldb::DynamicValueType m_use_dynamic; - bool m_use_synthetic; - ConstString m_name; + lldb::ValueObjectSP m_valobj_sp; + lldb::DynamicValueType m_use_dynamic; + bool m_use_synthetic; + ConstString m_name; }; -class ValueLocker -{ +class ValueLocker { public: - ValueLocker () - { - } + ValueLocker() {} - ValueObjectSP - GetLockedSP(ValueImpl &in_value) - { - return in_value.GetSP(m_stop_locker, m_lock, m_lock_error); - } + ValueObjectSP GetLockedSP(ValueImpl &in_value) { + return in_value.GetSP(m_stop_locker, m_lock, m_lock_error); + } + + Error &GetError() { return m_lock_error; } - Error & - GetError() - { - return m_lock_error; - } - private: - Process::StopLocker m_stop_locker; - std::unique_lock m_lock; - Error m_lock_error; + Process::StopLocker m_stop_locker; + std::unique_lock m_lock; + Error m_lock_error; }; -SBValue::SBValue () : -m_opaque_sp () -{ -} +SBValue::SBValue() : m_opaque_sp() {} -SBValue::SBValue (const lldb::ValueObjectSP &value_sp) -{ - SetSP(value_sp); -} +SBValue::SBValue(const lldb::ValueObjectSP &value_sp) { SetSP(value_sp); } + +SBValue::SBValue(const SBValue &rhs) { SetSP(rhs.m_opaque_sp); } -SBValue::SBValue(const SBValue &rhs) -{ +SBValue &SBValue::operator=(const SBValue &rhs) { + if (this != &rhs) { SetSP(rhs.m_opaque_sp); + } + return *this; } -SBValue & -SBValue::operator = (const SBValue &rhs) -{ - if (this != &rhs) - { - SetSP(rhs.m_opaque_sp); - } - return *this; -} +SBValue::~SBValue() {} -SBValue::~SBValue() -{ +bool SBValue::IsValid() { + // If this function ever changes to anything that does more than just + // check if the opaque shared pointer is non NULL, then we need to update + // all "if (m_opaque_sp)" code in this file. + return m_opaque_sp.get() != NULL && m_opaque_sp->IsValid() && + m_opaque_sp->GetRootSP().get() != NULL; } -bool -SBValue::IsValid () -{ - // If this function ever changes to anything that does more than just - // check if the opaque shared pointer is non NULL, then we need to update - // all "if (m_opaque_sp)" code in this file. - return m_opaque_sp.get() != NULL && m_opaque_sp->IsValid() && m_opaque_sp->GetRootSP().get() != NULL; -} +void SBValue::Clear() { m_opaque_sp.reset(); } -void -SBValue::Clear() -{ - m_opaque_sp.reset(); -} +SBError SBValue::GetError() { + SBError sb_error; -SBError -SBValue::GetError() -{ - SBError sb_error; - - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - sb_error.SetError(value_sp->GetError()); - else - sb_error.SetErrorStringWithFormat ("error: %s", locker.GetError().AsCString()); - - return sb_error; -} - -user_id_t -SBValue::GetID() -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->GetID(); - return LLDB_INVALID_UID; -} - -const char * -SBValue::GetName() -{ - const char *name = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - name = value_sp->GetName().GetCString(); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (name) - log->Printf ("SBValue(%p)::GetName () => \"%s\"", - static_cast(value_sp.get()), name); - else - log->Printf ("SBValue(%p)::GetName () => NULL", - static_cast(value_sp.get())); - } + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + sb_error.SetError(value_sp->GetError()); + else + sb_error.SetErrorStringWithFormat("error: %s", + locker.GetError().AsCString()); - return name; + return sb_error; } -const char * -SBValue::GetTypeName () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *name = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - name = value_sp->GetQualifiedTypeName().GetCString(); - } - - if (log) - { - if (name) - log->Printf ("SBValue(%p)::GetTypeName () => \"%s\"", - static_cast(value_sp.get()), name); - else - log->Printf ("SBValue(%p)::GetTypeName () => NULL", - static_cast(value_sp.get())); - } - - return name; -} - -const char * -SBValue::GetDisplayTypeName () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *name = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - name = value_sp->GetDisplayTypeName().GetCString(); - } - - if (log) - { - if (name) - log->Printf ("SBValue(%p)::GetTypeName () => \"%s\"", - static_cast(value_sp.get()), name); - else - log->Printf ("SBValue(%p)::GetTypeName () => NULL", - static_cast(value_sp.get())); - } - - return name; +user_id_t SBValue::GetID() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetID(); + return LLDB_INVALID_UID; } -size_t -SBValue::GetByteSize () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - size_t result = 0; - - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - result = value_sp->GetByteSize(); - } +const char *SBValue::GetName() { + const char *name = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + name = value_sp->GetName().GetCString(); - if (log) - log->Printf ("SBValue(%p)::GetByteSize () => %" PRIu64, - static_cast(value_sp.get()), - static_cast(result)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (name) + log->Printf("SBValue(%p)::GetName () => \"%s\"", + static_cast(value_sp.get()), name); + else + log->Printf("SBValue(%p)::GetName () => NULL", + static_cast(value_sp.get())); + } + + return name; +} + +const char *SBValue::GetTypeName() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *name = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + name = value_sp->GetQualifiedTypeName().GetCString(); + } + + if (log) { + if (name) + log->Printf("SBValue(%p)::GetTypeName () => \"%s\"", + static_cast(value_sp.get()), name); + else + log->Printf("SBValue(%p)::GetTypeName () => NULL", + static_cast(value_sp.get())); + } + + return name; +} + +const char *SBValue::GetDisplayTypeName() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *name = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + name = value_sp->GetDisplayTypeName().GetCString(); + } + + if (log) { + if (name) + log->Printf("SBValue(%p)::GetTypeName () => \"%s\"", + static_cast(value_sp.get()), name); + else + log->Printf("SBValue(%p)::GetTypeName () => NULL", + static_cast(value_sp.get())); + } - return result; + return name; } -bool -SBValue::IsInScope () -{ - bool result = false; +size_t SBValue::GetByteSize() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + size_t result = 0; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - result = value_sp->IsInScope (); - } + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + result = value_sp->GetByteSize(); + } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::IsInScope () => %i", - static_cast(value_sp.get()), result); + if (log) + log->Printf("SBValue(%p)::GetByteSize () => %" PRIu64, + static_cast(value_sp.get()), + static_cast(result)); - return result; + return result; } -const char * -SBValue::GetValue () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +bool SBValue::IsInScope() { + bool result = false; - const char *cstr = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - cstr = value_sp->GetValueAsCString (); - } - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetValue() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetValue() => NULL", - static_cast(value_sp.get())); - } + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + result = value_sp->IsInScope(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBValue(%p)::IsInScope () => %i", + static_cast(value_sp.get()), result); - return cstr; + return result; } -ValueType -SBValue::GetValueType () -{ - ValueType result = eValueTypeInvalid; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - result = value_sp->GetValueType(); +const char *SBValue::GetValue() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - switch (result) - { - case eValueTypeInvalid: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeInvalid", - static_cast(value_sp.get())); - break; - case eValueTypeVariableGlobal: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeVariableGlobal", - static_cast(value_sp.get())); - break; - case eValueTypeVariableStatic: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeVariableStatic", - static_cast(value_sp.get())); - break; - case eValueTypeVariableArgument: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeVariableArgument", - static_cast(value_sp.get())); - break; - case eValueTypeVariableLocal: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeVariableLocal", - static_cast(value_sp.get())); - break; - case eValueTypeRegister: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeRegister", - static_cast(value_sp.get())); - break; - case eValueTypeRegisterSet: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeRegisterSet", - static_cast(value_sp.get())); - break; - case eValueTypeConstResult: - log->Printf ("SBValue(%p)::GetValueType () => eValueTypeConstResult", - static_cast(value_sp.get())); - break; - case eValueTypeVariableThreadLocal: - log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableThreadLocal", - static_cast(value_sp.get())); - break; - } - } - return result; -} - -const char * -SBValue::GetObjectDescription () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *cstr = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - cstr = value_sp->GetObjectDescription (); - } - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetObjectDescription() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetObjectDescription() => NULL", - static_cast(value_sp.get())); - } - return cstr; -} - -const char * -SBValue::GetTypeValidatorResult () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *cstr = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - const auto& validation(value_sp->GetValidationStatus()); - if (TypeValidatorResult::Failure == validation.first) - { - if (validation.second.empty()) - cstr = "unknown error"; - else - cstr = validation.second.c_str(); - } - } - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetTypeValidatorResult() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetTypeValidatorResult() => NULL", - static_cast(value_sp.get())); - } - return cstr; -} - -SBType -SBValue::GetType() -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - SBType sb_type; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - TypeImplSP type_sp; - if (value_sp) - { - type_sp.reset (new TypeImpl(value_sp->GetTypeImpl())); - sb_type.SetSP(type_sp); - } - if (log) - { - if (type_sp) - log->Printf ("SBValue(%p)::GetType => SBType(%p)", - static_cast(value_sp.get()), - static_cast(type_sp.get())); - else - log->Printf ("SBValue(%p)::GetType => NULL", - static_cast(value_sp.get())); - } - return sb_type; -} - -bool -SBValue::GetValueDidChange () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool result = false; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - if (value_sp->UpdateValueIfNeeded(false)) - result = value_sp->GetValueDidChange (); - } - if (log) - log->Printf ("SBValue(%p)::GetValueDidChange() => %i", - static_cast(value_sp.get()), result); - - return result; -} - -const char * -SBValue::GetSummary () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *cstr = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - cstr = value_sp->GetSummaryAsCString(); - } - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetSummary() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetSummary() => NULL", - static_cast(value_sp.get())); - } - return cstr; -} - -const char * -SBValue::GetSummary (lldb::SBStream& stream, - lldb::SBTypeSummaryOptions& options) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - std::string buffer; - if (value_sp->GetSummaryAsCString(buffer,options.ref()) && !buffer.empty()) - stream.Printf("%s",buffer.c_str()); - } - const char* cstr = stream.GetData(); - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetSummary() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetSummary() => NULL", - static_cast(value_sp.get())); - } - return cstr; -} - -const char * -SBValue::GetLocation () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - const char *cstr = NULL; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - cstr = value_sp->GetLocationAsCString(); - } - if (log) - { - if (cstr) - log->Printf ("SBValue(%p)::GetLocation() => \"%s\"", - static_cast(value_sp.get()), cstr); - else - log->Printf ("SBValue(%p)::GetLocation() => NULL", - static_cast(value_sp.get())); - } - return cstr; + const char *cstr = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + cstr = value_sp->GetValueAsCString(); + } + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetValue() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetValue() => NULL", + static_cast(value_sp.get())); + } + + return cstr; +} + +ValueType SBValue::GetValueType() { + ValueType result = eValueTypeInvalid; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + result = value_sp->GetValueType(); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + switch (result) { + case eValueTypeInvalid: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeInvalid", + static_cast(value_sp.get())); + break; + case eValueTypeVariableGlobal: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableGlobal", + static_cast(value_sp.get())); + break; + case eValueTypeVariableStatic: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableStatic", + static_cast(value_sp.get())); + break; + case eValueTypeVariableArgument: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableArgument", + static_cast(value_sp.get())); + break; + case eValueTypeVariableLocal: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeVariableLocal", + static_cast(value_sp.get())); + break; + case eValueTypeRegister: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeRegister", + static_cast(value_sp.get())); + break; + case eValueTypeRegisterSet: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeRegisterSet", + static_cast(value_sp.get())); + break; + case eValueTypeConstResult: + log->Printf("SBValue(%p)::GetValueType () => eValueTypeConstResult", + static_cast(value_sp.get())); + break; + case eValueTypeVariableThreadLocal: + log->Printf( + "SBValue(%p)::GetValueType () => eValueTypeVariableThreadLocal", + static_cast(value_sp.get())); + break; + } + } + return result; +} + +const char *SBValue::GetObjectDescription() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *cstr = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + cstr = value_sp->GetObjectDescription(); + } + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetObjectDescription() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetObjectDescription() => NULL", + static_cast(value_sp.get())); + } + return cstr; +} + +const char *SBValue::GetTypeValidatorResult() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *cstr = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + const auto &validation(value_sp->GetValidationStatus()); + if (TypeValidatorResult::Failure == validation.first) { + if (validation.second.empty()) + cstr = "unknown error"; + else + cstr = validation.second.c_str(); + } + } + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetTypeValidatorResult() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetTypeValidatorResult() => NULL", + static_cast(value_sp.get())); + } + return cstr; +} + +SBType SBValue::GetType() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + SBType sb_type; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TypeImplSP type_sp; + if (value_sp) { + type_sp.reset(new TypeImpl(value_sp->GetTypeImpl())); + sb_type.SetSP(type_sp); + } + if (log) { + if (type_sp) + log->Printf("SBValue(%p)::GetType => SBType(%p)", + static_cast(value_sp.get()), + static_cast(type_sp.get())); + else + log->Printf("SBValue(%p)::GetType => NULL", + static_cast(value_sp.get())); + } + return sb_type; +} + +bool SBValue::GetValueDidChange() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool result = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(false)) + result = value_sp->GetValueDidChange(); + } + if (log) + log->Printf("SBValue(%p)::GetValueDidChange() => %i", + static_cast(value_sp.get()), result); + + return result; +} + +const char *SBValue::GetSummary() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *cstr = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + cstr = value_sp->GetSummaryAsCString(); + } + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetSummary() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetSummary() => NULL", + static_cast(value_sp.get())); + } + return cstr; +} + +const char *SBValue::GetSummary(lldb::SBStream &stream, + lldb::SBTypeSummaryOptions &options) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + std::string buffer; + if (value_sp->GetSummaryAsCString(buffer, options.ref()) && !buffer.empty()) + stream.Printf("%s", buffer.c_str()); + } + const char *cstr = stream.GetData(); + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetSummary() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetSummary() => NULL", + static_cast(value_sp.get())); + } + return cstr; +} + +const char *SBValue::GetLocation() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + const char *cstr = NULL; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + cstr = value_sp->GetLocationAsCString(); + } + if (log) { + if (cstr) + log->Printf("SBValue(%p)::GetLocation() => \"%s\"", + static_cast(value_sp.get()), cstr); + else + log->Printf("SBValue(%p)::GetLocation() => NULL", + static_cast(value_sp.get())); + } + return cstr; } // Deprecated - use the one that takes an lldb::SBError -bool -SBValue::SetValueFromCString (const char *value_str) -{ - lldb::SBError dummy; - return SetValueFromCString(value_str,dummy); -} - -bool -SBValue::SetValueFromCString (const char *value_str, lldb::SBError& error) -{ - bool success = false; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (value_sp) - { - success = value_sp->SetValueFromCString (value_str,error.ref()); - } - else - error.SetErrorStringWithFormat ("Could not get value: %s", locker.GetError().AsCString()); - - if (log) - log->Printf ("SBValue(%p)::SetValueFromCString(\"%s\") => %i", - static_cast(value_sp.get()), value_str, success); - - return success; -} - -lldb::SBTypeFormat -SBValue::GetTypeFormat () -{ - lldb::SBTypeFormat format; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - if (value_sp->UpdateValueIfNeeded(true)) - { - lldb::TypeFormatImplSP format_sp = value_sp->GetValueFormat(); - if (format_sp) - format.SetSP(format_sp); - } - } - return format; -} - -lldb::SBTypeSummary -SBValue::GetTypeSummary () -{ - lldb::SBTypeSummary summary; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - if (value_sp->UpdateValueIfNeeded(true)) - { - lldb::TypeSummaryImplSP summary_sp = value_sp->GetSummaryFormat(); - if (summary_sp) - summary.SetSP(summary_sp); - } - } - return summary; -} - -lldb::SBTypeFilter -SBValue::GetTypeFilter () -{ - lldb::SBTypeFilter filter; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - if (value_sp->UpdateValueIfNeeded(true)) - { - lldb::SyntheticChildrenSP synthetic_sp = value_sp->GetSyntheticChildren(); - - if (synthetic_sp && !synthetic_sp->IsScripted()) - { - TypeFilterImplSP filter_sp = std::static_pointer_cast(synthetic_sp); - filter.SetSP(filter_sp); - } - } - } - return filter; +bool SBValue::SetValueFromCString(const char *value_str) { + lldb::SBError dummy; + return SetValueFromCString(value_str, dummy); +} + +bool SBValue::SetValueFromCString(const char *value_str, lldb::SBError &error) { + bool success = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (value_sp) { + success = value_sp->SetValueFromCString(value_str, error.ref()); + } else + error.SetErrorStringWithFormat("Could not get value: %s", + locker.GetError().AsCString()); + + if (log) + log->Printf("SBValue(%p)::SetValueFromCString(\"%s\") => %i", + static_cast(value_sp.get()), value_str, success); + + return success; +} + +lldb::SBTypeFormat SBValue::GetTypeFormat() { + lldb::SBTypeFormat format; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::TypeFormatImplSP format_sp = value_sp->GetValueFormat(); + if (format_sp) + format.SetSP(format_sp); + } + } + return format; +} + +lldb::SBTypeSummary SBValue::GetTypeSummary() { + lldb::SBTypeSummary summary; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::TypeSummaryImplSP summary_sp = value_sp->GetSummaryFormat(); + if (summary_sp) + summary.SetSP(summary_sp); + } + } + return summary; +} + +lldb::SBTypeFilter SBValue::GetTypeFilter() { + lldb::SBTypeFilter filter; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::SyntheticChildrenSP synthetic_sp = value_sp->GetSyntheticChildren(); + + if (synthetic_sp && !synthetic_sp->IsScripted()) { + TypeFilterImplSP filter_sp = + std::static_pointer_cast(synthetic_sp); + filter.SetSP(filter_sp); + } + } + } + return filter; } #ifndef LLDB_DISABLE_PYTHON -lldb::SBTypeSynthetic -SBValue::GetTypeSynthetic () -{ - lldb::SBTypeSynthetic synthetic; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - if (value_sp->UpdateValueIfNeeded(true)) - { - lldb::SyntheticChildrenSP children_sp = value_sp->GetSyntheticChildren(); - - if (children_sp && children_sp->IsScripted()) - { - ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast(children_sp); - synthetic.SetSP(synth_sp); - } - } - } - return synthetic; +lldb::SBTypeSynthetic SBValue::GetTypeSynthetic() { + lldb::SBTypeSynthetic synthetic; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + if (value_sp->UpdateValueIfNeeded(true)) { + lldb::SyntheticChildrenSP children_sp = value_sp->GetSyntheticChildren(); + + if (children_sp && children_sp->IsScripted()) { + ScriptedSyntheticChildrenSP synth_sp = + std::static_pointer_cast(children_sp); + synthetic.SetSP(synth_sp); + } + } + } + return synthetic; } #endif -lldb::SBValue -SBValue::CreateChildAtOffset (const char *name, uint32_t offset, SBType type) -{ - lldb::SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - lldb::ValueObjectSP new_value_sp; - if (value_sp) - { - TypeImplSP type_sp (type.GetSP()); - if (type.IsValid()) - { - sb_value.SetSP(value_sp->GetSyntheticChildAtOffset(offset, type_sp->GetCompilerType(false), true),GetPreferDynamicValue(),GetPreferSyntheticValue(), name); - } - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBValue(%p)::CreateChildAtOffset => \"%s\"", - static_cast(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBValue(%p)::CreateChildAtOffset => NULL", - static_cast(value_sp.get())); - } - return sb_value; -} - -lldb::SBValue -SBValue::Cast (SBType type) -{ - lldb::SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - TypeImplSP type_sp (type.GetSP()); - if (value_sp && type_sp) - sb_value.SetSP(value_sp->Cast(type_sp->GetCompilerType(false)),GetPreferDynamicValue(),GetPreferSyntheticValue()); - return sb_value; -} - -lldb::SBValue -SBValue::CreateValueFromExpression (const char *name, const char* expression) -{ - SBExpressionOptions options; - options.ref().SetKeepInMemory(true); - return CreateValueFromExpression (name, expression, options); -} - -lldb::SBValue -SBValue::CreateValueFromExpression (const char *name, const char *expression, SBExpressionOptions &options) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - lldb::ValueObjectSP new_value_sp; - if (value_sp) - { - ExecutionContext exe_ctx (value_sp->GetExecutionContextRef()); - new_value_sp = ValueObject::CreateValueObjectFromExpression(name, expression, exe_ctx, options.ref()); - if (new_value_sp) - new_value_sp->SetName(ConstString(name)); - } - sb_value.SetSP(new_value_sp); - if (log) - { - if (new_value_sp) - log->Printf ("SBValue(%p)::CreateValueFromExpression(name=\"%s\", expression=\"%s\") => SBValue (%p)", - static_cast(value_sp.get()), name, expression, - static_cast(new_value_sp.get())); - else - log->Printf ("SBValue(%p)::CreateValueFromExpression(name=\"%s\", expression=\"%s\") => NULL", - static_cast(value_sp.get()), name, expression); - } - return sb_value; -} - -lldb::SBValue -SBValue::CreateValueFromAddress(const char* name, lldb::addr_t address, SBType sb_type) -{ - lldb::SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - lldb::ValueObjectSP new_value_sp; - lldb::TypeImplSP type_impl_sp (sb_type.GetSP()); - if (value_sp && type_impl_sp) - { - CompilerType ast_type(type_impl_sp->GetCompilerType(true)); - ExecutionContext exe_ctx (value_sp->GetExecutionContextRef()); - new_value_sp = ValueObject::CreateValueObjectFromAddress(name, address, exe_ctx, ast_type); - } - sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBValue(%p)::CreateValueFromAddress => \"%s\"", - static_cast(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBValue(%p)::CreateValueFromAddress => NULL", - static_cast(value_sp.get())); - } - return sb_value; -} - -lldb::SBValue -SBValue::CreateValueFromData (const char* name, SBData data, SBType sb_type) -{ - lldb::SBValue sb_value; - lldb::ValueObjectSP new_value_sp; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - lldb::TypeImplSP type_impl_sp (sb_type.GetSP()); - if (value_sp && type_impl_sp) - { - ExecutionContext exe_ctx (value_sp->GetExecutionContextRef()); - new_value_sp = ValueObject::CreateValueObjectFromData(name, **data, exe_ctx, type_impl_sp->GetCompilerType(true)); - new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad); - } - sb_value.SetSP(new_value_sp); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (new_value_sp) - log->Printf ("SBValue(%p)::CreateValueFromData => \"%s\"", - static_cast(value_sp.get()), - new_value_sp->GetName().AsCString()); - else - log->Printf ("SBValue(%p)::CreateValueFromData => NULL", - static_cast(value_sp.get())); - } - return sb_value; -} - -SBValue -SBValue::GetChildAtIndex (uint32_t idx) -{ - const bool can_create_synthetic = false; - lldb::DynamicValueType use_dynamic = eNoDynamicValues; - TargetSP target_sp; - if (m_opaque_sp) - target_sp = m_opaque_sp->GetTargetSP(); - - if (target_sp) - use_dynamic = target_sp->GetPreferDynamicValue(); - - return GetChildAtIndex (idx, use_dynamic, can_create_synthetic); -} - -SBValue -SBValue::GetChildAtIndex (uint32_t idx, lldb::DynamicValueType use_dynamic, bool can_create_synthetic) -{ - lldb::ValueObjectSP child_sp; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - const bool can_create = true; - child_sp = value_sp->GetChildAtIndex (idx, can_create); - if (can_create_synthetic && !child_sp) - { - child_sp = value_sp->GetSyntheticArrayMember(idx, can_create); - } - } - - SBValue sb_value; - sb_value.SetSP (child_sp, use_dynamic, GetPreferSyntheticValue()); - if (log) - log->Printf ("SBValue(%p)::GetChildAtIndex (%u) => SBValue(%p)", - static_cast(value_sp.get()), idx, - static_cast(value_sp.get())); - - return sb_value; -} - -uint32_t -SBValue::GetIndexOfChildWithName (const char *name) -{ - uint32_t idx = UINT32_MAX; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - idx = value_sp->GetIndexOfChildWithName (ConstString(name)); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (idx == UINT32_MAX) - log->Printf ("SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => NOT FOUND", - static_cast(value_sp.get()), name); - else - log->Printf ("SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => %u", - static_cast(value_sp.get()), name, idx); - } - return idx; +lldb::SBValue SBValue::CreateChildAtOffset(const char *name, uint32_t offset, + SBType type) { + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + if (value_sp) { + TypeImplSP type_sp(type.GetSP()); + if (type.IsValid()) { + sb_value.SetSP(value_sp->GetSyntheticChildAtOffset( + offset, type_sp->GetCompilerType(false), true), + GetPreferDynamicValue(), GetPreferSyntheticValue(), name); + } + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBValue(%p)::CreateChildAtOffset => \"%s\"", + static_cast(value_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBValue(%p)::CreateChildAtOffset => NULL", + static_cast(value_sp.get())); + } + return sb_value; +} + +lldb::SBValue SBValue::Cast(SBType type) { + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TypeImplSP type_sp(type.GetSP()); + if (value_sp && type_sp) + sb_value.SetSP(value_sp->Cast(type_sp->GetCompilerType(false)), + GetPreferDynamicValue(), GetPreferSyntheticValue()); + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromExpression(const char *name, + const char *expression) { + SBExpressionOptions options; + options.ref().SetKeepInMemory(true); + return CreateValueFromExpression(name, expression, options); +} + +lldb::SBValue SBValue::CreateValueFromExpression(const char *name, + const char *expression, + SBExpressionOptions &options) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + if (value_sp) { + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromExpression( + name, expression, exe_ctx, options.ref()); + if (new_value_sp) + new_value_sp->SetName(ConstString(name)); + } + sb_value.SetSP(new_value_sp); + if (log) { + if (new_value_sp) + log->Printf("SBValue(%p)::CreateValueFromExpression(name=\"%s\", " + "expression=\"%s\") => SBValue (%p)", + static_cast(value_sp.get()), name, expression, + static_cast(new_value_sp.get())); + else + log->Printf("SBValue(%p)::CreateValueFromExpression(name=\"%s\", " + "expression=\"%s\") => NULL", + static_cast(value_sp.get()), name, expression); + } + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromAddress(const char *name, + lldb::addr_t address, + SBType sb_type) { + lldb::SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::ValueObjectSP new_value_sp; + lldb::TypeImplSP type_impl_sp(sb_type.GetSP()); + if (value_sp && type_impl_sp) { + CompilerType ast_type(type_impl_sp->GetCompilerType(true)); + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromAddress(name, address, + exe_ctx, ast_type); + } + sb_value.SetSP(new_value_sp); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBValue(%p)::CreateValueFromAddress => \"%s\"", + static_cast(value_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBValue(%p)::CreateValueFromAddress => NULL", + static_cast(value_sp.get())); + } + return sb_value; +} + +lldb::SBValue SBValue::CreateValueFromData(const char *name, SBData data, + SBType sb_type) { + lldb::SBValue sb_value; + lldb::ValueObjectSP new_value_sp; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + lldb::TypeImplSP type_impl_sp(sb_type.GetSP()); + if (value_sp && type_impl_sp) { + ExecutionContext exe_ctx(value_sp->GetExecutionContextRef()); + new_value_sp = ValueObject::CreateValueObjectFromData( + name, **data, exe_ctx, type_impl_sp->GetCompilerType(true)); + new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad); + } + sb_value.SetSP(new_value_sp); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (new_value_sp) + log->Printf("SBValue(%p)::CreateValueFromData => \"%s\"", + static_cast(value_sp.get()), + new_value_sp->GetName().AsCString()); + else + log->Printf("SBValue(%p)::CreateValueFromData => NULL", + static_cast(value_sp.get())); + } + return sb_value; +} + +SBValue SBValue::GetChildAtIndex(uint32_t idx) { + const bool can_create_synthetic = false; + lldb::DynamicValueType use_dynamic = eNoDynamicValues; + TargetSP target_sp; + if (m_opaque_sp) + target_sp = m_opaque_sp->GetTargetSP(); + + if (target_sp) + use_dynamic = target_sp->GetPreferDynamicValue(); + + return GetChildAtIndex(idx, use_dynamic, can_create_synthetic); +} + +SBValue SBValue::GetChildAtIndex(uint32_t idx, + lldb::DynamicValueType use_dynamic, + bool can_create_synthetic) { + lldb::ValueObjectSP child_sp; + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + const bool can_create = true; + child_sp = value_sp->GetChildAtIndex(idx, can_create); + if (can_create_synthetic && !child_sp) { + child_sp = value_sp->GetSyntheticArrayMember(idx, can_create); + } + } + + SBValue sb_value; + sb_value.SetSP(child_sp, use_dynamic, GetPreferSyntheticValue()); + if (log) + log->Printf("SBValue(%p)::GetChildAtIndex (%u) => SBValue(%p)", + static_cast(value_sp.get()), idx, + static_cast(value_sp.get())); + + return sb_value; +} + +uint32_t SBValue::GetIndexOfChildWithName(const char *name) { + uint32_t idx = UINT32_MAX; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + idx = value_sp->GetIndexOfChildWithName(ConstString(name)); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (idx == UINT32_MAX) + log->Printf( + "SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => NOT FOUND", + static_cast(value_sp.get()), name); + else + log->Printf("SBValue(%p)::GetIndexOfChildWithName (name=\"%s\") => %u", + static_cast(value_sp.get()), name, idx); + } + return idx; } -SBValue -SBValue::GetChildMemberWithName (const char *name) -{ - lldb::DynamicValueType use_dynamic_value = eNoDynamicValues; - TargetSP target_sp; - if (m_opaque_sp) - target_sp = m_opaque_sp->GetTargetSP(); +SBValue SBValue::GetChildMemberWithName(const char *name) { + lldb::DynamicValueType use_dynamic_value = eNoDynamicValues; + TargetSP target_sp; + if (m_opaque_sp) + target_sp = m_opaque_sp->GetTargetSP(); - if (target_sp) - use_dynamic_value = target_sp->GetPreferDynamicValue(); - return GetChildMemberWithName (name, use_dynamic_value); + if (target_sp) + use_dynamic_value = target_sp->GetPreferDynamicValue(); + return GetChildMemberWithName(name, use_dynamic_value); } SBValue -SBValue::GetChildMemberWithName (const char *name, lldb::DynamicValueType use_dynamic_value) -{ - lldb::ValueObjectSP child_sp; - const ConstString str_name (name); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - child_sp = value_sp->GetChildMemberWithName (str_name, true); - } - - SBValue sb_value; - sb_value.SetSP(child_sp, use_dynamic_value, GetPreferSyntheticValue()); - - if (log) - log->Printf ("SBValue(%p)::GetChildMemberWithName (name=\"%s\") => SBValue(%p)", - static_cast(value_sp.get()), name, - static_cast(value_sp.get())); +SBValue::GetChildMemberWithName(const char *name, + lldb::DynamicValueType use_dynamic_value) { + lldb::ValueObjectSP child_sp; + const ConstString str_name(name); - return sb_value; -} + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -lldb::SBValue -SBValue::GetDynamicValue (lldb::DynamicValueType use_dynamic) -{ - SBValue value_sb; - if (IsValid()) - { - ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(),use_dynamic,m_opaque_sp->GetUseSynthetic())); - value_sb.SetSP(proxy_sp); - } - return value_sb; -} + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + child_sp = value_sp->GetChildMemberWithName(str_name, true); + } -lldb::SBValue -SBValue::GetStaticValue () -{ - SBValue value_sb; - if (IsValid()) - { - ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(),eNoDynamicValues,m_opaque_sp->GetUseSynthetic())); - value_sb.SetSP(proxy_sp); - } - return value_sb; -} + SBValue sb_value; + sb_value.SetSP(child_sp, use_dynamic_value, GetPreferSyntheticValue()); -lldb::SBValue -SBValue::GetNonSyntheticValue () -{ - SBValue value_sb; - if (IsValid()) - { - ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(),m_opaque_sp->GetUseDynamic(),false)); - value_sb.SetSP(proxy_sp); - } - return value_sb; -} + if (log) + log->Printf( + "SBValue(%p)::GetChildMemberWithName (name=\"%s\") => SBValue(%p)", + static_cast(value_sp.get()), name, + static_cast(value_sp.get())); -lldb::DynamicValueType -SBValue::GetPreferDynamicValue () -{ - if (!IsValid()) - return eNoDynamicValues; - return m_opaque_sp->GetUseDynamic(); + return sb_value; } -void -SBValue::SetPreferDynamicValue (lldb::DynamicValueType use_dynamic) -{ - if (IsValid()) - return m_opaque_sp->SetUseDynamic (use_dynamic); +lldb::SBValue SBValue::GetDynamicValue(lldb::DynamicValueType use_dynamic) { + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), use_dynamic, + m_opaque_sp->GetUseSynthetic())); + value_sb.SetSP(proxy_sp); + } + return value_sb; } -bool -SBValue::GetPreferSyntheticValue () -{ - if (!IsValid()) - return false; - return m_opaque_sp->GetUseSynthetic(); +lldb::SBValue SBValue::GetStaticValue() { + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), + eNoDynamicValues, + m_opaque_sp->GetUseSynthetic())); + value_sb.SetSP(proxy_sp); + } + return value_sb; } -void -SBValue::SetPreferSyntheticValue (bool use_synthetic) -{ - if (IsValid()) - return m_opaque_sp->SetUseSynthetic (use_synthetic); +lldb::SBValue SBValue::GetNonSyntheticValue() { + SBValue value_sb; + if (IsValid()) { + ValueImplSP proxy_sp(new ValueImpl(m_opaque_sp->GetRootSP(), + m_opaque_sp->GetUseDynamic(), false)); + value_sb.SetSP(proxy_sp); + } + return value_sb; } -bool -SBValue::IsDynamic() -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->IsDynamic(); - return false; +lldb::DynamicValueType SBValue::GetPreferDynamicValue() { + if (!IsValid()) + return eNoDynamicValues; + return m_opaque_sp->GetUseDynamic(); } -bool -SBValue::IsSynthetic () -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->IsSynthetic(); - return false; +void SBValue::SetPreferDynamicValue(lldb::DynamicValueType use_dynamic) { + if (IsValid()) + return m_opaque_sp->SetUseDynamic(use_dynamic); } -bool -SBValue::IsSyntheticChildrenGenerated () -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->IsSyntheticChildrenGenerated(); +bool SBValue::GetPreferSyntheticValue() { + if (!IsValid()) return false; -} - -void -SBValue::SetSyntheticChildrenGenerated (bool is) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->SetSyntheticChildrenGenerated(is); -} - -lldb::SBValue -SBValue::GetValueForExpressionPath(const char* expr_path) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::ValueObjectSP child_sp; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - // using default values for all the fancy options, just do it if you can - child_sp = value_sp->GetValueForExpressionPath(expr_path); - } - - SBValue sb_value; - sb_value.SetSP(child_sp,GetPreferDynamicValue(),GetPreferSyntheticValue()); - - if (log) - log->Printf ("SBValue(%p)::GetValueForExpressionPath (expr_path=\"%s\") => SBValue(%p)", - static_cast(value_sp.get()), expr_path, - static_cast(value_sp.get())); - - return sb_value; -} - -int64_t -SBValue::GetValueAsSigned(SBError& error, int64_t fail_value) -{ - error.Clear(); - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - bool success = true; - uint64_t ret_val = fail_value; - ret_val = value_sp->GetValueAsSigned(fail_value, &success); - if (!success) - error.SetErrorString("could not resolve value"); - return ret_val; - } - else - error.SetErrorStringWithFormat ("could not get SBValue: %s", locker.GetError().AsCString()); - - return fail_value; -} - -uint64_t -SBValue::GetValueAsUnsigned(SBError& error, uint64_t fail_value) -{ - error.Clear(); - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - bool success = true; - uint64_t ret_val = fail_value; - ret_val = value_sp->GetValueAsUnsigned(fail_value, &success); - if (!success) - error.SetErrorString("could not resolve value"); - return ret_val; - } - else - error.SetErrorStringWithFormat ("could not get SBValue: %s", locker.GetError().AsCString()); - - return fail_value; -} - -int64_t -SBValue::GetValueAsSigned(int64_t fail_value) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - return value_sp->GetValueAsSigned(fail_value); - } - return fail_value; -} - -uint64_t -SBValue::GetValueAsUnsigned(uint64_t fail_value) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - return value_sp->GetValueAsUnsigned(fail_value); - } - return fail_value; -} - -bool -SBValue::MightHaveChildren () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool has_children = false; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - has_children = value_sp->MightHaveChildren(); - - if (log) - log->Printf ("SBValue(%p)::MightHaveChildren() => %i", - static_cast(value_sp.get()), has_children); - return has_children; -} - -bool -SBValue::IsRuntimeSupportValue () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - bool is_support = false; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - is_support = value_sp->IsRuntimeSupportValue(); - - if (log) - log->Printf ("SBValue(%p)::IsRuntimeSupportValue() => %i", - static_cast(value_sp.get()), is_support); - return is_support; -} - -uint32_t -SBValue::GetNumChildren () -{ - return GetNumChildren (UINT32_MAX); -} - -uint32_t -SBValue::GetNumChildren (uint32_t max) -{ - uint32_t num_children = 0; - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - num_children = value_sp->GetNumChildren(max); - - if (log) - log->Printf ("SBValue(%p)::GetNumChildren (%u) => %u", - static_cast(value_sp.get()), max, num_children); - - return num_children; -} - -SBValue -SBValue::Dereference () -{ - SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - Error error; - sb_value = value_sp->Dereference (error); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::Dereference () => SBValue(%p)", - static_cast(value_sp.get()), - static_cast(value_sp.get())); - - return sb_value; + return m_opaque_sp->GetUseSynthetic(); +} + +void SBValue::SetPreferSyntheticValue(bool use_synthetic) { + if (IsValid()) + return m_opaque_sp->SetUseSynthetic(use_synthetic); +} + +bool SBValue::IsDynamic() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsDynamic(); + return false; +} + +bool SBValue::IsSynthetic() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsSynthetic(); + return false; +} + +bool SBValue::IsSyntheticChildrenGenerated() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->IsSyntheticChildrenGenerated(); + return false; +} + +void SBValue::SetSyntheticChildrenGenerated(bool is) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->SetSyntheticChildrenGenerated(is); +} + +lldb::SBValue SBValue::GetValueForExpressionPath(const char *expr_path) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::ValueObjectSP child_sp; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + // using default values for all the fancy options, just do it if you can + child_sp = value_sp->GetValueForExpressionPath(expr_path); + } + + SBValue sb_value; + sb_value.SetSP(child_sp, GetPreferDynamicValue(), GetPreferSyntheticValue()); + + if (log) + log->Printf("SBValue(%p)::GetValueForExpressionPath (expr_path=\"%s\") => " + "SBValue(%p)", + static_cast(value_sp.get()), expr_path, + static_cast(value_sp.get())); + + return sb_value; +} + +int64_t SBValue::GetValueAsSigned(SBError &error, int64_t fail_value) { + error.Clear(); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + bool success = true; + uint64_t ret_val = fail_value; + ret_val = value_sp->GetValueAsSigned(fail_value, &success); + if (!success) + error.SetErrorString("could not resolve value"); + return ret_val; + } else + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + + return fail_value; +} + +uint64_t SBValue::GetValueAsUnsigned(SBError &error, uint64_t fail_value) { + error.Clear(); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + bool success = true; + uint64_t ret_val = fail_value; + ret_val = value_sp->GetValueAsUnsigned(fail_value, &success); + if (!success) + error.SetErrorString("could not resolve value"); + return ret_val; + } else + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + + return fail_value; +} + +int64_t SBValue::GetValueAsSigned(int64_t fail_value) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + return value_sp->GetValueAsSigned(fail_value); + } + return fail_value; +} + +uint64_t SBValue::GetValueAsUnsigned(uint64_t fail_value) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + return value_sp->GetValueAsUnsigned(fail_value); + } + return fail_value; +} + +bool SBValue::MightHaveChildren() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool has_children = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + has_children = value_sp->MightHaveChildren(); + + if (log) + log->Printf("SBValue(%p)::MightHaveChildren() => %i", + static_cast(value_sp.get()), has_children); + return has_children; +} + +bool SBValue::IsRuntimeSupportValue() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + bool is_support = false; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + is_support = value_sp->IsRuntimeSupportValue(); + + if (log) + log->Printf("SBValue(%p)::IsRuntimeSupportValue() => %i", + static_cast(value_sp.get()), is_support); + return is_support; +} + +uint32_t SBValue::GetNumChildren() { return GetNumChildren(UINT32_MAX); } + +uint32_t SBValue::GetNumChildren(uint32_t max) { + uint32_t num_children = 0; + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + num_children = value_sp->GetNumChildren(max); + + if (log) + log->Printf("SBValue(%p)::GetNumChildren (%u) => %u", + static_cast(value_sp.get()), max, num_children); + + return num_children; +} + +SBValue SBValue::Dereference() { + SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + Error error; + sb_value = value_sp->Dereference(error); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBValue(%p)::Dereference () => SBValue(%p)", + static_cast(value_sp.get()), + static_cast(value_sp.get())); + + return sb_value; } // Deprecated - please use GetType().IsPointerType() instead. -bool -SBValue::TypeIsPointerType () -{ - return GetType().IsPointerType(); -} - -void * -SBValue::GetOpaqueType() -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->GetCompilerType().GetOpaqueQualType(); - return NULL; -} - -lldb::SBTarget -SBValue::GetTarget() -{ - SBTarget sb_target; - TargetSP target_sp; - if (m_opaque_sp) - { - target_sp = m_opaque_sp->GetTargetSP(); - sb_target.SetSP (target_sp); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (target_sp.get() == NULL) - log->Printf ("SBValue(%p)::GetTarget () => NULL", - static_cast(m_opaque_sp.get())); - else - log->Printf ("SBValue(%p)::GetTarget () => %p", - static_cast(m_opaque_sp.get()), - static_cast(target_sp.get())); - } - return sb_target; -} - -lldb::SBProcess -SBValue::GetProcess() -{ - SBProcess sb_process; - ProcessSP process_sp; - if (m_opaque_sp) - { - process_sp = m_opaque_sp->GetProcessSP(); - sb_process.SetSP (process_sp); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (process_sp.get() == NULL) - log->Printf ("SBValue(%p)::GetProcess () => NULL", - static_cast(m_opaque_sp.get())); - else - log->Printf ("SBValue(%p)::GetProcess () => %p", - static_cast(m_opaque_sp.get()), - static_cast(process_sp.get())); - } - return sb_process; -} - -lldb::SBThread -SBValue::GetThread() -{ - SBThread sb_thread; - ThreadSP thread_sp; - if (m_opaque_sp) - { - thread_sp = m_opaque_sp->GetThreadSP(); - sb_thread.SetThread(thread_sp); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (thread_sp.get() == NULL) - log->Printf ("SBValue(%p)::GetThread () => NULL", - static_cast(m_opaque_sp.get())); - else - log->Printf ("SBValue(%p)::GetThread () => %p", - static_cast(m_opaque_sp.get()), - static_cast(thread_sp.get())); - } - return sb_thread; -} - -lldb::SBFrame -SBValue::GetFrame() -{ - SBFrame sb_frame; - StackFrameSP frame_sp; - if (m_opaque_sp) - { - frame_sp = m_opaque_sp->GetFrameSP(); - sb_frame.SetFrameSP (frame_sp); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - { - if (frame_sp.get() == NULL) - log->Printf ("SBValue(%p)::GetFrame () => NULL", - static_cast(m_opaque_sp.get())); - else - log->Printf ("SBValue(%p)::GetFrame () => %p", - static_cast(m_opaque_sp.get()), - static_cast(frame_sp.get())); - } - return sb_frame; -} - - -lldb::ValueObjectSP -SBValue::GetSP (ValueLocker &locker) const -{ - if (!m_opaque_sp || !m_opaque_sp->IsValid()) - { - locker.GetError().SetErrorString("No value"); - return ValueObjectSP(); - } - return locker.GetLockedSP(*m_opaque_sp.get()); -} - -lldb::ValueObjectSP -SBValue::GetSP () const -{ - ValueLocker locker; - return GetSP(locker); -} - -void -SBValue::SetSP (ValueImplSP impl_sp) -{ - m_opaque_sp = impl_sp; -} - -void -SBValue::SetSP (const lldb::ValueObjectSP &sp) -{ - if (sp) - { - lldb::TargetSP target_sp(sp->GetTargetSP()); - if (target_sp) - { - lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); - bool use_synthetic = target_sp->TargetProperties::GetEnableSyntheticValue(); - m_opaque_sp = ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic)); - } - else - m_opaque_sp = ValueImplSP(new ValueImpl(sp,eNoDynamicValues,true)); - } +bool SBValue::TypeIsPointerType() { return GetType().IsPointerType(); } + +void *SBValue::GetOpaqueType() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetCompilerType().GetOpaqueQualType(); + return NULL; +} + +lldb::SBTarget SBValue::GetTarget() { + SBTarget sb_target; + TargetSP target_sp; + if (m_opaque_sp) { + target_sp = m_opaque_sp->GetTargetSP(); + sb_target.SetSP(target_sp); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (target_sp.get() == NULL) + log->Printf("SBValue(%p)::GetTarget () => NULL", + static_cast(m_opaque_sp.get())); else - m_opaque_sp = ValueImplSP(new ValueImpl(sp,eNoDynamicValues,false)); -} - -void -SBValue::SetSP (const lldb::ValueObjectSP &sp, lldb::DynamicValueType use_dynamic) -{ - if (sp) - { - lldb::TargetSP target_sp(sp->GetTargetSP()); - if (target_sp) - { - bool use_synthetic = target_sp->TargetProperties::GetEnableSyntheticValue(); - SetSP (sp, use_dynamic, use_synthetic); - } - else - SetSP (sp, use_dynamic, true); - } + log->Printf("SBValue(%p)::GetTarget () => %p", + static_cast(m_opaque_sp.get()), + static_cast(target_sp.get())); + } + return sb_target; +} + +lldb::SBProcess SBValue::GetProcess() { + SBProcess sb_process; + ProcessSP process_sp; + if (m_opaque_sp) { + process_sp = m_opaque_sp->GetProcessSP(); + sb_process.SetSP(process_sp); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (process_sp.get() == NULL) + log->Printf("SBValue(%p)::GetProcess () => NULL", + static_cast(m_opaque_sp.get())); else - SetSP (sp, use_dynamic, false); -} - -void -SBValue::SetSP (const lldb::ValueObjectSP &sp, bool use_synthetic) -{ - if (sp) - { - lldb::TargetSP target_sp(sp->GetTargetSP()); - if (target_sp) - { - lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); - SetSP (sp, use_dynamic, use_synthetic); - } - else - SetSP (sp, eNoDynamicValues, use_synthetic); - } + log->Printf("SBValue(%p)::GetProcess () => %p", + static_cast(m_opaque_sp.get()), + static_cast(process_sp.get())); + } + return sb_process; +} + +lldb::SBThread SBValue::GetThread() { + SBThread sb_thread; + ThreadSP thread_sp; + if (m_opaque_sp) { + thread_sp = m_opaque_sp->GetThreadSP(); + sb_thread.SetThread(thread_sp); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (thread_sp.get() == NULL) + log->Printf("SBValue(%p)::GetThread () => NULL", + static_cast(m_opaque_sp.get())); else - SetSP (sp, eNoDynamicValues, use_synthetic); -} - -void -SBValue::SetSP (const lldb::ValueObjectSP &sp, lldb::DynamicValueType use_dynamic, bool use_synthetic) -{ - m_opaque_sp = ValueImplSP(new ValueImpl(sp,use_dynamic,use_synthetic)); -} - -void -SBValue::SetSP (const lldb::ValueObjectSP &sp, lldb::DynamicValueType use_dynamic, bool use_synthetic, const char *name) -{ - m_opaque_sp = ValueImplSP(new ValueImpl(sp,use_dynamic,use_synthetic, name)); -} - -bool -SBValue::GetExpressionPath (SBStream &description) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - value_sp->GetExpressionPath (description.ref(), false); - return true; - } - return false; -} - -bool -SBValue::GetExpressionPath (SBStream &description, bool qualify_cxx_base_classes) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - value_sp->GetExpressionPath (description.ref(), qualify_cxx_base_classes); - return true; - } - return false; -} - -bool -SBValue::GetDescription (SBStream &description) -{ - Stream &strm = description.ref(); - - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - value_sp->Dump(strm); + log->Printf("SBValue(%p)::GetThread () => %p", + static_cast(m_opaque_sp.get()), + static_cast(thread_sp.get())); + } + return sb_thread; +} + +lldb::SBFrame SBValue::GetFrame() { + SBFrame sb_frame; + StackFrameSP frame_sp; + if (m_opaque_sp) { + frame_sp = m_opaque_sp->GetFrameSP(); + sb_frame.SetFrameSP(frame_sp); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) { + if (frame_sp.get() == NULL) + log->Printf("SBValue(%p)::GetFrame () => NULL", + static_cast(m_opaque_sp.get())); else - strm.PutCString ("No value"); - + log->Printf("SBValue(%p)::GetFrame () => %p", + static_cast(m_opaque_sp.get()), + static_cast(frame_sp.get())); + } + return sb_frame; +} + +lldb::ValueObjectSP SBValue::GetSP(ValueLocker &locker) const { + if (!m_opaque_sp || !m_opaque_sp->IsValid()) { + locker.GetError().SetErrorString("No value"); + return ValueObjectSP(); + } + return locker.GetLockedSP(*m_opaque_sp.get()); +} + +lldb::ValueObjectSP SBValue::GetSP() const { + ValueLocker locker; + return GetSP(locker); +} + +void SBValue::SetSP(ValueImplSP impl_sp) { m_opaque_sp = impl_sp; } + +void SBValue::SetSP(const lldb::ValueObjectSP &sp) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); + bool use_synthetic = + target_sp->TargetProperties::GetEnableSyntheticValue(); + m_opaque_sp = ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic)); + } else + m_opaque_sp = ValueImplSP(new ValueImpl(sp, eNoDynamicValues, true)); + } else + m_opaque_sp = ValueImplSP(new ValueImpl(sp, eNoDynamicValues, false)); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + bool use_synthetic = + target_sp->TargetProperties::GetEnableSyntheticValue(); + SetSP(sp, use_dynamic, use_synthetic); + } else + SetSP(sp, use_dynamic, true); + } else + SetSP(sp, use_dynamic, false); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, bool use_synthetic) { + if (sp) { + lldb::TargetSP target_sp(sp->GetTargetSP()); + if (target_sp) { + lldb::DynamicValueType use_dynamic = target_sp->GetPreferDynamicValue(); + SetSP(sp, use_dynamic, use_synthetic); + } else + SetSP(sp, eNoDynamicValues, use_synthetic); + } else + SetSP(sp, eNoDynamicValues, use_synthetic); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic) { + m_opaque_sp = ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic)); +} + +void SBValue::SetSP(const lldb::ValueObjectSP &sp, + lldb::DynamicValueType use_dynamic, bool use_synthetic, + const char *name) { + m_opaque_sp = + ValueImplSP(new ValueImpl(sp, use_dynamic, use_synthetic, name)); +} + +bool SBValue::GetExpressionPath(SBStream &description) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + value_sp->GetExpressionPath(description.ref(), false); return true; + } + return false; } -lldb::Format -SBValue::GetFormat () -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - return value_sp->GetFormat(); - return eFormatDefault; -} - -void -SBValue::SetFormat (lldb::Format format) -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - value_sp->SetFormat(format); -} - -lldb::SBValue -SBValue::AddressOf() -{ - SBValue sb_value; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - Error error; - sb_value.SetSP(value_sp->AddressOf (error),GetPreferDynamicValue(), GetPreferSyntheticValue()); - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::AddressOf () => SBValue(%p)", - static_cast(value_sp.get()), - static_cast(value_sp.get())); - - return sb_value; -} - -lldb::addr_t -SBValue::GetLoadAddress() -{ - lldb::addr_t value = LLDB_INVALID_ADDRESS; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - TargetSP target_sp (value_sp->GetTargetSP()); - if (target_sp) - { - const bool scalar_is_load_address = true; - AddressType addr_type; - value = value_sp->GetAddressOf(scalar_is_load_address, &addr_type); - if (addr_type == eAddressTypeFile) - { - ModuleSP module_sp (value_sp->GetModule()); - if (!module_sp) - value = LLDB_INVALID_ADDRESS; - else - { - Address addr; - module_sp->ResolveFileAddress(value, addr); - value = addr.GetLoadAddress(target_sp.get()); - } - } - else if (addr_type == eAddressTypeHost || addr_type == eAddressTypeInvalid) - value = LLDB_INVALID_ADDRESS; +bool SBValue::GetExpressionPath(SBStream &description, + bool qualify_cxx_base_classes) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + value_sp->GetExpressionPath(description.ref(), qualify_cxx_base_classes); + return true; + } + return false; +} + +bool SBValue::GetDescription(SBStream &description) { + Stream &strm = description.ref(); + + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + value_sp->Dump(strm); + else + strm.PutCString("No value"); + + return true; +} + +lldb::Format SBValue::GetFormat() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + return value_sp->GetFormat(); + return eFormatDefault; +} + +void SBValue::SetFormat(lldb::Format format) { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) + value_sp->SetFormat(format); +} + +lldb::SBValue SBValue::AddressOf() { + SBValue sb_value; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + Error error; + sb_value.SetSP(value_sp->AddressOf(error), GetPreferDynamicValue(), + GetPreferSyntheticValue()); + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBValue(%p)::AddressOf () => SBValue(%p)", + static_cast(value_sp.get()), + static_cast(value_sp.get())); + + return sb_value; +} + +lldb::addr_t SBValue::GetLoadAddress() { + lldb::addr_t value = LLDB_INVALID_ADDRESS; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + TargetSP target_sp(value_sp->GetTargetSP()); + if (target_sp) { + const bool scalar_is_load_address = true; + AddressType addr_type; + value = value_sp->GetAddressOf(scalar_is_load_address, &addr_type); + if (addr_type == eAddressTypeFile) { + ModuleSP module_sp(value_sp->GetModule()); + if (!module_sp) + value = LLDB_INVALID_ADDRESS; + else { + Address addr; + module_sp->ResolveFileAddress(value, addr); + value = addr.GetLoadAddress(target_sp.get()); } - } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::GetLoadAddress () => (%" PRIu64 ")", - static_cast(value_sp.get()), value); - - return value; -} - -lldb::SBAddress -SBValue::GetAddress() -{ - Address addr; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - TargetSP target_sp (value_sp->GetTargetSP()); - if (target_sp) - { - lldb::addr_t value = LLDB_INVALID_ADDRESS; - const bool scalar_is_load_address = true; - AddressType addr_type; - value = value_sp->GetAddressOf(scalar_is_load_address, &addr_type); - if (addr_type == eAddressTypeFile) - { - ModuleSP module_sp (value_sp->GetModule()); - if (module_sp) - module_sp->ResolveFileAddress(value, addr); - } - else if (addr_type == eAddressTypeLoad) - { - // no need to check the return value on this.. if it can actually do the resolve - // addr will be in the form (section,offset), otherwise it will simply be returned - // as (NULL, value) - addr.SetLoadAddress(value, target_sp.get()); - } + } else if (addr_type == eAddressTypeHost || + addr_type == eAddressTypeInvalid) + value = LLDB_INVALID_ADDRESS; + } + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBValue(%p)::GetLoadAddress () => (%" PRIu64 ")", + static_cast(value_sp.get()), value); + + return value; +} + +lldb::SBAddress SBValue::GetAddress() { + Address addr; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + TargetSP target_sp(value_sp->GetTargetSP()); + if (target_sp) { + lldb::addr_t value = LLDB_INVALID_ADDRESS; + const bool scalar_is_load_address = true; + AddressType addr_type; + value = value_sp->GetAddressOf(scalar_is_load_address, &addr_type); + if (addr_type == eAddressTypeFile) { + ModuleSP module_sp(value_sp->GetModule()); + if (module_sp) + module_sp->ResolveFileAddress(value, addr); + } else if (addr_type == eAddressTypeLoad) { + // no need to check the return value on this.. if it can actually do the + // resolve + // addr will be in the form (section,offset), otherwise it will simply + // be returned + // as (NULL, value) + addr.SetLoadAddress(value, target_sp.get()); + } + } + } + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBValue(%p)::GetAddress () => (%s,%" PRIu64 ")", + static_cast(value_sp.get()), + (addr.GetSection() ? addr.GetSection()->GetName().GetCString() + : "NULL"), + addr.GetOffset()); + return SBAddress(new Address(addr)); +} + +lldb::SBData SBValue::GetPointeeData(uint32_t item_idx, uint32_t item_count) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::SBData sb_data; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + TargetSP target_sp(value_sp->GetTargetSP()); + if (target_sp) { + DataExtractorSP data_sp(new DataExtractor()); + value_sp->GetPointeeData(*data_sp, item_idx, item_count); + if (data_sp->GetByteSize() > 0) + *sb_data = data_sp; + } + } + if (log) + log->Printf("SBValue(%p)::GetPointeeData (%d, %d) => SBData(%p)", + static_cast(value_sp.get()), item_idx, item_count, + static_cast(sb_data.get())); + + return sb_data; +} + +lldb::SBData SBValue::GetData() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + lldb::SBData sb_data; + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + if (value_sp) { + DataExtractorSP data_sp(new DataExtractor()); + Error error; + value_sp->GetData(*data_sp, error); + if (error.Success()) + *sb_data = data_sp; + } + if (log) + log->Printf("SBValue(%p)::GetData () => SBData(%p)", + static_cast(value_sp.get()), + static_cast(sb_data.get())); + + return sb_data; +} + +bool SBValue::SetData(lldb::SBData &data, SBError &error) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + bool ret = true; + + if (value_sp) { + DataExtractor *data_extractor = data.get(); + + if (!data_extractor) { + if (log) + log->Printf("SBValue(%p)::SetData() => error: no data to set", + static_cast(value_sp.get())); + + error.SetErrorString("No data to set"); + ret = false; + } else { + Error set_error; + + value_sp->SetData(*data_extractor, set_error); + + if (!set_error.Success()) { + error.SetErrorStringWithFormat("Couldn't set data: %s", + set_error.AsCString()); + ret = false; + } + } + } else { + error.SetErrorStringWithFormat( + "Couldn't set data: could not get SBValue: %s", + locker.GetError().AsCString()); + ret = false; + } + + if (log) + log->Printf("SBValue(%p)::SetData (%p) => %s", + static_cast(value_sp.get()), + static_cast(data.get()), ret ? "true" : "false"); + return ret; +} + +lldb::SBDeclaration SBValue::GetDeclaration() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + SBDeclaration decl_sb; + if (value_sp) { + Declaration decl; + if (value_sp->GetDeclaration(decl)) + decl_sb.SetDeclaration(decl); + } + return decl_sb; +} + +lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, bool write, + SBError &error) { + SBWatchpoint sb_watchpoint; + + // If the SBValue is not valid, there's no point in even trying to watch it. + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + TargetSP target_sp(GetTarget().GetSP()); + if (value_sp && target_sp) { + // Read and Write cannot both be false. + if (!read && !write) + return sb_watchpoint; + + // If the value is not in scope, don't try and watch and invalid value + if (!IsInScope()) + return sb_watchpoint; + + addr_t addr = GetLoadAddress(); + if (addr == LLDB_INVALID_ADDRESS) + return sb_watchpoint; + size_t byte_size = GetByteSize(); + if (byte_size == 0) + return sb_watchpoint; + + uint32_t watch_type = 0; + if (read) + watch_type |= LLDB_WATCH_TYPE_READ; + if (write) + watch_type |= LLDB_WATCH_TYPE_WRITE; + + Error rc; + CompilerType type(value_sp->GetCompilerType()); + WatchpointSP watchpoint_sp = + target_sp->CreateWatchpoint(addr, byte_size, &type, watch_type, rc); + error.SetError(rc); + + if (watchpoint_sp) { + sb_watchpoint.SetSP(watchpoint_sp); + Declaration decl; + if (value_sp->GetDeclaration(decl)) { + if (decl.GetFile()) { + StreamString ss; + // True to show fullpath for declaration file. + decl.DumpStopContext(&ss, true); + watchpoint_sp->SetDeclInfo(ss.GetString()); } + } } - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + } else if (target_sp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (log) - log->Printf ("SBValue(%p)::GetAddress () => (%s,%" PRIu64 ")", - static_cast(value_sp.get()), - (addr.GetSection() - ? addr.GetSection()->GetName().GetCString() - : "NULL"), - addr.GetOffset()); - return SBAddress(new Address(addr)); -} - -lldb::SBData -SBValue::GetPointeeData (uint32_t item_idx, - uint32_t item_count) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::SBData sb_data; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - TargetSP target_sp (value_sp->GetTargetSP()); - if (target_sp) - { - DataExtractorSP data_sp(new DataExtractor()); - value_sp->GetPointeeData(*data_sp, item_idx, item_count); - if (data_sp->GetByteSize() > 0) - *sb_data = data_sp; - } - } + log->Printf("SBValue(%p)::Watch() => error getting SBValue: %s", + static_cast(value_sp.get()), + locker.GetError().AsCString()); + + error.SetErrorStringWithFormat("could not get SBValue: %s", + locker.GetError().AsCString()); + } else { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (log) - log->Printf ("SBValue(%p)::GetPointeeData (%d, %d) => SBData(%p)", - static_cast(value_sp.get()), item_idx, item_count, - static_cast(sb_data.get())); - - return sb_data; -} - -lldb::SBData -SBValue::GetData () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - lldb::SBData sb_data; - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - if (value_sp) - { - DataExtractorSP data_sp(new DataExtractor()); - Error error; - value_sp->GetData(*data_sp, error); - if (error.Success()) - *sb_data = data_sp; - } - if (log) - log->Printf ("SBValue(%p)::GetData () => SBData(%p)", - static_cast(value_sp.get()), - static_cast(sb_data.get())); + log->Printf("SBValue(%p)::Watch() => error getting SBValue: no target", + static_cast(value_sp.get())); + error.SetErrorString("could not set watchpoint, a target is required"); + } - return sb_data; + return sb_watchpoint; } -bool -SBValue::SetData (lldb::SBData &data, SBError &error) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - bool ret = true; - - if (value_sp) - { - DataExtractor *data_extractor = data.get(); - - if (!data_extractor) - { - if (log) - log->Printf ("SBValue(%p)::SetData() => error: no data to set", - static_cast(value_sp.get())); - - error.SetErrorString("No data to set"); - ret = false; - } - else - { - Error set_error; - - value_sp->SetData(*data_extractor, set_error); - - if (!set_error.Success()) - { - error.SetErrorStringWithFormat("Couldn't set data: %s", set_error.AsCString()); - ret = false; - } - } - } - else - { - error.SetErrorStringWithFormat ("Couldn't set data: could not get SBValue: %s", locker.GetError().AsCString()); - ret = false; - } - - if (log) - log->Printf ("SBValue(%p)::SetData (%p) => %s", - static_cast(value_sp.get()), - static_cast(data.get()), ret ? "true" : "false"); - return ret; -} - -lldb::SBDeclaration -SBValue::GetDeclaration () -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - SBDeclaration decl_sb; - if (value_sp) - { - Declaration decl; - if (value_sp->GetDeclaration(decl)) - decl_sb.SetDeclaration(decl); - } - return decl_sb; -} - -lldb::SBWatchpoint -SBValue::Watch (bool resolve_location, bool read, bool write, SBError &error) -{ - SBWatchpoint sb_watchpoint; - - // If the SBValue is not valid, there's no point in even trying to watch it. - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - TargetSP target_sp (GetTarget().GetSP()); - if (value_sp && target_sp) - { - // Read and Write cannot both be false. - if (!read && !write) - return sb_watchpoint; - - // If the value is not in scope, don't try and watch and invalid value - if (!IsInScope()) - return sb_watchpoint; - - addr_t addr = GetLoadAddress(); - if (addr == LLDB_INVALID_ADDRESS) - return sb_watchpoint; - size_t byte_size = GetByteSize(); - if (byte_size == 0) - return sb_watchpoint; - - uint32_t watch_type = 0; - if (read) - watch_type |= LLDB_WATCH_TYPE_READ; - if (write) - watch_type |= LLDB_WATCH_TYPE_WRITE; - - Error rc; - CompilerType type (value_sp->GetCompilerType()); - WatchpointSP watchpoint_sp = target_sp->CreateWatchpoint(addr, byte_size, &type, watch_type, rc); - error.SetError(rc); - - if (watchpoint_sp) - { - sb_watchpoint.SetSP (watchpoint_sp); - Declaration decl; - if (value_sp->GetDeclaration (decl)) - { - if (decl.GetFile()) - { - StreamString ss; - // True to show fullpath for declaration file. - decl.DumpStopContext(&ss, true); - watchpoint_sp->SetDeclInfo(ss.GetString()); - } - } - } - } - else if (target_sp) - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::Watch() => error getting SBValue: %s", - static_cast(value_sp.get()), - locker.GetError().AsCString()); - - error.SetErrorStringWithFormat("could not get SBValue: %s", locker.GetError().AsCString()); - } - else - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBValue(%p)::Watch() => error getting SBValue: no target", - static_cast(value_sp.get())); - error.SetErrorString("could not set watchpoint, a target is required"); - } - - return sb_watchpoint; -} - -// FIXME: Remove this method impl (as well as the decl in .h) once it is no longer needed. +// FIXME: Remove this method impl (as well as the decl in .h) once it is no +// longer needed. // Backward compatibility fix in the interim. -lldb::SBWatchpoint -SBValue::Watch (bool resolve_location, bool read, bool write) -{ - SBError error; - return Watch(resolve_location, read, write, error); -} - -lldb::SBWatchpoint -SBValue::WatchPointee (bool resolve_location, bool read, bool write, SBError &error) -{ - SBWatchpoint sb_watchpoint; - if (IsInScope() && GetType().IsPointerType()) - sb_watchpoint = Dereference().Watch (resolve_location, read, write, error); - return sb_watchpoint; -} - -lldb::SBValue -SBValue::Persist () -{ - ValueLocker locker; - lldb::ValueObjectSP value_sp(GetSP(locker)); - SBValue persisted_sb; - if (value_sp) - { - persisted_sb.SetSP(value_sp->Persist()); - } - return persisted_sb; +lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, + bool write) { + SBError error; + return Watch(resolve_location, read, write, error); +} + +lldb::SBWatchpoint SBValue::WatchPointee(bool resolve_location, bool read, + bool write, SBError &error) { + SBWatchpoint sb_watchpoint; + if (IsInScope() && GetType().IsPointerType()) + sb_watchpoint = Dereference().Watch(resolve_location, read, write, error); + return sb_watchpoint; +} + +lldb::SBValue SBValue::Persist() { + ValueLocker locker; + lldb::ValueObjectSP value_sp(GetSP(locker)); + SBValue persisted_sb; + if (value_sp) { + persisted_sb.SetSP(value_sp->Persist()); + } + return persisted_sb; } diff --git a/lldb/source/API/SBValueList.cpp b/lldb/source/API/SBValueList.cpp index 5461b05fb19..16289d9a9a9 100644 --- a/lldb/source/API/SBValueList.cpp +++ b/lldb/source/API/SBValueList.cpp @@ -7,10 +7,9 @@ // //===----------------------------------------------------------------------===// - #include "lldb/API/SBValueList.h" -#include "lldb/API/SBValue.h" #include "lldb/API/SBStream.h" +#include "lldb/API/SBValue.h" #include "lldb/Core/Log.h" #include "lldb/Core/ValueObjectList.h" @@ -19,281 +18,192 @@ using namespace lldb; using namespace lldb_private; -class ValueListImpl -{ +class ValueListImpl { public: - ValueListImpl () : - m_values() - { - } - - ValueListImpl (const ValueListImpl& rhs) : - m_values(rhs.m_values) - { - } - - ValueListImpl& - operator = (const ValueListImpl& rhs) - { - if (this == &rhs) - return *this; - m_values = rhs.m_values; - return *this; - } - - uint32_t - GetSize () - { - return m_values.size(); - } - - void - Append (const lldb::SBValue& sb_value) - { - m_values.push_back(sb_value); - } - - void - Append (const ValueListImpl& list) - { - for (auto val : list.m_values) - Append (val); - } - - lldb::SBValue - GetValueAtIndex (uint32_t index) - { - if (index >= GetSize()) - return lldb::SBValue(); - return m_values[index]; - } - - lldb::SBValue - FindValueByUID (lldb::user_id_t uid) - { - for (auto val : m_values) - { - if (val.IsValid() && val.GetID() == uid) - return val; - } - return lldb::SBValue(); + ValueListImpl() : m_values() {} + + ValueListImpl(const ValueListImpl &rhs) : m_values(rhs.m_values) {} + + ValueListImpl &operator=(const ValueListImpl &rhs) { + if (this == &rhs) + return *this; + m_values = rhs.m_values; + return *this; + } + + uint32_t GetSize() { return m_values.size(); } + + void Append(const lldb::SBValue &sb_value) { m_values.push_back(sb_value); } + + void Append(const ValueListImpl &list) { + for (auto val : list.m_values) + Append(val); + } + + lldb::SBValue GetValueAtIndex(uint32_t index) { + if (index >= GetSize()) + return lldb::SBValue(); + return m_values[index]; + } + + lldb::SBValue FindValueByUID(lldb::user_id_t uid) { + for (auto val : m_values) { + if (val.IsValid() && val.GetID() == uid) + return val; } - - lldb::SBValue - GetFirstValueByName (const char* name) const - { - if (name) - { - for (auto val : m_values) - { - if (val.IsValid() && val.GetName() && - strcmp(name,val.GetName()) == 0) - return val; - } - } - return lldb::SBValue(); + return lldb::SBValue(); + } + + lldb::SBValue GetFirstValueByName(const char *name) const { + if (name) { + for (auto val : m_values) { + if (val.IsValid() && val.GetName() && strcmp(name, val.GetName()) == 0) + return val; + } } + return lldb::SBValue(); + } private: - std::vector m_values; + std::vector m_values; }; -SBValueList::SBValueList () : - m_opaque_ap () -{ -} +SBValueList::SBValueList() : m_opaque_ap() {} -SBValueList::SBValueList (const SBValueList &rhs) : - m_opaque_ap () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBValueList::SBValueList(const SBValueList &rhs) : m_opaque_ap() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (rhs.IsValid()) - m_opaque_ap.reset (new ValueListImpl (*rhs)); + if (rhs.IsValid()) + m_opaque_ap.reset(new ValueListImpl(*rhs)); - if (log) - { - log->Printf ("SBValueList::SBValueList (rhs.ap=%p) => this.ap = %p", - static_cast(rhs.IsValid() ? rhs.m_opaque_ap.get() : NULL), - static_cast(m_opaque_ap.get())); - } + if (log) { + log->Printf( + "SBValueList::SBValueList (rhs.ap=%p) => this.ap = %p", + static_cast(rhs.IsValid() ? rhs.m_opaque_ap.get() : NULL), + static_cast(m_opaque_ap.get())); + } } -SBValueList::SBValueList (const ValueListImpl *lldb_object_ptr) : - m_opaque_ap () -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +SBValueList::SBValueList(const ValueListImpl *lldb_object_ptr) : m_opaque_ap() { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - if (lldb_object_ptr) - m_opaque_ap.reset (new ValueListImpl (*lldb_object_ptr)); + if (lldb_object_ptr) + m_opaque_ap.reset(new ValueListImpl(*lldb_object_ptr)); - if (log) - { - log->Printf ("SBValueList::SBValueList (lldb_object_ptr=%p) => this.ap = %p", - static_cast(lldb_object_ptr), - static_cast(m_opaque_ap.get())); - } + if (log) { + log->Printf("SBValueList::SBValueList (lldb_object_ptr=%p) => this.ap = %p", + static_cast(lldb_object_ptr), + static_cast(m_opaque_ap.get())); + } } -SBValueList::~SBValueList () -{ -} +SBValueList::~SBValueList() {} -bool -SBValueList::IsValid () const -{ - return (m_opaque_ap.get() != NULL); -} +bool SBValueList::IsValid() const { return (m_opaque_ap.get() != NULL); } -void -SBValueList::Clear() -{ - m_opaque_ap.reset(); -} +void SBValueList::Clear() { m_opaque_ap.reset(); } -const SBValueList & -SBValueList::operator = (const SBValueList &rhs) -{ - if (this != &rhs) - { - if (rhs.IsValid()) - m_opaque_ap.reset (new ValueListImpl (*rhs)); - else - m_opaque_ap.reset (); - } - return *this; +const SBValueList &SBValueList::operator=(const SBValueList &rhs) { + if (this != &rhs) { + if (rhs.IsValid()) + m_opaque_ap.reset(new ValueListImpl(*rhs)); + else + m_opaque_ap.reset(); + } + return *this; } -ValueListImpl * -SBValueList::operator->() -{ - return m_opaque_ap.get(); -} +ValueListImpl *SBValueList::operator->() { return m_opaque_ap.get(); } -ValueListImpl & -SBValueList::operator*() -{ - return *m_opaque_ap; -} +ValueListImpl &SBValueList::operator*() { return *m_opaque_ap; } -const ValueListImpl * -SBValueList::operator->() const -{ - return m_opaque_ap.get(); +const ValueListImpl *SBValueList::operator->() const { + return m_opaque_ap.get(); } -const ValueListImpl & -SBValueList::operator*() const -{ - return *m_opaque_ap; -} +const ValueListImpl &SBValueList::operator*() const { return *m_opaque_ap; } -void -SBValueList::Append (const SBValue &val_obj) -{ - CreateIfNeeded (); - m_opaque_ap->Append (val_obj); +void SBValueList::Append(const SBValue &val_obj) { + CreateIfNeeded(); + m_opaque_ap->Append(val_obj); } -void -SBValueList::Append (lldb::ValueObjectSP& val_obj_sp) -{ - if (val_obj_sp) - { - CreateIfNeeded (); - m_opaque_ap->Append (SBValue(val_obj_sp)); - } +void SBValueList::Append(lldb::ValueObjectSP &val_obj_sp) { + if (val_obj_sp) { + CreateIfNeeded(); + m_opaque_ap->Append(SBValue(val_obj_sp)); + } } -void -SBValueList::Append (const lldb::SBValueList& value_list) -{ - if (value_list.IsValid()) - { - CreateIfNeeded (); - m_opaque_ap->Append (*value_list); - } +void SBValueList::Append(const lldb::SBValueList &value_list) { + if (value_list.IsValid()) { + CreateIfNeeded(); + m_opaque_ap->Append(*value_list); + } } +SBValue SBValueList::GetValueAtIndex(uint32_t idx) const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBValue -SBValueList::GetValueAtIndex (uint32_t idx) const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); + // if (log) + // log->Printf ("SBValueList::GetValueAtIndex (uint32_t idx) idx = %d", + // idx); - //if (log) - // log->Printf ("SBValueList::GetValueAtIndex (uint32_t idx) idx = %d", idx); + SBValue sb_value; + if (m_opaque_ap.get()) + sb_value = m_opaque_ap->GetValueAtIndex(idx); - SBValue sb_value; - if (m_opaque_ap.get()) - sb_value = m_opaque_ap->GetValueAtIndex (idx); + if (log) { + SBStream sstr; + sb_value.GetDescription(sstr); + log->Printf("SBValueList::GetValueAtIndex (this.ap=%p, idx=%d) => SBValue " + "(this.sp = %p, '%s')", + static_cast(m_opaque_ap.get()), idx, + static_cast(sb_value.GetSP().get()), sstr.GetData()); + } - if (log) - { - SBStream sstr; - sb_value.GetDescription (sstr); - log->Printf ("SBValueList::GetValueAtIndex (this.ap=%p, idx=%d) => SBValue (this.sp = %p, '%s')", - static_cast(m_opaque_ap.get()), idx, - static_cast(sb_value.GetSP().get()), sstr.GetData()); - } - - return sb_value; + return sb_value; } -uint32_t -SBValueList::GetSize () const -{ - Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); +uint32_t SBValueList::GetSize() const { + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); - //if (log) - // log->Printf ("SBValueList::GetSize ()"); + // if (log) + // log->Printf ("SBValueList::GetSize ()"); - uint32_t size = 0; - if (m_opaque_ap.get()) - size = m_opaque_ap->GetSize(); + uint32_t size = 0; + if (m_opaque_ap.get()) + size = m_opaque_ap->GetSize(); - if (log) - log->Printf ("SBValueList::GetSize (this.ap=%p) => %d", - static_cast(m_opaque_ap.get()), size); + if (log) + log->Printf("SBValueList::GetSize (this.ap=%p) => %d", + static_cast(m_opaque_ap.get()), size); - return size; + return size; } -void -SBValueList::CreateIfNeeded () -{ - if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset (new ValueListImpl()); +void SBValueList::CreateIfNeeded() { + if (m_opaque_ap.get() == NULL) + m_opaque_ap.reset(new ValueListImpl()); } - -SBValue -SBValueList::FindValueObjectByUID (lldb::user_id_t uid) -{ - SBValue sb_value; - if (m_opaque_ap.get()) - sb_value = m_opaque_ap->FindValueByUID(uid); - return sb_value; +SBValue SBValueList::FindValueObjectByUID(lldb::user_id_t uid) { + SBValue sb_value; + if (m_opaque_ap.get()) + sb_value = m_opaque_ap->FindValueByUID(uid); + return sb_value; } -SBValue -SBValueList::GetFirstValueByName (const char* name) const -{ - SBValue sb_value; - if (m_opaque_ap.get()) - sb_value = m_opaque_ap->GetFirstValueByName(name); - return sb_value; +SBValue SBValueList::GetFirstValueByName(const char *name) const { + SBValue sb_value; + if (m_opaque_ap.get()) + sb_value = m_opaque_ap->GetFirstValueByName(name); + return sb_value; } -void * -SBValueList::opaque_ptr () -{ - return m_opaque_ap.get(); -} +void *SBValueList::opaque_ptr() { return m_opaque_ap.get(); } -ValueListImpl & -SBValueList::ref () -{ - CreateIfNeeded(); - return *m_opaque_ap.get(); +ValueListImpl &SBValueList::ref() { + CreateIfNeeded(); + return *m_opaque_ap.get(); } diff --git a/lldb/source/API/SBVariablesOptions.cpp b/lldb/source/API/SBVariablesOptions.cpp index 7c453567c0a..e12b9696521 100644 --- a/lldb/source/API/SBVariablesOptions.cpp +++ b/lldb/source/API/SBVariablesOptions.cpp @@ -1,4 +1,5 @@ -//===-- SBVariablesOptions.cpp --------------------------------------*- C++ -*-===// +//===-- SBVariablesOptions.cpp --------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -7,248 +8,148 @@ // //===----------------------------------------------------------------------===// - #include "lldb/API/SBVariablesOptions.h" using namespace lldb; using namespace lldb_private; -class VariablesOptionsImpl -{ +class VariablesOptionsImpl { public: - VariablesOptionsImpl () : - m_include_arguments(false), - m_include_locals(false), - m_include_statics(false), - m_in_scope_only(false), - m_include_runtime_support_values(false), - m_use_dynamic(lldb::eNoDynamicValues) - {} - - VariablesOptionsImpl (const VariablesOptionsImpl&) = default; - - ~VariablesOptionsImpl () = default; - - VariablesOptionsImpl& - operator = (const VariablesOptionsImpl&) = default; - - bool - GetIncludeArguments () const - { - return m_include_arguments; - } - - void - SetIncludeArguments (bool b) - { - m_include_arguments = b; - } - - bool - GetIncludeLocals () const - { - return m_include_locals; - } - - void - SetIncludeLocals (bool b) - { - m_include_locals = b; - } - - bool - GetIncludeStatics () const - { - return m_include_statics; - } - - void - SetIncludeStatics (bool b) - { - m_include_statics = b; - } - - bool - GetInScopeOnly () const - { - return m_in_scope_only; - } - - void - SetInScopeOnly (bool b) - { - m_in_scope_only = b; - } - - bool - GetIncludeRuntimeSupportValues () const - { - return m_include_runtime_support_values; - } - - void - SetIncludeRuntimeSupportValues (bool b) - { - m_include_runtime_support_values = b; - } - - lldb::DynamicValueType - GetUseDynamic () const - { - return m_use_dynamic; - } - - void - SetUseDynamic (lldb::DynamicValueType d) - { - m_use_dynamic = d; - } - - + VariablesOptionsImpl() + : m_include_arguments(false), m_include_locals(false), + m_include_statics(false), m_in_scope_only(false), + m_include_runtime_support_values(false), + m_use_dynamic(lldb::eNoDynamicValues) {} + + VariablesOptionsImpl(const VariablesOptionsImpl &) = default; + + ~VariablesOptionsImpl() = default; + + VariablesOptionsImpl &operator=(const VariablesOptionsImpl &) = default; + + bool GetIncludeArguments() const { return m_include_arguments; } + + void SetIncludeArguments(bool b) { m_include_arguments = b; } + + bool GetIncludeLocals() const { return m_include_locals; } + + void SetIncludeLocals(bool b) { m_include_locals = b; } + + bool GetIncludeStatics() const { return m_include_statics; } + + void SetIncludeStatics(bool b) { m_include_statics = b; } + + bool GetInScopeOnly() const { return m_in_scope_only; } + + void SetInScopeOnly(bool b) { m_in_scope_only = b; } + + bool GetIncludeRuntimeSupportValues() const { + return m_include_runtime_support_values; + } + + void SetIncludeRuntimeSupportValues(bool b) { + m_include_runtime_support_values = b; + } + + lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; } + + void SetUseDynamic(lldb::DynamicValueType d) { m_use_dynamic = d; } + private: - bool m_include_arguments : 1; - bool m_include_locals : 1; - bool m_include_statics : 1; - bool m_in_scope_only : 1; - bool m_include_runtime_support_values : 1; - lldb::DynamicValueType m_use_dynamic; + bool m_include_arguments : 1; + bool m_include_locals : 1; + bool m_include_statics : 1; + bool m_in_scope_only : 1; + bool m_include_runtime_support_values : 1; + lldb::DynamicValueType m_use_dynamic; }; -SBVariablesOptions::SBVariablesOptions () : -m_opaque_ap(new VariablesOptionsImpl()) -{ -} +SBVariablesOptions::SBVariablesOptions() + : m_opaque_ap(new VariablesOptionsImpl()) {} -SBVariablesOptions::SBVariablesOptions (const SBVariablesOptions& options) : -m_opaque_ap(new VariablesOptionsImpl(options.ref())) -{ -} +SBVariablesOptions::SBVariablesOptions(const SBVariablesOptions &options) + : m_opaque_ap(new VariablesOptionsImpl(options.ref())) {} -SBVariablesOptions& -SBVariablesOptions::operator = (const SBVariablesOptions& options) -{ - m_opaque_ap.reset(new VariablesOptionsImpl(options.ref())); - return *this; +SBVariablesOptions &SBVariablesOptions:: +operator=(const SBVariablesOptions &options) { + m_opaque_ap.reset(new VariablesOptionsImpl(options.ref())); + return *this; } -SBVariablesOptions::~SBVariablesOptions () = default; +SBVariablesOptions::~SBVariablesOptions() = default; -bool -SBVariablesOptions::IsValid () const -{ - return m_opaque_ap.get() != nullptr; +bool SBVariablesOptions::IsValid() const { + return m_opaque_ap.get() != nullptr; } -bool -SBVariablesOptions::GetIncludeArguments () const -{ - return m_opaque_ap->GetIncludeArguments(); +bool SBVariablesOptions::GetIncludeArguments() const { + return m_opaque_ap->GetIncludeArguments(); } -void -SBVariablesOptions::SetIncludeArguments (bool arguments) -{ - m_opaque_ap->SetIncludeArguments(arguments); +void SBVariablesOptions::SetIncludeArguments(bool arguments) { + m_opaque_ap->SetIncludeArguments(arguments); } -bool -SBVariablesOptions::GetIncludeLocals () const -{ - return m_opaque_ap->GetIncludeLocals(); +bool SBVariablesOptions::GetIncludeLocals() const { + return m_opaque_ap->GetIncludeLocals(); } -void -SBVariablesOptions::SetIncludeLocals (bool locals) -{ - m_opaque_ap->SetIncludeLocals(locals); +void SBVariablesOptions::SetIncludeLocals(bool locals) { + m_opaque_ap->SetIncludeLocals(locals); } -bool -SBVariablesOptions::GetIncludeStatics () const -{ - return m_opaque_ap->GetIncludeStatics(); +bool SBVariablesOptions::GetIncludeStatics() const { + return m_opaque_ap->GetIncludeStatics(); } -void -SBVariablesOptions::SetIncludeStatics (bool statics) -{ - m_opaque_ap->SetIncludeStatics(statics); +void SBVariablesOptions::SetIncludeStatics(bool statics) { + m_opaque_ap->SetIncludeStatics(statics); } -bool -SBVariablesOptions::GetInScopeOnly () const -{ - return m_opaque_ap->GetInScopeOnly(); +bool SBVariablesOptions::GetInScopeOnly() const { + return m_opaque_ap->GetInScopeOnly(); } -void -SBVariablesOptions::SetInScopeOnly (bool in_scope_only) -{ - m_opaque_ap->SetInScopeOnly(in_scope_only); +void SBVariablesOptions::SetInScopeOnly(bool in_scope_only) { + m_opaque_ap->SetInScopeOnly(in_scope_only); } -bool -SBVariablesOptions::GetIncludeRuntimeSupportValues () const -{ - return m_opaque_ap->GetIncludeRuntimeSupportValues(); +bool SBVariablesOptions::GetIncludeRuntimeSupportValues() const { + return m_opaque_ap->GetIncludeRuntimeSupportValues(); } -void -SBVariablesOptions::SetIncludeRuntimeSupportValues (bool runtime_support_values) -{ - m_opaque_ap->SetIncludeRuntimeSupportValues(runtime_support_values); +void SBVariablesOptions::SetIncludeRuntimeSupportValues( + bool runtime_support_values) { + m_opaque_ap->SetIncludeRuntimeSupportValues(runtime_support_values); } -lldb::DynamicValueType -SBVariablesOptions::GetUseDynamic () const -{ - return m_opaque_ap->GetUseDynamic(); +lldb::DynamicValueType SBVariablesOptions::GetUseDynamic() const { + return m_opaque_ap->GetUseDynamic(); } -void -SBVariablesOptions::SetUseDynamic (lldb::DynamicValueType dynamic) -{ - m_opaque_ap->SetUseDynamic(dynamic); +void SBVariablesOptions::SetUseDynamic(lldb::DynamicValueType dynamic) { + m_opaque_ap->SetUseDynamic(dynamic); } -VariablesOptionsImpl * -SBVariablesOptions::operator->() -{ - return m_opaque_ap.operator->(); +VariablesOptionsImpl *SBVariablesOptions::operator->() { + return m_opaque_ap.operator->(); } -const VariablesOptionsImpl * -SBVariablesOptions::operator->() const -{ - return m_opaque_ap.operator->(); +const VariablesOptionsImpl *SBVariablesOptions::operator->() const { + return m_opaque_ap.operator->(); } -VariablesOptionsImpl * -SBVariablesOptions::get () -{ - return m_opaque_ap.get(); -} +VariablesOptionsImpl *SBVariablesOptions::get() { return m_opaque_ap.get(); } -VariablesOptionsImpl & -SBVariablesOptions::ref() -{ - return *m_opaque_ap; -} +VariablesOptionsImpl &SBVariablesOptions::ref() { return *m_opaque_ap; } -const VariablesOptionsImpl & -SBVariablesOptions::ref() const -{ - return *m_opaque_ap; +const VariablesOptionsImpl &SBVariablesOptions::ref() const { + return *m_opaque_ap; } -SBVariablesOptions::SBVariablesOptions (VariablesOptionsImpl *lldb_object_ptr) : -m_opaque_ap(std::move(lldb_object_ptr)) -{ -} +SBVariablesOptions::SBVariablesOptions(VariablesOptionsImpl *lldb_object_ptr) + : m_opaque_ap(std::move(lldb_object_ptr)) {} -void -SBVariablesOptions::SetOptions (VariablesOptionsImpl *lldb_object_ptr) -{ - m_opaque_ap.reset(std::move(lldb_object_ptr)); +void SBVariablesOptions::SetOptions(VariablesOptionsImpl *lldb_object_ptr) { + m_opaque_ap.reset(std::move(lldb_object_ptr)); } - diff --git a/lldb/source/API/SBWatchpoint.cpp b/lldb/source/API/SBWatchpoint.cpp index 1c88a58191e..f5d72076487 100644 --- a/lldb/source/API/SBWatchpoint.cpp +++ b/lldb/source/API/SBWatchpoint.cpp @@ -8,296 +8,234 @@ //===----------------------------------------------------------------------===// #include "lldb/API/SBWatchpoint.h" -#include "lldb/API/SBDefines.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" +#include "lldb/API/SBDefines.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBStream.h" -#include "lldb/lldb-types.h" -#include "lldb/lldb-defines.h" #include "lldb/Breakpoint/Watchpoint.h" #include "lldb/Breakpoint/WatchpointList.h" #include "lldb/Core/Log.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" #include "lldb/Target/Target.h" +#include "lldb/lldb-defines.h" +#include "lldb/lldb-types.h" using namespace lldb; using namespace lldb_private; +SBWatchpoint::SBWatchpoint() : m_opaque_sp() {} -SBWatchpoint::SBWatchpoint () : - m_opaque_sp () -{ -} +SBWatchpoint::SBWatchpoint(const lldb::WatchpointSP &wp_sp) + : m_opaque_sp(wp_sp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -SBWatchpoint::SBWatchpoint (const lldb::WatchpointSP &wp_sp) : - m_opaque_sp (wp_sp) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - if (log) - { - SBStream sstr; - GetDescription (sstr, lldb::eDescriptionLevelBrief); - log->Printf ("SBWatchpoint::SBWatchpoint (const lldb::WatchpointSP &wp_sp" - "=%p) => this.sp = %p (%s)", - static_cast(wp_sp.get()), - static_cast(m_opaque_sp.get()), sstr.GetData()); - } + if (log) { + SBStream sstr; + GetDescription(sstr, lldb::eDescriptionLevelBrief); + log->Printf("SBWatchpoint::SBWatchpoint (const lldb::WatchpointSP &wp_sp" + "=%p) => this.sp = %p (%s)", + static_cast(wp_sp.get()), + static_cast(m_opaque_sp.get()), sstr.GetData()); + } } -SBWatchpoint::SBWatchpoint(const SBWatchpoint &rhs) : - m_opaque_sp (rhs.m_opaque_sp) -{ -} +SBWatchpoint::SBWatchpoint(const SBWatchpoint &rhs) + : m_opaque_sp(rhs.m_opaque_sp) {} -const SBWatchpoint & -SBWatchpoint::operator = (const SBWatchpoint &rhs) -{ - if (this != &rhs) - m_opaque_sp = rhs.m_opaque_sp; - return *this; +const SBWatchpoint &SBWatchpoint::operator=(const SBWatchpoint &rhs) { + if (this != &rhs) + m_opaque_sp = rhs.m_opaque_sp; + return *this; } +SBWatchpoint::~SBWatchpoint() {} -SBWatchpoint::~SBWatchpoint () -{ -} +watch_id_t SBWatchpoint::GetID() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); -watch_id_t -SBWatchpoint::GetID () -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - - watch_id_t watch_id = LLDB_INVALID_WATCH_ID; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - watch_id = watchpoint_sp->GetID(); - - if (log) - { - if (watch_id == LLDB_INVALID_WATCH_ID) - log->Printf ("SBWatchpoint(%p)::GetID () => LLDB_INVALID_WATCH_ID", - static_cast(watchpoint_sp.get())); - else - log->Printf ("SBWatchpoint(%p)::GetID () => %u", - static_cast(watchpoint_sp.get()), watch_id); - } - - return watch_id; -} + watch_id_t watch_id = LLDB_INVALID_WATCH_ID; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) + watch_id = watchpoint_sp->GetID(); + + if (log) { + if (watch_id == LLDB_INVALID_WATCH_ID) + log->Printf("SBWatchpoint(%p)::GetID () => LLDB_INVALID_WATCH_ID", + static_cast(watchpoint_sp.get())); + else + log->Printf("SBWatchpoint(%p)::GetID () => %u", + static_cast(watchpoint_sp.get()), watch_id); + } -bool -SBWatchpoint::IsValid() const -{ - return (bool) m_opaque_sp; + return watch_id; } -SBError -SBWatchpoint::GetError () -{ - SBError sb_error; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - sb_error.SetError(watchpoint_sp->GetError()); - } - return sb_error; +bool SBWatchpoint::IsValid() const { return (bool)m_opaque_sp; } + +SBError SBWatchpoint::GetError() { + SBError sb_error; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + sb_error.SetError(watchpoint_sp->GetError()); + } + return sb_error; } -int32_t -SBWatchpoint::GetHardwareIndex () -{ - int32_t hw_index = -1; +int32_t SBWatchpoint::GetHardwareIndex() { + int32_t hw_index = -1; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - hw_index = watchpoint_sp->GetHardwareIndex(); - } + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + hw_index = watchpoint_sp->GetHardwareIndex(); + } - return hw_index; + return hw_index; } -addr_t -SBWatchpoint::GetWatchAddress () -{ - addr_t ret_addr = LLDB_INVALID_ADDRESS; +addr_t SBWatchpoint::GetWatchAddress() { + addr_t ret_addr = LLDB_INVALID_ADDRESS; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - ret_addr = watchpoint_sp->GetLoadAddress(); - } + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + ret_addr = watchpoint_sp->GetLoadAddress(); + } - return ret_addr; + return ret_addr; } -size_t -SBWatchpoint::GetWatchSize () -{ - size_t watch_size = 0; +size_t SBWatchpoint::GetWatchSize() { + size_t watch_size = 0; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - watch_size = watchpoint_sp->GetByteSize(); - } + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watch_size = watchpoint_sp->GetByteSize(); + } - return watch_size; + return watch_size; } -void -SBWatchpoint::SetEnabled (bool enabled) -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - watchpoint_sp->SetEnabled(enabled); - } +void SBWatchpoint::SetEnabled(bool enabled) { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->SetEnabled(enabled); + } } -bool -SBWatchpoint::IsEnabled () -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - return watchpoint_sp->IsEnabled(); - } - else - return false; +bool SBWatchpoint::IsEnabled() { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return watchpoint_sp->IsEnabled(); + } else + return false; } -uint32_t -SBWatchpoint::GetHitCount () -{ - uint32_t count = 0; - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - count = watchpoint_sp->GetHitCount(); - } - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API)); - if (log) - log->Printf ("SBWatchpoint(%p)::GetHitCount () => %u", - static_cast(watchpoint_sp.get()), count); - - return count; +uint32_t SBWatchpoint::GetHitCount() { + uint32_t count = 0; + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + count = watchpoint_sp->GetHitCount(); + } + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); + if (log) + log->Printf("SBWatchpoint(%p)::GetHitCount () => %u", + static_cast(watchpoint_sp.get()), count); + + return count; } -uint32_t -SBWatchpoint::GetIgnoreCount () -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - return watchpoint_sp->GetIgnoreCount(); - } - else - return 0; +uint32_t SBWatchpoint::GetIgnoreCount() { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return watchpoint_sp->GetIgnoreCount(); + } else + return 0; } -void -SBWatchpoint::SetIgnoreCount (uint32_t n) -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - watchpoint_sp->SetIgnoreCount (n); - } +void SBWatchpoint::SetIgnoreCount(uint32_t n) { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->SetIgnoreCount(n); + } } -const char * -SBWatchpoint::GetCondition () -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - return watchpoint_sp->GetConditionText (); - } - return NULL; +const char *SBWatchpoint::GetCondition() { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + return watchpoint_sp->GetConditionText(); + } + return NULL; } -void -SBWatchpoint::SetCondition (const char *condition) -{ - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - watchpoint_sp->SetCondition (condition); - } +void SBWatchpoint::SetCondition(const char *condition) { + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->SetCondition(condition); + } } -bool -SBWatchpoint::GetDescription (SBStream &description, DescriptionLevel level) -{ - Stream &strm = description.ref(); - - lldb::WatchpointSP watchpoint_sp(GetSP()); - if (watchpoint_sp) - { - std::lock_guard guard(watchpoint_sp->GetTarget().GetAPIMutex()); - watchpoint_sp->GetDescription (&strm, level); - strm.EOL(); - } - else - strm.PutCString ("No value"); +bool SBWatchpoint::GetDescription(SBStream &description, + DescriptionLevel level) { + Stream &strm = description.ref(); - return true; -} + lldb::WatchpointSP watchpoint_sp(GetSP()); + if (watchpoint_sp) { + std::lock_guard guard( + watchpoint_sp->GetTarget().GetAPIMutex()); + watchpoint_sp->GetDescription(&strm, level); + strm.EOL(); + } else + strm.PutCString("No value"); -void -SBWatchpoint::Clear () -{ - m_opaque_sp.reset(); + return true; } -lldb::WatchpointSP -SBWatchpoint::GetSP () const -{ - return m_opaque_sp; -} +void SBWatchpoint::Clear() { m_opaque_sp.reset(); } -void -SBWatchpoint::SetSP (const lldb::WatchpointSP &sp) -{ - m_opaque_sp = sp; -} +lldb::WatchpointSP SBWatchpoint::GetSP() const { return m_opaque_sp; } -bool -SBWatchpoint::EventIsWatchpointEvent (const lldb::SBEvent &event) -{ - return Watchpoint::WatchpointEventData::GetEventDataFromEvent(event.get()) != NULL; +void SBWatchpoint::SetSP(const lldb::WatchpointSP &sp) { m_opaque_sp = sp; } +bool SBWatchpoint::EventIsWatchpointEvent(const lldb::SBEvent &event) { + return Watchpoint::WatchpointEventData::GetEventDataFromEvent(event.get()) != + NULL; } WatchpointEventType -SBWatchpoint::GetWatchpointEventTypeFromEvent (const SBEvent& event) -{ - if (event.IsValid()) - return Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent (event.GetSP()); - return eWatchpointEventTypeInvalidType; -} - -SBWatchpoint -SBWatchpoint::GetWatchpointFromEvent (const lldb::SBEvent& event) -{ - SBWatchpoint sb_watchpoint; - if (event.IsValid()) - sb_watchpoint.m_opaque_sp = Watchpoint::WatchpointEventData::GetWatchpointFromEvent (event.GetSP()); - return sb_watchpoint; +SBWatchpoint::GetWatchpointEventTypeFromEvent(const SBEvent &event) { + if (event.IsValid()) + return Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent( + event.GetSP()); + return eWatchpointEventTypeInvalidType; +} + +SBWatchpoint SBWatchpoint::GetWatchpointFromEvent(const lldb::SBEvent &event) { + SBWatchpoint sb_watchpoint; + if (event.IsValid()) + sb_watchpoint.m_opaque_sp = + Watchpoint::WatchpointEventData::GetWatchpointFromEvent(event.GetSP()); + return sb_watchpoint; } diff --git a/lldb/source/API/SystemInitializerFull.cpp b/lldb/source/API/SystemInitializerFull.cpp index 00cbb5dee75..a297a7c111c 100644 --- a/lldb/source/API/SystemInitializerFull.cpp +++ b/lldb/source/API/SystemInitializerFull.cpp @@ -43,8 +43,8 @@ #include "Plugins/ABI/SysV-s390x/ABISysV_s390x.h" #include "Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h" #include "Plugins/Disassembler/llvm/DisassemblerLLVMC.h" -#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h" #include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOS.h" +#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h" #include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h" #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h" #include "Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h" @@ -55,9 +55,9 @@ #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" #include "Plugins/Language/Go/GoLanguage.h" #include "Plugins/Language/Java/JavaLanguage.h" +#include "Plugins/Language/OCaml/OCamlLanguage.h" #include "Plugins/Language/ObjC/ObjCLanguage.h" #include "Plugins/Language/ObjCPlusPlus/ObjCPlusPlusLanguage.h" -#include "Plugins/Language/OCaml/OCamlLanguage.h" #include "Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h" #include "Plugins/LanguageRuntime/Go/GoLanguageRuntime.h" #include "Plugins/LanguageRuntime/Java/JavaLanguageRuntime.h" @@ -107,9 +107,9 @@ #endif #if defined(_MSC_VER) -#include "lldb/Host/windows/windows.h" #include "Plugins/Process/Windows/Live/ProcessWindowsLive.h" #include "Plugins/Process/Windows/MiniDump/ProcessWinMiniDump.h" +#include "lldb/Host/windows/windows.h" #endif #include "llvm/Support/TargetSelect.h" @@ -122,14 +122,12 @@ using namespace lldb_private; // Defined in the SWIG source file #if PY_MAJOR_VERSION >= 3 -extern "C" PyObject* -PyInit__lldb(void); +extern "C" PyObject *PyInit__lldb(void); #define LLDBSwigPyInit PyInit__lldb #else -extern "C" void -init_lldb(void); +extern "C" void init_lldb(void); #define LLDBSwigPyInit init_lldb #endif @@ -139,412 +137,370 @@ init_lldb(void); // we still need to use function pointers to them instead of relying // on linkage-time resolution because the SWIG stuff and this file // get built at different times -extern "C" bool -LLDBSwigPythonBreakpointCallbackFunction (const char *python_function_name, - const char *session_dictionary_name, - const lldb::StackFrameSP& sb_frame, - const lldb::BreakpointLocationSP& sb_bp_loc); +extern "C" bool LLDBSwigPythonBreakpointCallbackFunction( + const char *python_function_name, const char *session_dictionary_name, + const lldb::StackFrameSP &sb_frame, + const lldb::BreakpointLocationSP &sb_bp_loc); -extern "C" bool -LLDBSwigPythonWatchpointCallbackFunction (const char *python_function_name, - const char *session_dictionary_name, - const lldb::StackFrameSP& sb_frame, - const lldb::WatchpointSP& sb_wp); - -extern "C" bool -LLDBSwigPythonCallTypeScript (const char *python_function_name, - void *session_dictionary, - const lldb::ValueObjectSP& valobj_sp, - void** pyfunct_wrapper, - const lldb::TypeSummaryOptionsSP& options_sp, - std::string& retval); - -extern "C" void* -LLDBSwigPythonCreateSyntheticProvider (const char *python_class_name, - const char *session_dictionary_name, - const lldb::ValueObjectSP& valobj_sp); - -extern "C" void* -LLDBSwigPythonCreateCommandObject (const char *python_class_name, - const char *session_dictionary_name, - const lldb::DebuggerSP debugger_sp); - -extern "C" void* -LLDBSwigPythonCreateScriptedThreadPlan (const char *python_class_name, - const char *session_dictionary_name, - const lldb::ThreadPlanSP& thread_plan_sp); +extern "C" bool LLDBSwigPythonWatchpointCallbackFunction( + const char *python_function_name, const char *session_dictionary_name, + const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp); -extern "C" bool -LLDBSWIGPythonCallThreadPlan (void *implementor, - const char *method_name, - Event *event_sp, - bool &got_error); +extern "C" bool LLDBSwigPythonCallTypeScript( + const char *python_function_name, void *session_dictionary, + const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, + const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval); -extern "C" size_t -LLDBSwigPython_CalculateNumChildren (void *implementor, uint32_t max); +extern "C" void * +LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, + const char *session_dictionary_name, + const lldb::ValueObjectSP &valobj_sp); extern "C" void * -LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx); +LLDBSwigPythonCreateCommandObject(const char *python_class_name, + const char *session_dictionary_name, + const lldb::DebuggerSP debugger_sp); -extern "C" int -LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name); +extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan( + const char *python_class_name, const char *session_dictionary_name, + const lldb::ThreadPlanSP &thread_plan_sp); -extern "C" void * -LLDBSWIGPython_CastPyObjectToSBValue (void* data); +extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor, + const char *method_name, + Event *event_sp, bool &got_error); + +extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor, + uint32_t max); + +extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor, + uint32_t idx); + +extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor, + const char *child_name); + +extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data); extern lldb::ValueObjectSP -LLDBSWIGPython_GetValueObjectSPFromSBValue (void* data); +LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data); -extern "C" bool -LLDBSwigPython_UpdateSynthProviderInstance (void* implementor); +extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor); extern "C" bool -LLDBSwigPython_MightHaveChildrenSynthProviderInstance (void* implementor); +LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor); extern "C" void * -LLDBSwigPython_GetValueSynthProviderInstance (void* implementor); +LLDBSwigPython_GetValueSynthProviderInstance(void *implementor); extern "C" bool -LLDBSwigPythonCallCommand (const char *python_function_name, - const char *session_dictionary_name, - lldb::DebuggerSP& debugger, - const char* args, - lldb_private::CommandReturnObject &cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); +LLDBSwigPythonCallCommand(const char *python_function_name, + const char *session_dictionary_name, + lldb::DebuggerSP &debugger, const char *args, + lldb_private::CommandReturnObject &cmd_retobj, + lldb::ExecutionContextRefSP exe_ctx_ref_sp); extern "C" bool -LLDBSwigPythonCallCommandObject (void *implementor, - lldb::DebuggerSP& debugger, - const char* args, - lldb_private::CommandReturnObject& cmd_retobj, - lldb::ExecutionContextRefSP exe_ctx_ref_sp); +LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger, + const char *args, + lldb_private::CommandReturnObject &cmd_retobj, + lldb::ExecutionContextRefSP exe_ctx_ref_sp); extern "C" bool -LLDBSwigPythonCallModuleInit (const char *python_module_name, - const char *session_dictionary_name, - lldb::DebuggerSP& debugger); +LLDBSwigPythonCallModuleInit(const char *python_module_name, + const char *session_dictionary_name, + lldb::DebuggerSP &debugger); -extern "C" void* -LLDBSWIGPythonCreateOSPlugin (const char *python_class_name, - const char *session_dictionary_name, - const lldb::ProcessSP& process_sp); - -extern "C" bool -LLDBSWIGPythonRunScriptKeywordProcess (const char* python_function_name, - const char* session_dictionary_name, - lldb::ProcessSP& process, - std::string& output); +extern "C" void * +LLDBSWIGPythonCreateOSPlugin(const char *python_class_name, + const char *session_dictionary_name, + const lldb::ProcessSP &process_sp); -extern "C" bool -LLDBSWIGPythonRunScriptKeywordThread (const char* python_function_name, - const char* session_dictionary_name, - lldb::ThreadSP& thread, - std::string& output); +extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess( + const char *python_function_name, const char *session_dictionary_name, + lldb::ProcessSP &process, std::string &output); -extern "C" bool -LLDBSWIGPythonRunScriptKeywordTarget (const char* python_function_name, - const char* session_dictionary_name, - lldb::TargetSP& target, - std::string& output); +extern "C" bool LLDBSWIGPythonRunScriptKeywordThread( + const char *python_function_name, const char *session_dictionary_name, + lldb::ThreadSP &thread, std::string &output); -extern "C" bool -LLDBSWIGPythonRunScriptKeywordFrame (const char* python_function_name, - const char* session_dictionary_name, - lldb::StackFrameSP& frame, - std::string& output); +extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget( + const char *python_function_name, const char *session_dictionary_name, + lldb::TargetSP &target, std::string &output); -extern "C" bool -LLDBSWIGPythonRunScriptKeywordValue (const char* python_function_name, - const char* session_dictionary_name, - lldb::ValueObjectSP& value, - std::string& output); +extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame( + const char *python_function_name, const char *session_dictionary_name, + lldb::StackFrameSP &frame, std::string &output); -extern "C" void* -LLDBSWIGPython_GetDynamicSetting (void* module, - const char* setting, - const lldb::TargetSP& target_sp); +extern "C" bool LLDBSWIGPythonRunScriptKeywordValue( + const char *python_function_name, const char *session_dictionary_name, + lldb::ValueObjectSP &value, std::string &output); +extern "C" void * +LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, + const lldb::TargetSP &target_sp); #endif -SystemInitializerFull::SystemInitializerFull() -{ -} +SystemInitializerFull::SystemInitializerFull() {} -SystemInitializerFull::~SystemInitializerFull() -{ -} +SystemInitializerFull::~SystemInitializerFull() {} -void -SystemInitializerFull::Initialize() -{ - SystemInitializerCommon::Initialize(); - ScriptInterpreterNone::Initialize(); +void SystemInitializerFull::Initialize() { + SystemInitializerCommon::Initialize(); + ScriptInterpreterNone::Initialize(); #ifndef LLDB_DISABLE_PYTHON - OperatingSystemPython::Initialize(); + OperatingSystemPython::Initialize(); #endif - OperatingSystemGo::Initialize(); + OperatingSystemGo::Initialize(); #if !defined(LLDB_DISABLE_PYTHON) - InitializeSWIG(); + InitializeSWIG(); - // ScriptInterpreterPython::Initialize() depends on things like HostInfo being initialized - // so it can compute the python directory etc, so we need to do this after - // SystemInitializerCommon::Initialize(). - ScriptInterpreterPython::Initialize(); + // ScriptInterpreterPython::Initialize() depends on things like HostInfo being + // initialized + // so it can compute the python directory etc, so we need to do this after + // SystemInitializerCommon::Initialize(). + ScriptInterpreterPython::Initialize(); #endif - platform_freebsd::PlatformFreeBSD::Initialize(); - platform_linux::PlatformLinux::Initialize(); - platform_netbsd::PlatformNetBSD::Initialize(); - PlatformWindows::Initialize(); - PlatformKalimba::Initialize(); - platform_android::PlatformAndroid::Initialize(); - PlatformRemoteiOS::Initialize(); - PlatformMacOSX::Initialize(); + platform_freebsd::PlatformFreeBSD::Initialize(); + platform_linux::PlatformLinux::Initialize(); + platform_netbsd::PlatformNetBSD::Initialize(); + PlatformWindows::Initialize(); + PlatformKalimba::Initialize(); + platform_android::PlatformAndroid::Initialize(); + PlatformRemoteiOS::Initialize(); + PlatformMacOSX::Initialize(); #if defined(__APPLE__) - PlatformiOSSimulator::Initialize(); - PlatformDarwinKernel::Initialize(); + PlatformiOSSimulator::Initialize(); + PlatformDarwinKernel::Initialize(); #endif - // Initialize LLVM and Clang - llvm::InitializeAllTargets(); - llvm::InitializeAllAsmPrinters(); - llvm::InitializeAllTargetMCs(); - llvm::InitializeAllDisassemblers(); - - ClangASTContext::Initialize(); - GoASTContext::Initialize(); - JavaASTContext::Initialize(); - OCamlASTContext::Initialize(); - - ABIMacOSX_i386::Initialize(); - ABIMacOSX_arm::Initialize(); - ABIMacOSX_arm64::Initialize(); - ABISysV_arm::Initialize(); - ABISysV_arm64::Initialize(); - ABISysV_hexagon::Initialize(); - ABISysV_i386::Initialize(); - ABISysV_x86_64::Initialize(); - ABISysV_ppc::Initialize(); - ABISysV_ppc64::Initialize(); - ABISysV_mips::Initialize(); - ABISysV_mips64::Initialize(); - ABISysV_s390x::Initialize(); - DisassemblerLLVMC::Initialize(); - - JITLoaderGDB::Initialize(); - ProcessElfCore::Initialize(); + // Initialize LLVM and Clang + llvm::InitializeAllTargets(); + llvm::InitializeAllAsmPrinters(); + llvm::InitializeAllTargetMCs(); + llvm::InitializeAllDisassemblers(); + + ClangASTContext::Initialize(); + GoASTContext::Initialize(); + JavaASTContext::Initialize(); + OCamlASTContext::Initialize(); + + ABIMacOSX_i386::Initialize(); + ABIMacOSX_arm::Initialize(); + ABIMacOSX_arm64::Initialize(); + ABISysV_arm::Initialize(); + ABISysV_arm64::Initialize(); + ABISysV_hexagon::Initialize(); + ABISysV_i386::Initialize(); + ABISysV_x86_64::Initialize(); + ABISysV_ppc::Initialize(); + ABISysV_ppc64::Initialize(); + ABISysV_mips::Initialize(); + ABISysV_mips64::Initialize(); + ABISysV_s390x::Initialize(); + DisassemblerLLVMC::Initialize(); + + JITLoaderGDB::Initialize(); + ProcessElfCore::Initialize(); #if defined(_MSC_VER) - ProcessWinMiniDump::Initialize(); + ProcessWinMiniDump::Initialize(); #endif - MemoryHistoryASan::Initialize(); - AddressSanitizerRuntime::Initialize(); - ThreadSanitizerRuntime::Initialize(); - - SymbolVendorELF::Initialize(); - SymbolFileDWARF::Initialize(); - SymbolFilePDB::Initialize(); - SymbolFileSymtab::Initialize(); - UnwindAssemblyInstEmulation::Initialize(); - UnwindAssembly_x86::Initialize(); - EmulateInstructionARM64::Initialize(); - SymbolFileDWARFDebugMap::Initialize(); - ItaniumABILanguageRuntime::Initialize(); - AppleObjCRuntimeV2::Initialize(); - AppleObjCRuntimeV1::Initialize(); - SystemRuntimeMacOSX::Initialize(); - RenderScriptRuntime::Initialize(); - GoLanguageRuntime::Initialize(); - JavaLanguageRuntime::Initialize(); - - CPlusPlusLanguage::Initialize(); - GoLanguage::Initialize(); - JavaLanguage::Initialize(); - ObjCLanguage::Initialize(); - ObjCPlusPlusLanguage::Initialize(); - OCamlLanguage::Initialize(); + MemoryHistoryASan::Initialize(); + AddressSanitizerRuntime::Initialize(); + ThreadSanitizerRuntime::Initialize(); + + SymbolVendorELF::Initialize(); + SymbolFileDWARF::Initialize(); + SymbolFilePDB::Initialize(); + SymbolFileSymtab::Initialize(); + UnwindAssemblyInstEmulation::Initialize(); + UnwindAssembly_x86::Initialize(); + EmulateInstructionARM64::Initialize(); + SymbolFileDWARFDebugMap::Initialize(); + ItaniumABILanguageRuntime::Initialize(); + AppleObjCRuntimeV2::Initialize(); + AppleObjCRuntimeV1::Initialize(); + SystemRuntimeMacOSX::Initialize(); + RenderScriptRuntime::Initialize(); + GoLanguageRuntime::Initialize(); + JavaLanguageRuntime::Initialize(); + + CPlusPlusLanguage::Initialize(); + GoLanguage::Initialize(); + JavaLanguage::Initialize(); + ObjCLanguage::Initialize(); + ObjCPlusPlusLanguage::Initialize(); + OCamlLanguage::Initialize(); #if defined(_MSC_VER) - ProcessWindowsLive::Initialize(); + ProcessWindowsLive::Initialize(); #endif #if defined(__FreeBSD__) - ProcessFreeBSD::Initialize(); + ProcessFreeBSD::Initialize(); #endif #if defined(__APPLE__) - SymbolVendorMacOSX::Initialize(); - ProcessKDP::Initialize(); - ProcessMachCore::Initialize(); - PlatformAppleTVSimulator::Initialize(); - PlatformAppleWatchSimulator::Initialize(); - PlatformRemoteAppleTV::Initialize(); - PlatformRemoteAppleWatch::Initialize(); - DynamicLoaderDarwinKernel::Initialize(); + SymbolVendorMacOSX::Initialize(); + ProcessKDP::Initialize(); + ProcessMachCore::Initialize(); + PlatformAppleTVSimulator::Initialize(); + PlatformAppleWatchSimulator::Initialize(); + PlatformRemoteAppleTV::Initialize(); + PlatformRemoteAppleWatch::Initialize(); + DynamicLoaderDarwinKernel::Initialize(); #endif - // This plugin is valid on any host that talks to a Darwin remote. - // It shouldn't be limited to __APPLE__. - StructuredDataDarwinLog::Initialize(); + // This plugin is valid on any host that talks to a Darwin remote. + // It shouldn't be limited to __APPLE__. + StructuredDataDarwinLog::Initialize(); - //---------------------------------------------------------------------- - // Platform agnostic plugins - //---------------------------------------------------------------------- - platform_gdb_server::PlatformRemoteGDBServer::Initialize(); + //---------------------------------------------------------------------- + // Platform agnostic plugins + //---------------------------------------------------------------------- + platform_gdb_server::PlatformRemoteGDBServer::Initialize(); - process_gdb_remote::ProcessGDBRemote::Initialize(); - DynamicLoaderMacOSXDYLD::Initialize(); - DynamicLoaderMacOS::Initialize(); - DynamicLoaderPOSIXDYLD::Initialize(); - DynamicLoaderStatic::Initialize(); - DynamicLoaderWindowsDYLD::Initialize(); + process_gdb_remote::ProcessGDBRemote::Initialize(); + DynamicLoaderMacOSXDYLD::Initialize(); + DynamicLoaderMacOS::Initialize(); + DynamicLoaderPOSIXDYLD::Initialize(); + DynamicLoaderStatic::Initialize(); + DynamicLoaderWindowsDYLD::Initialize(); - // Scan for any system or user LLDB plug-ins - PluginManager::Initialize(); + // Scan for any system or user LLDB plug-ins + PluginManager::Initialize(); - // The process settings need to know about installed plug-ins, so the Settings must be initialized - // AFTER PluginManager::Initialize is called. + // The process settings need to know about installed plug-ins, so the Settings + // must be initialized + // AFTER PluginManager::Initialize is called. - Debugger::SettingsInitialize(); + Debugger::SettingsInitialize(); } -void SystemInitializerFull::InitializeSWIG() -{ +void SystemInitializerFull::InitializeSWIG() { #if !defined(LLDB_DISABLE_PYTHON) - ScriptInterpreterPython::InitializeInterpreter( - LLDBSwigPyInit, - LLDBSwigPythonBreakpointCallbackFunction, - LLDBSwigPythonWatchpointCallbackFunction, - LLDBSwigPythonCallTypeScript, - LLDBSwigPythonCreateSyntheticProvider, - LLDBSwigPythonCreateCommandObject, - LLDBSwigPython_CalculateNumChildren, - LLDBSwigPython_GetChildAtIndex, - LLDBSwigPython_GetIndexOfChildWithName, - LLDBSWIGPython_CastPyObjectToSBValue, - LLDBSWIGPython_GetValueObjectSPFromSBValue, - LLDBSwigPython_UpdateSynthProviderInstance, - LLDBSwigPython_MightHaveChildrenSynthProviderInstance, - LLDBSwigPython_GetValueSynthProviderInstance, - LLDBSwigPythonCallCommand, - LLDBSwigPythonCallCommandObject, - LLDBSwigPythonCallModuleInit, - LLDBSWIGPythonCreateOSPlugin, - LLDBSWIGPythonRunScriptKeywordProcess, - LLDBSWIGPythonRunScriptKeywordThread, - LLDBSWIGPythonRunScriptKeywordTarget, - LLDBSWIGPythonRunScriptKeywordFrame, - LLDBSWIGPythonRunScriptKeywordValue, - LLDBSWIGPython_GetDynamicSetting, - LLDBSwigPythonCreateScriptedThreadPlan, - LLDBSWIGPythonCallThreadPlan); + ScriptInterpreterPython::InitializeInterpreter( + LLDBSwigPyInit, LLDBSwigPythonBreakpointCallbackFunction, + LLDBSwigPythonWatchpointCallbackFunction, LLDBSwigPythonCallTypeScript, + LLDBSwigPythonCreateSyntheticProvider, LLDBSwigPythonCreateCommandObject, + LLDBSwigPython_CalculateNumChildren, LLDBSwigPython_GetChildAtIndex, + LLDBSwigPython_GetIndexOfChildWithName, + LLDBSWIGPython_CastPyObjectToSBValue, + LLDBSWIGPython_GetValueObjectSPFromSBValue, + LLDBSwigPython_UpdateSynthProviderInstance, + LLDBSwigPython_MightHaveChildrenSynthProviderInstance, + LLDBSwigPython_GetValueSynthProviderInstance, LLDBSwigPythonCallCommand, + LLDBSwigPythonCallCommandObject, LLDBSwigPythonCallModuleInit, + LLDBSWIGPythonCreateOSPlugin, LLDBSWIGPythonRunScriptKeywordProcess, + LLDBSWIGPythonRunScriptKeywordThread, + LLDBSWIGPythonRunScriptKeywordTarget, LLDBSWIGPythonRunScriptKeywordFrame, + LLDBSWIGPythonRunScriptKeywordValue, LLDBSWIGPython_GetDynamicSetting, + LLDBSwigPythonCreateScriptedThreadPlan, LLDBSWIGPythonCallThreadPlan); #endif } -void -SystemInitializerFull::Terminate() -{ - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); - - Debugger::SettingsTerminate(); - - // Terminate and unload and loaded system or user LLDB plug-ins - PluginManager::Terminate(); - - ClangASTContext::Terminate(); - GoASTContext::Terminate(); - JavaASTContext::Terminate(); - OCamlASTContext::Terminate(); - - ABIMacOSX_i386::Terminate(); - ABIMacOSX_arm::Terminate(); - ABIMacOSX_arm64::Terminate(); - ABISysV_arm::Terminate(); - ABISysV_arm64::Terminate(); - ABISysV_hexagon::Terminate(); - ABISysV_i386::Terminate(); - ABISysV_x86_64::Terminate(); - ABISysV_ppc::Terminate(); - ABISysV_ppc64::Terminate(); - ABISysV_mips::Terminate(); - ABISysV_mips64::Terminate(); - ABISysV_s390x::Terminate(); - DisassemblerLLVMC::Terminate(); - - JITLoaderGDB::Terminate(); - ProcessElfCore::Terminate(); +void SystemInitializerFull::Terminate() { + Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + + Debugger::SettingsTerminate(); + + // Terminate and unload and loaded system or user LLDB plug-ins + PluginManager::Terminate(); + + ClangASTContext::Terminate(); + GoASTContext::Terminate(); + JavaASTContext::Terminate(); + OCamlASTContext::Terminate(); + + ABIMacOSX_i386::Terminate(); + ABIMacOSX_arm::Terminate(); + ABIMacOSX_arm64::Terminate(); + ABISysV_arm::Terminate(); + ABISysV_arm64::Terminate(); + ABISysV_hexagon::Terminate(); + ABISysV_i386::Terminate(); + ABISysV_x86_64::Terminate(); + ABISysV_ppc::Terminate(); + ABISysV_ppc64::Terminate(); + ABISysV_mips::Terminate(); + ABISysV_mips64::Terminate(); + ABISysV_s390x::Terminate(); + DisassemblerLLVMC::Terminate(); + + JITLoaderGDB::Terminate(); + ProcessElfCore::Terminate(); #if defined(_MSC_VER) - ProcessWinMiniDump::Terminate(); + ProcessWinMiniDump::Terminate(); #endif - MemoryHistoryASan::Terminate(); - AddressSanitizerRuntime::Terminate(); - ThreadSanitizerRuntime::Terminate(); - SymbolVendorELF::Terminate(); - SymbolFileDWARF::Terminate(); - SymbolFilePDB::Terminate(); - SymbolFileSymtab::Terminate(); - UnwindAssembly_x86::Terminate(); - UnwindAssemblyInstEmulation::Terminate(); - EmulateInstructionARM64::Terminate(); - SymbolFileDWARFDebugMap::Terminate(); - ItaniumABILanguageRuntime::Terminate(); - AppleObjCRuntimeV2::Terminate(); - AppleObjCRuntimeV1::Terminate(); - SystemRuntimeMacOSX::Terminate(); - RenderScriptRuntime::Terminate(); - JavaLanguageRuntime::Terminate(); - - CPlusPlusLanguage::Terminate(); - GoLanguage::Terminate(); - JavaLanguage::Terminate(); - ObjCLanguage::Terminate(); - ObjCPlusPlusLanguage::Terminate(); - OCamlLanguage::Terminate(); + MemoryHistoryASan::Terminate(); + AddressSanitizerRuntime::Terminate(); + ThreadSanitizerRuntime::Terminate(); + SymbolVendorELF::Terminate(); + SymbolFileDWARF::Terminate(); + SymbolFilePDB::Terminate(); + SymbolFileSymtab::Terminate(); + UnwindAssembly_x86::Terminate(); + UnwindAssemblyInstEmulation::Terminate(); + EmulateInstructionARM64::Terminate(); + SymbolFileDWARFDebugMap::Terminate(); + ItaniumABILanguageRuntime::Terminate(); + AppleObjCRuntimeV2::Terminate(); + AppleObjCRuntimeV1::Terminate(); + SystemRuntimeMacOSX::Terminate(); + RenderScriptRuntime::Terminate(); + JavaLanguageRuntime::Terminate(); + + CPlusPlusLanguage::Terminate(); + GoLanguage::Terminate(); + JavaLanguage::Terminate(); + ObjCLanguage::Terminate(); + ObjCPlusPlusLanguage::Terminate(); + OCamlLanguage::Terminate(); #if defined(__APPLE__) - DynamicLoaderDarwinKernel::Terminate(); - ProcessMachCore::Terminate(); - ProcessKDP::Terminate(); - SymbolVendorMacOSX::Terminate(); - PlatformAppleTVSimulator::Terminate(); - PlatformAppleWatchSimulator::Terminate(); - PlatformRemoteAppleTV::Terminate(); - PlatformRemoteAppleWatch::Terminate(); + DynamicLoaderDarwinKernel::Terminate(); + ProcessMachCore::Terminate(); + ProcessKDP::Terminate(); + SymbolVendorMacOSX::Terminate(); + PlatformAppleTVSimulator::Terminate(); + PlatformAppleWatchSimulator::Terminate(); + PlatformRemoteAppleTV::Terminate(); + PlatformRemoteAppleWatch::Terminate(); #endif #if defined(__FreeBSD__) - ProcessFreeBSD::Terminate(); + ProcessFreeBSD::Terminate(); #endif - Debugger::SettingsTerminate(); + Debugger::SettingsTerminate(); - platform_gdb_server::PlatformRemoteGDBServer::Terminate(); - process_gdb_remote::ProcessGDBRemote::Terminate(); - StructuredDataDarwinLog::Terminate(); + platform_gdb_server::PlatformRemoteGDBServer::Terminate(); + process_gdb_remote::ProcessGDBRemote::Terminate(); + StructuredDataDarwinLog::Terminate(); - DynamicLoaderMacOSXDYLD::Terminate(); - DynamicLoaderMacOS::Terminate(); - DynamicLoaderPOSIXDYLD::Terminate(); - DynamicLoaderStatic::Terminate(); - DynamicLoaderWindowsDYLD::Terminate(); + DynamicLoaderMacOSXDYLD::Terminate(); + DynamicLoaderMacOS::Terminate(); + DynamicLoaderPOSIXDYLD::Terminate(); + DynamicLoaderStatic::Terminate(); + DynamicLoaderWindowsDYLD::Terminate(); #ifndef LLDB_DISABLE_PYTHON - OperatingSystemPython::Terminate(); + OperatingSystemPython::Terminate(); #endif - OperatingSystemGo::Terminate(); - - platform_freebsd::PlatformFreeBSD::Terminate(); - platform_linux::PlatformLinux::Terminate(); - platform_netbsd::PlatformNetBSD::Terminate(); - PlatformWindows::Terminate(); - PlatformKalimba::Terminate(); - platform_android::PlatformAndroid::Terminate(); - PlatformMacOSX::Terminate(); - PlatformRemoteiOS::Terminate(); + OperatingSystemGo::Terminate(); + + platform_freebsd::PlatformFreeBSD::Terminate(); + platform_linux::PlatformLinux::Terminate(); + platform_netbsd::PlatformNetBSD::Terminate(); + PlatformWindows::Terminate(); + PlatformKalimba::Terminate(); + platform_android::PlatformAndroid::Terminate(); + PlatformMacOSX::Terminate(); + PlatformRemoteiOS::Terminate(); #if defined(__APPLE__) - PlatformiOSSimulator::Terminate(); - PlatformDarwinKernel::Terminate(); + PlatformiOSSimulator::Terminate(); + PlatformDarwinKernel::Terminate(); #endif - // Now shutdown the common parts, in reverse order. - SystemInitializerCommon::Terminate(); + // Now shutdown the common parts, in reverse order. + SystemInitializerCommon::Terminate(); } diff --git a/lldb/source/Breakpoint/Breakpoint.cpp b/lldb/source/Breakpoint/Breakpoint.cpp index 224f266fe11..78354e28c48 100644 --- a/lldb/source/Breakpoint/Breakpoint.cpp +++ b/lldb/source/Breakpoint/Breakpoint.cpp @@ -13,12 +13,12 @@ #include "llvm/Support/Casting.h" // Project includes -#include "lldb/Core/Address.h" #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointLocationCollection.h" #include "lldb/Breakpoint/BreakpointResolver.h" #include "lldb/Breakpoint/BreakpointResolverFileLine.h" +#include "lldb/Core/Address.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" @@ -36,47 +36,33 @@ using namespace lldb; using namespace lldb_private; using namespace llvm; -const ConstString & -Breakpoint::GetEventIdentifier () -{ - static ConstString g_identifier("event-identifier.breakpoint.changed"); - return g_identifier; +const ConstString &Breakpoint::GetEventIdentifier() { + static ConstString g_identifier("event-identifier.breakpoint.changed"); + return g_identifier; } //---------------------------------------------------------------------- // Breakpoint constructor //---------------------------------------------------------------------- -Breakpoint::Breakpoint(Target &target, - SearchFilterSP &filter_sp, - BreakpointResolverSP &resolver_sp, - bool hardware, - bool resolve_indirect_symbols) : - m_being_created(true), - m_hardware(hardware), - m_target (target), - m_filter_sp (filter_sp), - m_resolver_sp (resolver_sp), - m_options (), - m_locations (*this), - m_resolve_indirect_symbols(resolve_indirect_symbols), - m_hit_count(0) -{ - m_being_created = false; -} - -Breakpoint::Breakpoint (Target &new_target, Breakpoint &source_bp) : - m_being_created(true), - m_hardware(source_bp.m_hardware), - m_target(new_target), - m_name_list (source_bp.m_name_list), - m_options (source_bp.m_options), - m_locations(*this), - m_resolve_indirect_symbols(source_bp.m_resolve_indirect_symbols), - m_hit_count(0) -{ - // Now go through and copy the filter & resolver: - m_resolver_sp = source_bp.m_resolver_sp->CopyForBreakpoint(*this); - m_filter_sp = source_bp.m_filter_sp->CopyForBreakpoint(*this); +Breakpoint::Breakpoint(Target &target, SearchFilterSP &filter_sp, + BreakpointResolverSP &resolver_sp, bool hardware, + bool resolve_indirect_symbols) + : m_being_created(true), m_hardware(hardware), m_target(target), + m_filter_sp(filter_sp), m_resolver_sp(resolver_sp), m_options(), + m_locations(*this), m_resolve_indirect_symbols(resolve_indirect_symbols), + m_hit_count(0) { + m_being_created = false; +} + +Breakpoint::Breakpoint(Target &new_target, Breakpoint &source_bp) + : m_being_created(true), m_hardware(source_bp.m_hardware), + m_target(new_target), m_name_list(source_bp.m_name_list), + m_options(source_bp.m_options), m_locations(*this), + m_resolve_indirect_symbols(source_bp.m_resolve_indirect_symbols), + m_hit_count(0) { + // Now go through and copy the filter & resolver: + m_resolver_sp = source_bp.m_resolver_sp->CopyForBreakpoint(*this); + m_filter_sp = source_bp.m_filter_sp->CopyForBreakpoint(*this); } //---------------------------------------------------------------------- @@ -84,52 +70,36 @@ Breakpoint::Breakpoint (Target &new_target, Breakpoint &source_bp) : //---------------------------------------------------------------------- Breakpoint::~Breakpoint() = default; -const lldb::TargetSP -Breakpoint::GetTargetSP () -{ - return m_target.shared_from_this(); +const lldb::TargetSP Breakpoint::GetTargetSP() { + return m_target.shared_from_this(); } -bool -Breakpoint::IsInternal () const -{ - return LLDB_BREAK_ID_IS_INTERNAL(m_bid); -} +bool Breakpoint::IsInternal() const { return LLDB_BREAK_ID_IS_INTERNAL(m_bid); } -BreakpointLocationSP -Breakpoint::AddLocation (const Address &addr, bool *new_location) -{ - return m_locations.AddLocation (addr, m_resolve_indirect_symbols, new_location); +BreakpointLocationSP Breakpoint::AddLocation(const Address &addr, + bool *new_location) { + return m_locations.AddLocation(addr, m_resolve_indirect_symbols, + new_location); } -BreakpointLocationSP -Breakpoint::FindLocationByAddress (const Address &addr) -{ - return m_locations.FindByAddress(addr); +BreakpointLocationSP Breakpoint::FindLocationByAddress(const Address &addr) { + return m_locations.FindByAddress(addr); } -break_id_t -Breakpoint::FindLocationIDByAddress (const Address &addr) -{ - return m_locations.FindIDByAddress(addr); +break_id_t Breakpoint::FindLocationIDByAddress(const Address &addr) { + return m_locations.FindIDByAddress(addr); } -BreakpointLocationSP -Breakpoint::FindLocationByID (break_id_t bp_loc_id) -{ - return m_locations.FindByID(bp_loc_id); +BreakpointLocationSP Breakpoint::FindLocationByID(break_id_t bp_loc_id) { + return m_locations.FindByID(bp_loc_id); } -BreakpointLocationSP -Breakpoint::GetLocationAtIndex (size_t index) -{ - return m_locations.GetByIndex(index); +BreakpointLocationSP Breakpoint::GetLocationAtIndex(size_t index) { + return m_locations.GetByIndex(index); } -void -Breakpoint::RemoveInvalidLocations (const ArchSpec &arch) -{ - m_locations.RemoveInvalidLocations(arch); +void Breakpoint::RemoveInvalidLocations(const ArchSpec &arch) { + m_locations.RemoveInvalidLocations(arch); } // For each of the overall options we need to decide how they propagate to @@ -140,962 +110,815 @@ Breakpoint::RemoveInvalidLocations (const ArchSpec &arch) // That way you can conveniently turn off a whole breakpoint without messing // up the individual settings. -void -Breakpoint::SetEnabled (bool enable) -{ - if (enable == m_options.IsEnabled()) - return; +void Breakpoint::SetEnabled(bool enable) { + if (enable == m_options.IsEnabled()) + return; - m_options.SetEnabled(enable); - if (enable) - m_locations.ResolveAllBreakpointSites(); - else - m_locations.ClearAllBreakpointSites(); - - SendBreakpointChangedEvent (enable ? eBreakpointEventTypeEnabled : eBreakpointEventTypeDisabled); + m_options.SetEnabled(enable); + if (enable) + m_locations.ResolveAllBreakpointSites(); + else + m_locations.ClearAllBreakpointSites(); + SendBreakpointChangedEvent(enable ? eBreakpointEventTypeEnabled + : eBreakpointEventTypeDisabled); } -bool -Breakpoint::IsEnabled () -{ - return m_options.IsEnabled(); -} +bool Breakpoint::IsEnabled() { return m_options.IsEnabled(); } -void -Breakpoint::SetIgnoreCount (uint32_t n) -{ - if (m_options.GetIgnoreCount() == n) - return; - - m_options.SetIgnoreCount(n); - SendBreakpointChangedEvent (eBreakpointEventTypeIgnoreChanged); -} +void Breakpoint::SetIgnoreCount(uint32_t n) { + if (m_options.GetIgnoreCount() == n) + return; -void -Breakpoint::DecrementIgnoreCount () -{ - uint32_t ignore = m_options.GetIgnoreCount(); - if (ignore != 0) - m_options.SetIgnoreCount(ignore - 1); + m_options.SetIgnoreCount(n); + SendBreakpointChangedEvent(eBreakpointEventTypeIgnoreChanged); } -uint32_t -Breakpoint::GetIgnoreCount () const -{ - return m_options.GetIgnoreCount(); +void Breakpoint::DecrementIgnoreCount() { + uint32_t ignore = m_options.GetIgnoreCount(); + if (ignore != 0) + m_options.SetIgnoreCount(ignore - 1); } -bool -Breakpoint::IgnoreCountShouldStop () -{ - uint32_t ignore = GetIgnoreCount(); - if (ignore != 0) - { - // When we get here we know the location that caused the stop doesn't have an ignore count, - // since by contract we call it first... So we don't have to find & decrement it, we only have - // to decrement our own ignore count. - DecrementIgnoreCount(); - return false; - } - else - return true; +uint32_t Breakpoint::GetIgnoreCount() const { + return m_options.GetIgnoreCount(); } -uint32_t -Breakpoint::GetHitCount () const -{ - return m_hit_count; +bool Breakpoint::IgnoreCountShouldStop() { + uint32_t ignore = GetIgnoreCount(); + if (ignore != 0) { + // When we get here we know the location that caused the stop doesn't have + // an ignore count, + // since by contract we call it first... So we don't have to find & + // decrement it, we only have + // to decrement our own ignore count. + DecrementIgnoreCount(); + return false; + } else + return true; } -bool -Breakpoint::IsOneShot () const -{ - return m_options.IsOneShot(); -} +uint32_t Breakpoint::GetHitCount() const { return m_hit_count; } -void -Breakpoint::SetOneShot (bool one_shot) -{ - m_options.SetOneShot (one_shot); -} +bool Breakpoint::IsOneShot() const { return m_options.IsOneShot(); } -void -Breakpoint::SetThreadID (lldb::tid_t thread_id) -{ - if (m_options.GetThreadSpec()->GetTID() == thread_id) - return; - - m_options.GetThreadSpec()->SetTID(thread_id); - SendBreakpointChangedEvent (eBreakpointEventTypeThreadChanged); +void Breakpoint::SetOneShot(bool one_shot) { m_options.SetOneShot(one_shot); } + +void Breakpoint::SetThreadID(lldb::tid_t thread_id) { + if (m_options.GetThreadSpec()->GetTID() == thread_id) + return; + + m_options.GetThreadSpec()->SetTID(thread_id); + SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged); } -lldb::tid_t -Breakpoint::GetThreadID () const -{ - if (m_options.GetThreadSpecNoCreate() == nullptr) - return LLDB_INVALID_THREAD_ID; - else - return m_options.GetThreadSpecNoCreate()->GetTID(); +lldb::tid_t Breakpoint::GetThreadID() const { + if (m_options.GetThreadSpecNoCreate() == nullptr) + return LLDB_INVALID_THREAD_ID; + else + return m_options.GetThreadSpecNoCreate()->GetTID(); } -void -Breakpoint::SetThreadIndex (uint32_t index) -{ - if (m_options.GetThreadSpec()->GetIndex() == index) - return; - - m_options.GetThreadSpec()->SetIndex(index); - SendBreakpointChangedEvent (eBreakpointEventTypeThreadChanged); +void Breakpoint::SetThreadIndex(uint32_t index) { + if (m_options.GetThreadSpec()->GetIndex() == index) + return; + + m_options.GetThreadSpec()->SetIndex(index); + SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged); } -uint32_t -Breakpoint::GetThreadIndex() const -{ - if (m_options.GetThreadSpecNoCreate() == nullptr) - return 0; - else - return m_options.GetThreadSpecNoCreate()->GetIndex(); +uint32_t Breakpoint::GetThreadIndex() const { + if (m_options.GetThreadSpecNoCreate() == nullptr) + return 0; + else + return m_options.GetThreadSpecNoCreate()->GetIndex(); } -void -Breakpoint::SetThreadName (const char *thread_name) -{ - if (m_options.GetThreadSpec()->GetName() != nullptr - && ::strcmp (m_options.GetThreadSpec()->GetName(), thread_name) == 0) - return; - - m_options.GetThreadSpec()->SetName (thread_name); - SendBreakpointChangedEvent (eBreakpointEventTypeThreadChanged); +void Breakpoint::SetThreadName(const char *thread_name) { + if (m_options.GetThreadSpec()->GetName() != nullptr && + ::strcmp(m_options.GetThreadSpec()->GetName(), thread_name) == 0) + return; + + m_options.GetThreadSpec()->SetName(thread_name); + SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged); } -const char * -Breakpoint::GetThreadName () const -{ - if (m_options.GetThreadSpecNoCreate() == nullptr) - return nullptr; - else - return m_options.GetThreadSpecNoCreate()->GetName(); +const char *Breakpoint::GetThreadName() const { + if (m_options.GetThreadSpecNoCreate() == nullptr) + return nullptr; + else + return m_options.GetThreadSpecNoCreate()->GetName(); } -void -Breakpoint::SetQueueName (const char *queue_name) -{ - if (m_options.GetThreadSpec()->GetQueueName() != nullptr - && ::strcmp (m_options.GetThreadSpec()->GetQueueName(), queue_name) == 0) - return; - - m_options.GetThreadSpec()->SetQueueName (queue_name); - SendBreakpointChangedEvent (eBreakpointEventTypeThreadChanged); +void Breakpoint::SetQueueName(const char *queue_name) { + if (m_options.GetThreadSpec()->GetQueueName() != nullptr && + ::strcmp(m_options.GetThreadSpec()->GetQueueName(), queue_name) == 0) + return; + + m_options.GetThreadSpec()->SetQueueName(queue_name); + SendBreakpointChangedEvent(eBreakpointEventTypeThreadChanged); } -const char * -Breakpoint::GetQueueName () const -{ - if (m_options.GetThreadSpecNoCreate() == nullptr) - return nullptr; - else - return m_options.GetThreadSpecNoCreate()->GetQueueName(); +const char *Breakpoint::GetQueueName() const { + if (m_options.GetThreadSpecNoCreate() == nullptr) + return nullptr; + else + return m_options.GetThreadSpecNoCreate()->GetQueueName(); } -void -Breakpoint::SetCondition (const char *condition) -{ - m_options.SetCondition (condition); - SendBreakpointChangedEvent (eBreakpointEventTypeConditionChanged); +void Breakpoint::SetCondition(const char *condition) { + m_options.SetCondition(condition); + SendBreakpointChangedEvent(eBreakpointEventTypeConditionChanged); } -const char * -Breakpoint::GetConditionText () const -{ - return m_options.GetConditionText(); +const char *Breakpoint::GetConditionText() const { + return m_options.GetConditionText(); } // This function is used when "baton" doesn't need to be freed -void -Breakpoint::SetCallback (BreakpointHitCallback callback, void *baton, bool is_synchronous) -{ - // The default "Baton" class will keep a copy of "baton" and won't free - // or delete it when it goes goes out of scope. - m_options.SetCallback(callback, BatonSP (new Baton(baton)), is_synchronous); - - SendBreakpointChangedEvent (eBreakpointEventTypeCommandChanged); +void Breakpoint::SetCallback(BreakpointHitCallback callback, void *baton, + bool is_synchronous) { + // The default "Baton" class will keep a copy of "baton" and won't free + // or delete it when it goes goes out of scope. + m_options.SetCallback(callback, BatonSP(new Baton(baton)), is_synchronous); + + SendBreakpointChangedEvent(eBreakpointEventTypeCommandChanged); } -// This function is used when a baton needs to be freed and therefore is +// This function is used when a baton needs to be freed and therefore is // contained in a "Baton" subclass. -void -Breakpoint::SetCallback (BreakpointHitCallback callback, const BatonSP &callback_baton_sp, bool is_synchronous) -{ - m_options.SetCallback(callback, callback_baton_sp, is_synchronous); +void Breakpoint::SetCallback(BreakpointHitCallback callback, + const BatonSP &callback_baton_sp, + bool is_synchronous) { + m_options.SetCallback(callback, callback_baton_sp, is_synchronous); } -void -Breakpoint::ClearCallback () -{ - m_options.ClearCallback (); -} +void Breakpoint::ClearCallback() { m_options.ClearCallback(); } -bool -Breakpoint::InvokeCallback (StoppointCallbackContext *context, break_id_t bp_loc_id) -{ - return m_options.InvokeCallback (context, GetID(), bp_loc_id); +bool Breakpoint::InvokeCallback(StoppointCallbackContext *context, + break_id_t bp_loc_id) { + return m_options.InvokeCallback(context, GetID(), bp_loc_id); } -BreakpointOptions * -Breakpoint::GetOptions () -{ - return &m_options; -} +BreakpointOptions *Breakpoint::GetOptions() { return &m_options; } -void -Breakpoint::ResolveBreakpoint () -{ - if (m_resolver_sp) - m_resolver_sp->ResolveBreakpoint(*m_filter_sp); +void Breakpoint::ResolveBreakpoint() { + if (m_resolver_sp) + m_resolver_sp->ResolveBreakpoint(*m_filter_sp); } -void -Breakpoint::ResolveBreakpointInModules (ModuleList &module_list, BreakpointLocationCollection &new_locations) -{ - m_locations.StartRecordingNewLocations(new_locations); - - m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list); +void Breakpoint::ResolveBreakpointInModules( + ModuleList &module_list, BreakpointLocationCollection &new_locations) { + m_locations.StartRecordingNewLocations(new_locations); - m_locations.StopRecordingNewLocations(); + m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list); + + m_locations.StopRecordingNewLocations(); } -void -Breakpoint::ResolveBreakpointInModules (ModuleList &module_list, bool send_event) -{ - if (m_resolver_sp) - { - // If this is not an internal breakpoint, set up to record the new locations, then dispatch - // an event with the new locations. - if (!IsInternal() && send_event) - { - BreakpointEventData *new_locations_event = new BreakpointEventData (eBreakpointEventTypeLocationsAdded, - shared_from_this()); - - ResolveBreakpointInModules (module_list, new_locations_event->GetBreakpointLocationCollection()); - - if (new_locations_event->GetBreakpointLocationCollection().GetSize() != 0) - { - SendBreakpointChangedEvent (new_locations_event); - } - else - delete new_locations_event; - } - else - { - m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list); - } +void Breakpoint::ResolveBreakpointInModules(ModuleList &module_list, + bool send_event) { + if (m_resolver_sp) { + // If this is not an internal breakpoint, set up to record the new + // locations, then dispatch + // an event with the new locations. + if (!IsInternal() && send_event) { + BreakpointEventData *new_locations_event = new BreakpointEventData( + eBreakpointEventTypeLocationsAdded, shared_from_this()); + + ResolveBreakpointInModules( + module_list, new_locations_event->GetBreakpointLocationCollection()); + + if (new_locations_event->GetBreakpointLocationCollection().GetSize() != + 0) { + SendBreakpointChangedEvent(new_locations_event); + } else + delete new_locations_event; + } else { + m_resolver_sp->ResolveBreakpointInModules(*m_filter_sp, module_list); } + } } -void -Breakpoint::ClearAllBreakpointSites () -{ - m_locations.ClearAllBreakpointSites(); +void Breakpoint::ClearAllBreakpointSites() { + m_locations.ClearAllBreakpointSites(); } //---------------------------------------------------------------------- // ModulesChanged: Pass in a list of new modules, and //---------------------------------------------------------------------- -void -Breakpoint::ModulesChanged (ModuleList &module_list, bool load, bool delete_locations) -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - if (log) - log->Printf ("Breakpoint::ModulesChanged: num_modules: %zu load: %i delete_locations: %i\n", - module_list.GetSize(), load, delete_locations); - - std::lock_guard guard(module_list.GetMutex()); - if (load) - { - // The logic for handling new modules is: - // 1) If the filter rejects this module, then skip it. - // 2) Run through the current location list and if there are any locations - // for that module, we mark the module as "seen" and we don't try to re-resolve - // breakpoint locations for that module. - // However, we do add breakpoint sites to these locations if needed. - // 3) If we don't see this module in our breakpoint location list, call ResolveInModules. - - ModuleList new_modules; // We'll stuff the "unseen" modules in this list, and then resolve - // them after the locations pass. Have to do it this way because - // resolving breakpoints will add new locations potentially. - - for (ModuleSP module_sp : module_list.ModulesNoLocking()) - { - bool seen = false; - if (!m_filter_sp->ModulePasses (module_sp)) - continue; - - for (BreakpointLocationSP break_loc_sp : m_locations.BreakpointLocations()) - { - if (!break_loc_sp->IsEnabled()) - continue; - SectionSP section_sp (break_loc_sp->GetAddress().GetSection()); - if (!section_sp || section_sp->GetModule() == module_sp) - { - if (!seen) - seen = true; - - if (!break_loc_sp->ResolveBreakpointSite()) - { - if (log) - log->Printf ("Warning: could not set breakpoint site for breakpoint location %d of breakpoint %d.\n", - break_loc_sp->GetID(), GetID()); - } - } - } - - if (!seen) - new_modules.AppendIfNeeded (module_sp); - } - - if (new_modules.GetSize() > 0) - { - ResolveBreakpointInModules(new_modules); +void Breakpoint::ModulesChanged(ModuleList &module_list, bool load, + bool delete_locations) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + if (log) + log->Printf("Breakpoint::ModulesChanged: num_modules: %zu load: %i " + "delete_locations: %i\n", + module_list.GetSize(), load, delete_locations); + + std::lock_guard guard(module_list.GetMutex()); + if (load) { + // The logic for handling new modules is: + // 1) If the filter rejects this module, then skip it. + // 2) Run through the current location list and if there are any locations + // for that module, we mark the module as "seen" and we don't try to + // re-resolve + // breakpoint locations for that module. + // However, we do add breakpoint sites to these locations if needed. + // 3) If we don't see this module in our breakpoint location list, call + // ResolveInModules. + + ModuleList new_modules; // We'll stuff the "unseen" modules in this list, + // and then resolve + // them after the locations pass. Have to do it this way because + // resolving breakpoints will add new locations potentially. + + for (ModuleSP module_sp : module_list.ModulesNoLocking()) { + bool seen = false; + if (!m_filter_sp->ModulePasses(module_sp)) + continue; + + for (BreakpointLocationSP break_loc_sp : + m_locations.BreakpointLocations()) { + if (!break_loc_sp->IsEnabled()) + continue; + SectionSP section_sp(break_loc_sp->GetAddress().GetSection()); + if (!section_sp || section_sp->GetModule() == module_sp) { + if (!seen) + seen = true; + + if (!break_loc_sp->ResolveBreakpointSite()) { + if (log) + log->Printf("Warning: could not set breakpoint site for " + "breakpoint location %d of breakpoint %d.\n", + break_loc_sp->GetID(), GetID()); + } } + } + + if (!seen) + new_modules.AppendIfNeeded(module_sp); } + + if (new_modules.GetSize() > 0) { + ResolveBreakpointInModules(new_modules); + } + } else { + // Go through the currently set locations and if any have breakpoints in + // the module list, then remove their breakpoint sites, and their locations + // if asked to. + + BreakpointEventData *removed_locations_event; + if (!IsInternal()) + removed_locations_event = new BreakpointEventData( + eBreakpointEventTypeLocationsRemoved, shared_from_this()); else - { - // Go through the currently set locations and if any have breakpoints in - // the module list, then remove their breakpoint sites, and their locations if asked to. - - BreakpointEventData *removed_locations_event; - if (!IsInternal()) - removed_locations_event = new BreakpointEventData (eBreakpointEventTypeLocationsRemoved, - shared_from_this()); - else - removed_locations_event = nullptr; - - size_t num_modules = module_list.GetSize(); - for (size_t i = 0; i < num_modules; i++) - { - ModuleSP module_sp (module_list.GetModuleAtIndexUnlocked (i)); - if (m_filter_sp->ModulePasses (module_sp)) - { - size_t loc_idx = 0; - size_t num_locations = m_locations.GetSize(); - BreakpointLocationCollection locations_to_remove; - for (loc_idx = 0; loc_idx < num_locations; loc_idx++) - { - BreakpointLocationSP break_loc_sp (m_locations.GetByIndex(loc_idx)); - SectionSP section_sp (break_loc_sp->GetAddress().GetSection()); - if (section_sp && section_sp->GetModule() == module_sp) - { - // Remove this breakpoint since the shared library is - // unloaded, but keep the breakpoint location around - // so we always get complete hit count and breakpoint - // lifetime info - break_loc_sp->ClearBreakpointSite(); - if (removed_locations_event) - { - removed_locations_event->GetBreakpointLocationCollection().Add(break_loc_sp); - } - if (delete_locations) - locations_to_remove.Add (break_loc_sp); - } - } - - if (delete_locations) - { - size_t num_locations_to_remove = locations_to_remove.GetSize(); - for (loc_idx = 0; loc_idx < num_locations_to_remove; loc_idx++) - m_locations.RemoveLocation (locations_to_remove.GetByIndex(loc_idx)); - } + removed_locations_event = nullptr; + + size_t num_modules = module_list.GetSize(); + for (size_t i = 0; i < num_modules; i++) { + ModuleSP module_sp(module_list.GetModuleAtIndexUnlocked(i)); + if (m_filter_sp->ModulePasses(module_sp)) { + size_t loc_idx = 0; + size_t num_locations = m_locations.GetSize(); + BreakpointLocationCollection locations_to_remove; + for (loc_idx = 0; loc_idx < num_locations; loc_idx++) { + BreakpointLocationSP break_loc_sp(m_locations.GetByIndex(loc_idx)); + SectionSP section_sp(break_loc_sp->GetAddress().GetSection()); + if (section_sp && section_sp->GetModule() == module_sp) { + // Remove this breakpoint since the shared library is + // unloaded, but keep the breakpoint location around + // so we always get complete hit count and breakpoint + // lifetime info + break_loc_sp->ClearBreakpointSite(); + if (removed_locations_event) { + removed_locations_event->GetBreakpointLocationCollection().Add( + break_loc_sp); } + if (delete_locations) + locations_to_remove.Add(break_loc_sp); + } } - SendBreakpointChangedEvent (removed_locations_event); - } -} -namespace -{ -static bool -SymbolContextsMightBeEquivalent(SymbolContext &old_sc, SymbolContext &new_sc) -{ - bool equivalent_scs = false; - - if (old_sc.module_sp.get() == new_sc.module_sp.get()) - { - // If these come from the same module, we can directly compare the pointers: - if (old_sc.comp_unit && new_sc.comp_unit - && (old_sc.comp_unit == new_sc.comp_unit)) - { - if (old_sc.function && new_sc.function - && (old_sc.function == new_sc.function)) - { - equivalent_scs = true; - } - } - else if (old_sc.symbol && new_sc.symbol - && (old_sc.symbol == new_sc.symbol)) - { - equivalent_scs = true; + if (delete_locations) { + size_t num_locations_to_remove = locations_to_remove.GetSize(); + for (loc_idx = 0; loc_idx < num_locations_to_remove; loc_idx++) + m_locations.RemoveLocation(locations_to_remove.GetByIndex(loc_idx)); } + } } - else - { - // Otherwise we will compare by name... - if (old_sc.comp_unit && new_sc.comp_unit) - { - if (FileSpec::Equal(*old_sc.comp_unit, *new_sc.comp_unit, true)) - { - // Now check the functions: - if (old_sc.function && new_sc.function - && (old_sc.function->GetName() == new_sc.function->GetName())) - { - equivalent_scs = true; - } - } - } - else if (old_sc.symbol && new_sc.symbol) - { - if (Mangled::Compare(old_sc.symbol->GetMangled(), new_sc.symbol->GetMangled()) == 0) - { - equivalent_scs = true; - } + SendBreakpointChangedEvent(removed_locations_event); + } +} + +namespace { +static bool SymbolContextsMightBeEquivalent(SymbolContext &old_sc, + SymbolContext &new_sc) { + bool equivalent_scs = false; + + if (old_sc.module_sp.get() == new_sc.module_sp.get()) { + // If these come from the same module, we can directly compare the pointers: + if (old_sc.comp_unit && new_sc.comp_unit && + (old_sc.comp_unit == new_sc.comp_unit)) { + if (old_sc.function && new_sc.function && + (old_sc.function == new_sc.function)) { + equivalent_scs = true; + } + } else if (old_sc.symbol && new_sc.symbol && + (old_sc.symbol == new_sc.symbol)) { + equivalent_scs = true; + } + } else { + // Otherwise we will compare by name... + if (old_sc.comp_unit && new_sc.comp_unit) { + if (FileSpec::Equal(*old_sc.comp_unit, *new_sc.comp_unit, true)) { + // Now check the functions: + if (old_sc.function && new_sc.function && + (old_sc.function->GetName() == new_sc.function->GetName())) { + equivalent_scs = true; } + } + } else if (old_sc.symbol && new_sc.symbol) { + if (Mangled::Compare(old_sc.symbol->GetMangled(), + new_sc.symbol->GetMangled()) == 0) { + equivalent_scs = true; + } } - return equivalent_scs; + } + return equivalent_scs; } } // anonymous namespace -void -Breakpoint::ModuleReplaced (ModuleSP old_module_sp, ModuleSP new_module_sp) -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - if (log) - log->Printf ("Breakpoint::ModulesReplaced for %s\n", - old_module_sp->GetSpecificationDescription().c_str()); - // First find all the locations that are in the old module - - BreakpointLocationCollection old_break_locs; - for (BreakpointLocationSP break_loc_sp : m_locations.BreakpointLocations()) - { - SectionSP section_sp = break_loc_sp->GetAddress().GetSection(); - if (section_sp && section_sp->GetModule() == old_module_sp) - { - old_break_locs.Add(break_loc_sp); - } - } - - size_t num_old_locations = old_break_locs.GetSize(); - - if (num_old_locations == 0) - { - // There were no locations in the old module, so we just need to check if there were any in the new module. - ModuleList temp_list; - temp_list.Append (new_module_sp); - ResolveBreakpointInModules(temp_list); +void Breakpoint::ModuleReplaced(ModuleSP old_module_sp, + ModuleSP new_module_sp) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + if (log) + log->Printf("Breakpoint::ModulesReplaced for %s\n", + old_module_sp->GetSpecificationDescription().c_str()); + // First find all the locations that are in the old module + + BreakpointLocationCollection old_break_locs; + for (BreakpointLocationSP break_loc_sp : m_locations.BreakpointLocations()) { + SectionSP section_sp = break_loc_sp->GetAddress().GetSection(); + if (section_sp && section_sp->GetModule() == old_module_sp) { + old_break_locs.Add(break_loc_sp); } - else - { - // First search the new module for locations. - // Then compare this with the old list, copy over locations that "look the same" - // Then delete the old locations. - // Finally remember to post the creation event. - // - // Two locations are the same if they have the same comp unit & function (by name) and there are the same number - // of locations in the old function as in the new one. - - ModuleList temp_list; - temp_list.Append (new_module_sp); - BreakpointLocationCollection new_break_locs; - ResolveBreakpointInModules(temp_list, new_break_locs); - BreakpointLocationCollection locations_to_remove; - BreakpointLocationCollection locations_to_announce; - - size_t num_new_locations = new_break_locs.GetSize(); - - if (num_new_locations > 0) - { - // Break out the case of one location -> one location since that's the most common one, and there's no need - // to build up the structures needed for the merge in that case. - if (num_new_locations == 1 && num_old_locations == 1) - { - bool equivalent_locations = false; - SymbolContext old_sc, new_sc; - // The only way the old and new location can be equivalent is if they have the same amount of information: - BreakpointLocationSP old_loc_sp = old_break_locs.GetByIndex(0); - BreakpointLocationSP new_loc_sp = new_break_locs.GetByIndex(0); - - if (old_loc_sp->GetAddress().CalculateSymbolContext(&old_sc) - == new_loc_sp->GetAddress().CalculateSymbolContext(&new_sc)) - { - equivalent_locations = SymbolContextsMightBeEquivalent(old_sc, new_sc); - } - - if (equivalent_locations) - { - m_locations.SwapLocation (old_loc_sp, new_loc_sp); - } - else - { - locations_to_remove.Add(old_loc_sp); - locations_to_announce.Add(new_loc_sp); - } - } - else - { - //We don't want to have to keep computing the SymbolContexts for these addresses over and over, - // so lets get them up front: - - typedef std::map IDToSCMap; - IDToSCMap old_sc_map; - for (size_t idx = 0; idx < num_old_locations; idx++) - { - SymbolContext sc; - BreakpointLocationSP bp_loc_sp = old_break_locs.GetByIndex(idx); - lldb::break_id_t loc_id = bp_loc_sp->GetID(); - bp_loc_sp->GetAddress().CalculateSymbolContext(&old_sc_map[loc_id]); - } - - std::map new_sc_map; - for (size_t idx = 0; idx < num_new_locations; idx++) - { - SymbolContext sc; - BreakpointLocationSP bp_loc_sp = new_break_locs.GetByIndex(idx); - lldb::break_id_t loc_id = bp_loc_sp->GetID(); - bp_loc_sp->GetAddress().CalculateSymbolContext(&new_sc_map[loc_id]); - } - // Take an element from the old Symbol Contexts - while (old_sc_map.size() > 0) - { - lldb::break_id_t old_id = old_sc_map.begin()->first; - SymbolContext &old_sc = old_sc_map.begin()->second; - - // Count the number of entries equivalent to this SC for the old list: - std::vector old_id_vec; - old_id_vec.push_back(old_id); - - IDToSCMap::iterator tmp_iter; - for (tmp_iter = ++old_sc_map.begin(); tmp_iter != old_sc_map.end(); tmp_iter++) - { - if (SymbolContextsMightBeEquivalent (old_sc, tmp_iter->second)) - old_id_vec.push_back (tmp_iter->first); - } - - // Now find all the equivalent locations in the new list. - std::vector new_id_vec; - for (tmp_iter = new_sc_map.begin(); tmp_iter != new_sc_map.end(); tmp_iter++) - { - if (SymbolContextsMightBeEquivalent (old_sc, tmp_iter->second)) - new_id_vec.push_back(tmp_iter->first); - } - - // Alright, if we have the same number of potentially equivalent locations in the old - // and new modules, we'll just map them one to one in ascending ID order (assuming the - // resolver's order would match the equivalent ones. - // Otherwise, we'll dump all the old ones, and just take the new ones, erasing the elements - // from both maps as we go. - - if (old_id_vec.size() == new_id_vec.size()) - { - sort(old_id_vec.begin(), old_id_vec.end()); - sort(new_id_vec.begin(), new_id_vec.end()); - size_t num_elements = old_id_vec.size(); - for (size_t idx = 0; idx < num_elements; idx++) - { - BreakpointLocationSP old_loc_sp = old_break_locs.FindByIDPair(GetID(), old_id_vec[idx]); - BreakpointLocationSP new_loc_sp = new_break_locs.FindByIDPair(GetID(), new_id_vec[idx]); - m_locations.SwapLocation(old_loc_sp, new_loc_sp); - old_sc_map.erase(old_id_vec[idx]); - new_sc_map.erase(new_id_vec[idx]); - } - } - else - { - for (lldb::break_id_t old_id : old_id_vec) - { - locations_to_remove.Add(old_break_locs.FindByIDPair(GetID(), old_id)); - old_sc_map.erase(old_id); - } - for (lldb::break_id_t new_id : new_id_vec) - { - locations_to_announce.Add(new_break_locs.FindByIDPair(GetID(), new_id)); - new_sc_map.erase(new_id); - } - } - } - } + } + + size_t num_old_locations = old_break_locs.GetSize(); + + if (num_old_locations == 0) { + // There were no locations in the old module, so we just need to check if + // there were any in the new module. + ModuleList temp_list; + temp_list.Append(new_module_sp); + ResolveBreakpointInModules(temp_list); + } else { + // First search the new module for locations. + // Then compare this with the old list, copy over locations that "look the + // same" + // Then delete the old locations. + // Finally remember to post the creation event. + // + // Two locations are the same if they have the same comp unit & function (by + // name) and there are the same number + // of locations in the old function as in the new one. + + ModuleList temp_list; + temp_list.Append(new_module_sp); + BreakpointLocationCollection new_break_locs; + ResolveBreakpointInModules(temp_list, new_break_locs); + BreakpointLocationCollection locations_to_remove; + BreakpointLocationCollection locations_to_announce; + + size_t num_new_locations = new_break_locs.GetSize(); + + if (num_new_locations > 0) { + // Break out the case of one location -> one location since that's the + // most common one, and there's no need + // to build up the structures needed for the merge in that case. + if (num_new_locations == 1 && num_old_locations == 1) { + bool equivalent_locations = false; + SymbolContext old_sc, new_sc; + // The only way the old and new location can be equivalent is if they + // have the same amount of information: + BreakpointLocationSP old_loc_sp = old_break_locs.GetByIndex(0); + BreakpointLocationSP new_loc_sp = new_break_locs.GetByIndex(0); + + if (old_loc_sp->GetAddress().CalculateSymbolContext(&old_sc) == + new_loc_sp->GetAddress().CalculateSymbolContext(&new_sc)) { + equivalent_locations = + SymbolContextsMightBeEquivalent(old_sc, new_sc); } - - // Now remove the remaining old locations, and cons up a removed locations event. - // Note, we don't put the new locations that were swapped with an old location on the locations_to_remove - // list, so we don't need to worry about telling the world about removing a location we didn't tell them - // about adding. - - BreakpointEventData *locations_event; - if (!IsInternal()) - locations_event = new BreakpointEventData (eBreakpointEventTypeLocationsRemoved, - shared_from_this()); - else - locations_event = nullptr; - - for (BreakpointLocationSP loc_sp : locations_to_remove.BreakpointLocations()) - { - m_locations.RemoveLocation(loc_sp); - if (locations_event) - locations_event->GetBreakpointLocationCollection().Add(loc_sp); + + if (equivalent_locations) { + m_locations.SwapLocation(old_loc_sp, new_loc_sp); + } else { + locations_to_remove.Add(old_loc_sp); + locations_to_announce.Add(new_loc_sp); + } + } else { + // We don't want to have to keep computing the SymbolContexts for these + // addresses over and over, + // so lets get them up front: + + typedef std::map IDToSCMap; + IDToSCMap old_sc_map; + for (size_t idx = 0; idx < num_old_locations; idx++) { + SymbolContext sc; + BreakpointLocationSP bp_loc_sp = old_break_locs.GetByIndex(idx); + lldb::break_id_t loc_id = bp_loc_sp->GetID(); + bp_loc_sp->GetAddress().CalculateSymbolContext(&old_sc_map[loc_id]); + } + + std::map new_sc_map; + for (size_t idx = 0; idx < num_new_locations; idx++) { + SymbolContext sc; + BreakpointLocationSP bp_loc_sp = new_break_locs.GetByIndex(idx); + lldb::break_id_t loc_id = bp_loc_sp->GetID(); + bp_loc_sp->GetAddress().CalculateSymbolContext(&new_sc_map[loc_id]); } - SendBreakpointChangedEvent (locations_event); - - // And announce the new ones. - - if (!IsInternal()) - { - locations_event = new BreakpointEventData (eBreakpointEventTypeLocationsAdded, - shared_from_this()); - for (BreakpointLocationSP loc_sp : locations_to_announce.BreakpointLocations()) - locations_event->GetBreakpointLocationCollection().Add(loc_sp); - - SendBreakpointChangedEvent (locations_event); + // Take an element from the old Symbol Contexts + while (old_sc_map.size() > 0) { + lldb::break_id_t old_id = old_sc_map.begin()->first; + SymbolContext &old_sc = old_sc_map.begin()->second; + + // Count the number of entries equivalent to this SC for the old list: + std::vector old_id_vec; + old_id_vec.push_back(old_id); + + IDToSCMap::iterator tmp_iter; + for (tmp_iter = ++old_sc_map.begin(); tmp_iter != old_sc_map.end(); + tmp_iter++) { + if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second)) + old_id_vec.push_back(tmp_iter->first); + } + + // Now find all the equivalent locations in the new list. + std::vector new_id_vec; + for (tmp_iter = new_sc_map.begin(); tmp_iter != new_sc_map.end(); + tmp_iter++) { + if (SymbolContextsMightBeEquivalent(old_sc, tmp_iter->second)) + new_id_vec.push_back(tmp_iter->first); + } + + // Alright, if we have the same number of potentially equivalent + // locations in the old + // and new modules, we'll just map them one to one in ascending ID + // order (assuming the + // resolver's order would match the equivalent ones. + // Otherwise, we'll dump all the old ones, and just take the new ones, + // erasing the elements + // from both maps as we go. + + if (old_id_vec.size() == new_id_vec.size()) { + sort(old_id_vec.begin(), old_id_vec.end()); + sort(new_id_vec.begin(), new_id_vec.end()); + size_t num_elements = old_id_vec.size(); + for (size_t idx = 0; idx < num_elements; idx++) { + BreakpointLocationSP old_loc_sp = + old_break_locs.FindByIDPair(GetID(), old_id_vec[idx]); + BreakpointLocationSP new_loc_sp = + new_break_locs.FindByIDPair(GetID(), new_id_vec[idx]); + m_locations.SwapLocation(old_loc_sp, new_loc_sp); + old_sc_map.erase(old_id_vec[idx]); + new_sc_map.erase(new_id_vec[idx]); + } + } else { + for (lldb::break_id_t old_id : old_id_vec) { + locations_to_remove.Add( + old_break_locs.FindByIDPair(GetID(), old_id)); + old_sc_map.erase(old_id); + } + for (lldb::break_id_t new_id : new_id_vec) { + locations_to_announce.Add( + new_break_locs.FindByIDPair(GetID(), new_id)); + new_sc_map.erase(new_id); + } + } } - m_locations.Compact(); + } } -} -void -Breakpoint::Dump (Stream *) -{ -} + // Now remove the remaining old locations, and cons up a removed locations + // event. + // Note, we don't put the new locations that were swapped with an old + // location on the locations_to_remove + // list, so we don't need to worry about telling the world about removing a + // location we didn't tell them + // about adding. + + BreakpointEventData *locations_event; + if (!IsInternal()) + locations_event = new BreakpointEventData( + eBreakpointEventTypeLocationsRemoved, shared_from_this()); + else + locations_event = nullptr; -size_t -Breakpoint::GetNumResolvedLocations() const -{ - // Return the number of breakpoints that are actually resolved and set - // down in the inferior process. - return m_locations.GetNumResolvedLocations(); -} + for (BreakpointLocationSP loc_sp : + locations_to_remove.BreakpointLocations()) { + m_locations.RemoveLocation(loc_sp); + if (locations_event) + locations_event->GetBreakpointLocationCollection().Add(loc_sp); + } + SendBreakpointChangedEvent(locations_event); -size_t -Breakpoint::GetNumLocations() const -{ - return m_locations.GetSize(); -} + // And announce the new ones. + + if (!IsInternal()) { + locations_event = new BreakpointEventData( + eBreakpointEventTypeLocationsAdded, shared_from_this()); + for (BreakpointLocationSP loc_sp : + locations_to_announce.BreakpointLocations()) + locations_event->GetBreakpointLocationCollection().Add(loc_sp); -bool -Breakpoint::AddName (const char *new_name, Error &error) -{ - if (!new_name) - return false; - if (!BreakpointID::StringIsBreakpointName(new_name, error)) - { - error.SetErrorStringWithFormat("input name \"%s\" not a breakpoint name.", new_name); - return false; + SendBreakpointChangedEvent(locations_event); } - if (!error.Success()) - return false; + m_locations.Compact(); + } +} - m_name_list.insert(new_name); - return true; +void Breakpoint::Dump(Stream *) {} + +size_t Breakpoint::GetNumResolvedLocations() const { + // Return the number of breakpoints that are actually resolved and set + // down in the inferior process. + return m_locations.GetNumResolvedLocations(); } -void -Breakpoint::GetDescription (Stream *s, lldb::DescriptionLevel level, bool show_locations) -{ - assert (s != nullptr); - - if (!m_kind_description.empty()) - { - if (level == eDescriptionLevelBrief) - { - s->PutCString (GetBreakpointKind()); - return; - } - else - s->Printf("Kind: %s\n", GetBreakpointKind ()); - } - - const size_t num_locations = GetNumLocations (); - const size_t num_resolved_locations = GetNumResolvedLocations (); - - // They just made the breakpoint, they don't need to be told HOW they made it... - // Also, we'll print the breakpoint number differently depending on whether there is 1 or more locations. - if (level != eDescriptionLevelInitial) - { - s->Printf("%i: ", GetID()); - GetResolverDescription (s); - GetFilterDescription (s); - } - - switch (level) - { - case lldb::eDescriptionLevelBrief: - case lldb::eDescriptionLevelFull: - if (num_locations > 0) - { - s->Printf(", locations = %" PRIu64, (uint64_t)num_locations); - if (num_resolved_locations > 0) - s->Printf(", resolved = %" PRIu64 ", hit count = %d", (uint64_t)num_resolved_locations, GetHitCount()); - } - else - { - // Don't print the pending notification for exception resolvers since we don't generally - // know how to set them until the target is run. - if (m_resolver_sp->getResolverID() != BreakpointResolver::ExceptionResolver) - s->Printf(", locations = 0 (pending)"); - } +size_t Breakpoint::GetNumLocations() const { return m_locations.GetSize(); } - GetOptions()->GetDescription(s, level); - - if (m_precondition_sp) - m_precondition_sp->GetDescription(*s, level); - - if (level == lldb::eDescriptionLevelFull) - { - if (!m_name_list.empty()) - { - s->EOL(); - s->Indent(); - s->Printf ("Names:"); - s->EOL(); - s->IndentMore(); - for (std::string name : m_name_list) - { - s->Indent(); - s->Printf("%s\n", name.c_str()); - } - s->IndentLess(); - } - s->IndentLess(); - s->EOL(); - } - break; - - case lldb::eDescriptionLevelInitial: - s->Printf ("Breakpoint %i: ", GetID()); - if (num_locations == 0) - { - s->Printf ("no locations (pending)."); - } - else if (num_locations == 1 && !show_locations) - { - // There is only one location, so we'll just print that location information. - GetLocationAtIndex(0)->GetDescription(s, level); - } - else - { - s->Printf ("%" PRIu64 " locations.", static_cast(num_locations)); - } - s->EOL(); - break; - - case lldb::eDescriptionLevelVerbose: - // Verbose mode does a debug dump of the breakpoint - Dump (s); - s->EOL (); - //s->Indent(); - GetOptions()->GetDescription(s, level); - break; - - default: - break; +bool Breakpoint::AddName(const char *new_name, Error &error) { + if (!new_name) + return false; + if (!BreakpointID::StringIsBreakpointName(new_name, error)) { + error.SetErrorStringWithFormat("input name \"%s\" not a breakpoint name.", + new_name); + return false; + } + if (!error.Success()) + return false; + + m_name_list.insert(new_name); + return true; +} + +void Breakpoint::GetDescription(Stream *s, lldb::DescriptionLevel level, + bool show_locations) { + assert(s != nullptr); + + if (!m_kind_description.empty()) { + if (level == eDescriptionLevelBrief) { + s->PutCString(GetBreakpointKind()); + return; + } else + s->Printf("Kind: %s\n", GetBreakpointKind()); + } + + const size_t num_locations = GetNumLocations(); + const size_t num_resolved_locations = GetNumResolvedLocations(); + + // They just made the breakpoint, they don't need to be told HOW they made + // it... + // Also, we'll print the breakpoint number differently depending on whether + // there is 1 or more locations. + if (level != eDescriptionLevelInitial) { + s->Printf("%i: ", GetID()); + GetResolverDescription(s); + GetFilterDescription(s); + } + + switch (level) { + case lldb::eDescriptionLevelBrief: + case lldb::eDescriptionLevelFull: + if (num_locations > 0) { + s->Printf(", locations = %" PRIu64, (uint64_t)num_locations); + if (num_resolved_locations > 0) + s->Printf(", resolved = %" PRIu64 ", hit count = %d", + (uint64_t)num_resolved_locations, GetHitCount()); + } else { + // Don't print the pending notification for exception resolvers since we + // don't generally + // know how to set them until the target is run. + if (m_resolver_sp->getResolverID() != + BreakpointResolver::ExceptionResolver) + s->Printf(", locations = 0 (pending)"); } - // The brief description is just the location name (1.2 or whatever). That's pointless to - // show in the breakpoint's description, so suppress it. - if (show_locations && level != lldb::eDescriptionLevelBrief) - { + GetOptions()->GetDescription(s, level); + + if (m_precondition_sp) + m_precondition_sp->GetDescription(*s, level); + + if (level == lldb::eDescriptionLevelFull) { + if (!m_name_list.empty()) { + s->EOL(); + s->Indent(); + s->Printf("Names:"); + s->EOL(); s->IndentMore(); - for (size_t i = 0; i < num_locations; ++i) - { - BreakpointLocation *loc = GetLocationAtIndex(i).get(); - loc->GetDescription(s, level); - s->EOL(); + for (std::string name : m_name_list) { + s->Indent(); + s->Printf("%s\n", name.c_str()); } s->IndentLess(); + } + s->IndentLess(); + s->EOL(); + } + break; + + case lldb::eDescriptionLevelInitial: + s->Printf("Breakpoint %i: ", GetID()); + if (num_locations == 0) { + s->Printf("no locations (pending)."); + } else if (num_locations == 1 && !show_locations) { + // There is only one location, so we'll just print that location + // information. + GetLocationAtIndex(0)->GetDescription(s, level); + } else { + s->Printf("%" PRIu64 " locations.", static_cast(num_locations)); + } + s->EOL(); + break; + + case lldb::eDescriptionLevelVerbose: + // Verbose mode does a debug dump of the breakpoint + Dump(s); + s->EOL(); + // s->Indent(); + GetOptions()->GetDescription(s, level); + break; + + default: + break; + } + + // The brief description is just the location name (1.2 or whatever). That's + // pointless to + // show in the breakpoint's description, so suppress it. + if (show_locations && level != lldb::eDescriptionLevelBrief) { + s->IndentMore(); + for (size_t i = 0; i < num_locations; ++i) { + BreakpointLocation *loc = GetLocationAtIndex(i).get(); + loc->GetDescription(s, level); + s->EOL(); } + s->IndentLess(); + } +} + +void Breakpoint::GetResolverDescription(Stream *s) { + if (m_resolver_sp) + m_resolver_sp->GetDescription(s); +} + +bool Breakpoint::GetMatchingFileLine(const ConstString &filename, + uint32_t line_number, + BreakpointLocationCollection &loc_coll) { + // TODO: To be correct, this method needs to fill the breakpoint location + // collection + // with the location IDs which match the filename and line_number. + // + + if (m_resolver_sp) { + BreakpointResolverFileLine *resolverFileLine = + dyn_cast(m_resolver_sp.get()); + if (resolverFileLine && + resolverFileLine->m_file_spec.GetFilename() == filename && + resolverFileLine->m_line_number == line_number) { + return true; + } + } + return false; } -void -Breakpoint::GetResolverDescription (Stream *s) -{ - if (m_resolver_sp) - m_resolver_sp->GetDescription (s); +void Breakpoint::GetFilterDescription(Stream *s) { + m_filter_sp->GetDescription(s); } -bool -Breakpoint::GetMatchingFileLine (const ConstString &filename, uint32_t line_number, BreakpointLocationCollection &loc_coll) -{ - // TODO: To be correct, this method needs to fill the breakpoint location collection - // with the location IDs which match the filename and line_number. - // +bool Breakpoint::EvaluatePrecondition(StoppointCallbackContext &context) { + if (!m_precondition_sp) + return true; - if (m_resolver_sp) - { - BreakpointResolverFileLine *resolverFileLine = dyn_cast(m_resolver_sp.get()); - if (resolverFileLine && - resolverFileLine->m_file_spec.GetFilename() == filename && - resolverFileLine->m_line_number == line_number) - { - return true; - } - } - return false; + return m_precondition_sp->EvaluatePrecondition(context); } -void -Breakpoint::GetFilterDescription (Stream *s) -{ - m_filter_sp->GetDescription (s); +bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition( + StoppointCallbackContext &context) { + return true; } -bool -Breakpoint::EvaluatePrecondition (StoppointCallbackContext &context) -{ - if (!m_precondition_sp) - return true; +void Breakpoint::BreakpointPrecondition::GetDescription( + Stream &stream, lldb::DescriptionLevel level) {} - return m_precondition_sp->EvaluatePrecondition(context); +Error Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) { + Error error; + error.SetErrorString("Base breakpoint precondition has no options."); + return error; } -bool -Breakpoint::BreakpointPrecondition::EvaluatePrecondition(StoppointCallbackContext &context) -{ - return true; -} +void Breakpoint::SendBreakpointChangedEvent( + lldb::BreakpointEventType eventKind) { + if (!m_being_created && !IsInternal() && + GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) { + BreakpointEventData *data = + new Breakpoint::BreakpointEventData(eventKind, shared_from_this()); -void -Breakpoint::BreakpointPrecondition::GetDescription(Stream &stream, lldb::DescriptionLevel level) -{ + GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data); + } } -Error -Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) -{ - Error error; - error.SetErrorString("Base breakpoint precondition has no options."); - return error; -} +void Breakpoint::SendBreakpointChangedEvent(BreakpointEventData *data) { + if (data == nullptr) + return; -void -Breakpoint::SendBreakpointChangedEvent (lldb::BreakpointEventType eventKind) -{ - if (!m_being_created - && !IsInternal() - && GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - { - BreakpointEventData *data = new Breakpoint::BreakpointEventData (eventKind, shared_from_this()); - - GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, data); - } + if (!m_being_created && !IsInternal() && + GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) + GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, data); + else + delete data; } -void -Breakpoint::SendBreakpointChangedEvent (BreakpointEventData *data) -{ - if (data == nullptr) - return; - - if (!m_being_created - && !IsInternal() - && GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, data); - else - delete data; -} - -Breakpoint::BreakpointEventData::BreakpointEventData (BreakpointEventType sub_type, - const BreakpointSP &new_breakpoint_sp) : - EventData (), - m_breakpoint_event (sub_type), - m_new_breakpoint_sp (new_breakpoint_sp) -{ -} +Breakpoint::BreakpointEventData::BreakpointEventData( + BreakpointEventType sub_type, const BreakpointSP &new_breakpoint_sp) + : EventData(), m_breakpoint_event(sub_type), + m_new_breakpoint_sp(new_breakpoint_sp) {} Breakpoint::BreakpointEventData::~BreakpointEventData() = default; -const ConstString & -Breakpoint::BreakpointEventData::GetFlavorString () -{ - static ConstString g_flavor ("Breakpoint::BreakpointEventData"); - return g_flavor; +const ConstString &Breakpoint::BreakpointEventData::GetFlavorString() { + static ConstString g_flavor("Breakpoint::BreakpointEventData"); + return g_flavor; } -const ConstString & -Breakpoint::BreakpointEventData::GetFlavor () const -{ - return BreakpointEventData::GetFlavorString (); +const ConstString &Breakpoint::BreakpointEventData::GetFlavor() const { + return BreakpointEventData::GetFlavorString(); } -BreakpointSP & -Breakpoint::BreakpointEventData::GetBreakpoint () -{ - return m_new_breakpoint_sp; +BreakpointSP &Breakpoint::BreakpointEventData::GetBreakpoint() { + return m_new_breakpoint_sp; } BreakpointEventType -Breakpoint::BreakpointEventData::GetBreakpointEventType () const -{ - return m_breakpoint_event; +Breakpoint::BreakpointEventData::GetBreakpointEventType() const { + return m_breakpoint_event; } -void -Breakpoint::BreakpointEventData::Dump (Stream *s) const -{ -} +void Breakpoint::BreakpointEventData::Dump(Stream *s) const {} const Breakpoint::BreakpointEventData * -Breakpoint::BreakpointEventData::GetEventDataFromEvent (const Event *event) -{ - if (event) - { - const EventData *event_data = event->GetData(); - if (event_data && event_data->GetFlavor() == BreakpointEventData::GetFlavorString()) - return static_cast (event->GetData()); - } - return nullptr; +Breakpoint::BreakpointEventData::GetEventDataFromEvent(const Event *event) { + if (event) { + const EventData *event_data = event->GetData(); + if (event_data && + event_data->GetFlavor() == BreakpointEventData::GetFlavorString()) + return static_cast(event->GetData()); + } + return nullptr; } BreakpointEventType -Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (const EventSP &event_sp) -{ - const BreakpointEventData *data = GetEventDataFromEvent (event_sp.get()); +Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( + const EventSP &event_sp) { + const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get()); - if (data == nullptr) - return eBreakpointEventTypeInvalidType; - else - return data->GetBreakpointEventType(); + if (data == nullptr) + return eBreakpointEventTypeInvalidType; + else + return data->GetBreakpointEventType(); } -BreakpointSP -Breakpoint::BreakpointEventData::GetBreakpointFromEvent (const EventSP &event_sp) -{ - BreakpointSP bp_sp; +BreakpointSP Breakpoint::BreakpointEventData::GetBreakpointFromEvent( + const EventSP &event_sp) { + BreakpointSP bp_sp; - const BreakpointEventData *data = GetEventDataFromEvent (event_sp.get()); - if (data) - bp_sp = data->m_new_breakpoint_sp; + const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get()); + if (data) + bp_sp = data->m_new_breakpoint_sp; - return bp_sp; + return bp_sp; } -size_t -Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent (const EventSP &event_sp) -{ - const BreakpointEventData *data = GetEventDataFromEvent (event_sp.get()); - if (data) - return data->m_locations.GetSize(); +size_t Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( + const EventSP &event_sp) { + const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get()); + if (data) + return data->m_locations.GetSize(); - return 0; + return 0; } lldb::BreakpointLocationSP -Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent (const lldb::EventSP &event_sp, uint32_t bp_loc_idx) -{ - lldb::BreakpointLocationSP bp_loc_sp; - - const BreakpointEventData *data = GetEventDataFromEvent (event_sp.get()); - if (data) - { - bp_loc_sp = data->m_locations.GetByIndex(bp_loc_idx); - } +Breakpoint::BreakpointEventData::GetBreakpointLocationAtIndexFromEvent( + const lldb::EventSP &event_sp, uint32_t bp_loc_idx) { + lldb::BreakpointLocationSP bp_loc_sp; + + const BreakpointEventData *data = GetEventDataFromEvent(event_sp.get()); + if (data) { + bp_loc_sp = data->m_locations.GetByIndex(bp_loc_idx); + } - return bp_loc_sp; + return bp_loc_sp; } diff --git a/lldb/source/Breakpoint/BreakpointID.cpp b/lldb/source/Breakpoint/BreakpointID.cpp index 81a3dfe50d9..9ab7adf48c4 100644 --- a/lldb/source/Breakpoint/BreakpointID.cpp +++ b/lldb/source/Breakpoint/BreakpointID.cpp @@ -13,121 +13,108 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Breakpoint/BreakpointID.h" #include "lldb/Breakpoint/Breakpoint.h" -#include "lldb/Core/Stream.h" +#include "lldb/Breakpoint/BreakpointID.h" #include "lldb/Core/Error.h" +#include "lldb/Core/Stream.h" using namespace lldb; using namespace lldb_private; -BreakpointID::BreakpointID (break_id_t bp_id, break_id_t loc_id) : - m_break_id (bp_id), - m_location_id (loc_id) -{ -} +BreakpointID::BreakpointID(break_id_t bp_id, break_id_t loc_id) + : m_break_id(bp_id), m_location_id(loc_id) {} BreakpointID::~BreakpointID() = default; -const char *BreakpointID::g_range_specifiers[] = { "-", "to", "To", "TO", nullptr }; +const char *BreakpointID::g_range_specifiers[] = {"-", "to", "To", "TO", + nullptr}; -// Tells whether or not STR is valid to use between two strings representing breakpoint IDs, to -// indicate a range of breakpoint IDs. This is broken out into a separate function so that we can +// Tells whether or not STR is valid to use between two strings representing +// breakpoint IDs, to +// indicate a range of breakpoint IDs. This is broken out into a separate +// function so that we can // easily change or add to the format for specifying ID ranges at a later date. -bool -BreakpointID::IsRangeIdentifier (const char *str) -{ - int specifier_count = 0; - for (int i = 0; g_range_specifiers[i] != nullptr; ++i) - ++specifier_count; - - for (int i = 0; i < specifier_count; ++i) - { - if (strcmp (g_range_specifiers[i], str) == 0) - return true; - } +bool BreakpointID::IsRangeIdentifier(const char *str) { + int specifier_count = 0; + for (int i = 0; g_range_specifiers[i] != nullptr; ++i) + ++specifier_count; + + for (int i = 0; i < specifier_count; ++i) { + if (strcmp(g_range_specifiers[i], str) == 0) + return true; + } return false; } -bool -BreakpointID::IsValidIDExpression (const char *str) -{ - break_id_t bp_id; - break_id_t loc_id; - BreakpointID::ParseCanonicalReference (str, &bp_id, &loc_id); +bool BreakpointID::IsValidIDExpression(const char *str) { + break_id_t bp_id; + break_id_t loc_id; + BreakpointID::ParseCanonicalReference(str, &bp_id, &loc_id); - return (bp_id != LLDB_INVALID_BREAK_ID); + return (bp_id != LLDB_INVALID_BREAK_ID); } -void -BreakpointID::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - if (level == eDescriptionLevelVerbose) - s->Printf("%p BreakpointID:", static_cast(this)); - - if (m_break_id == LLDB_INVALID_BREAK_ID) - s->PutCString (""); - else if (m_location_id == LLDB_INVALID_BREAK_ID) - s->Printf("%i", m_break_id); - else - s->Printf("%i.%i", m_break_id, m_location_id); +void BreakpointID::GetDescription(Stream *s, lldb::DescriptionLevel level) { + if (level == eDescriptionLevelVerbose) + s->Printf("%p BreakpointID:", static_cast(this)); + + if (m_break_id == LLDB_INVALID_BREAK_ID) + s->PutCString(""); + else if (m_location_id == LLDB_INVALID_BREAK_ID) + s->Printf("%i", m_break_id); + else + s->Printf("%i.%i", m_break_id, m_location_id); } -void -BreakpointID::GetCanonicalReference (Stream *s, break_id_t bp_id, break_id_t loc_id) -{ - if (bp_id == LLDB_INVALID_BREAK_ID) - s->PutCString (""); - else if (loc_id == LLDB_INVALID_BREAK_ID) - s->Printf("%i", bp_id); - else - s->Printf("%i.%i", bp_id, loc_id); +void BreakpointID::GetCanonicalReference(Stream *s, break_id_t bp_id, + break_id_t loc_id) { + if (bp_id == LLDB_INVALID_BREAK_ID) + s->PutCString(""); + else if (loc_id == LLDB_INVALID_BREAK_ID) + s->Printf("%i", bp_id); + else + s->Printf("%i.%i", bp_id, loc_id); } -bool -BreakpointID::ParseCanonicalReference (const char *input, break_id_t *break_id_ptr, break_id_t *break_loc_id_ptr) -{ - *break_id_ptr = LLDB_INVALID_BREAK_ID; - *break_loc_id_ptr = LLDB_INVALID_BREAK_ID; - - if (input == nullptr || *input == '\0') - return false; - - const char *format = "%i%n.%i%n"; - int chars_consumed_1 = 0; - int chars_consumed_2 = 0; - int n_items_parsed = ::sscanf (input, - format, - break_id_ptr, // %i parse the breakpoint ID - &chars_consumed_1, // %n gets the number of characters parsed so far - break_loc_id_ptr, // %i parse the breakpoint location ID - &chars_consumed_2); // %n gets the number of characters parsed so far - - if ((n_items_parsed == 1 && input[chars_consumed_1] == '\0') || - (n_items_parsed == 2 && input[chars_consumed_2] == '\0')) - return true; - - // Badly formatted canonical reference. - *break_id_ptr = LLDB_INVALID_BREAK_ID; - *break_loc_id_ptr = LLDB_INVALID_BREAK_ID; +bool BreakpointID::ParseCanonicalReference(const char *input, + break_id_t *break_id_ptr, + break_id_t *break_loc_id_ptr) { + *break_id_ptr = LLDB_INVALID_BREAK_ID; + *break_loc_id_ptr = LLDB_INVALID_BREAK_ID; + + if (input == nullptr || *input == '\0') return false; + + const char *format = "%i%n.%i%n"; + int chars_consumed_1 = 0; + int chars_consumed_2 = 0; + int n_items_parsed = ::sscanf( + input, format, + break_id_ptr, // %i parse the breakpoint ID + &chars_consumed_1, // %n gets the number of characters parsed so far + break_loc_id_ptr, // %i parse the breakpoint location ID + &chars_consumed_2); // %n gets the number of characters parsed so far + + if ((n_items_parsed == 1 && input[chars_consumed_1] == '\0') || + (n_items_parsed == 2 && input[chars_consumed_2] == '\0')) + return true; + + // Badly formatted canonical reference. + *break_id_ptr = LLDB_INVALID_BREAK_ID; + *break_loc_id_ptr = LLDB_INVALID_BREAK_ID; + return false; } -bool -BreakpointID::StringIsBreakpointName(const char *name, Error &error) -{ - error.Clear(); - - if (name && (name[0] >= 'A' && name[0] <= 'z')) - { - if (strcspn(name, ".- ") != strlen(name)) - { - error.SetErrorStringWithFormat("invalid breakpoint name: \"%s\"", name); - } - return true; +bool BreakpointID::StringIsBreakpointName(const char *name, Error &error) { + error.Clear(); + + if (name && (name[0] >= 'A' && name[0] <= 'z')) { + if (strcspn(name, ".- ") != strlen(name)) { + error.SetErrorStringWithFormat("invalid breakpoint name: \"%s\"", name); } - else - return false; + return true; + } else + return false; } diff --git a/lldb/source/Breakpoint/BreakpointIDList.cpp b/lldb/source/Breakpoint/BreakpointIDList.cpp index ebf0697c271..4871105def7 100644 --- a/lldb/source/Breakpoint/BreakpointIDList.cpp +++ b/lldb/source/Breakpoint/BreakpointIDList.cpp @@ -15,8 +15,8 @@ #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" -#include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/Args.h" +#include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Target.h" using namespace lldb; @@ -26,412 +26,370 @@ using namespace lldb_private; // class BreakpointIDList //---------------------------------------------------------------------- -BreakpointIDList::BreakpointIDList () : -m_invalid_id (LLDB_INVALID_BREAK_ID, LLDB_INVALID_BREAK_ID) -{ -} +BreakpointIDList::BreakpointIDList() + : m_invalid_id(LLDB_INVALID_BREAK_ID, LLDB_INVALID_BREAK_ID) {} BreakpointIDList::~BreakpointIDList() = default; -size_t -BreakpointIDList::GetSize() -{ - return m_breakpoint_ids.size(); -} +size_t BreakpointIDList::GetSize() { return m_breakpoint_ids.size(); } -BreakpointID & -BreakpointIDList::GetBreakpointIDAtIndex(size_t index) -{ - return ((index < m_breakpoint_ids.size()) ? m_breakpoint_ids[index] : m_invalid_id); +BreakpointID &BreakpointIDList::GetBreakpointIDAtIndex(size_t index) { + return ((index < m_breakpoint_ids.size()) ? m_breakpoint_ids[index] + : m_invalid_id); } -bool -BreakpointIDList::RemoveBreakpointIDAtIndex (size_t index) -{ - if (index >= m_breakpoint_ids.size()) - return false; +bool BreakpointIDList::RemoveBreakpointIDAtIndex(size_t index) { + if (index >= m_breakpoint_ids.size()) + return false; - m_breakpoint_ids.erase (m_breakpoint_ids.begin() + index); - return true; + m_breakpoint_ids.erase(m_breakpoint_ids.begin() + index); + return true; } -void -BreakpointIDList::Clear() -{ - m_breakpoint_ids.clear (); -} +void BreakpointIDList::Clear() { m_breakpoint_ids.clear(); } -bool -BreakpointIDList::AddBreakpointID (BreakpointID bp_id) -{ - m_breakpoint_ids.push_back (bp_id); +bool BreakpointIDList::AddBreakpointID(BreakpointID bp_id) { + m_breakpoint_ids.push_back(bp_id); - return true; // We don't do any verification in this function, so always return true. + return true; // We don't do any verification in this function, so always + // return true. } -bool -BreakpointIDList::AddBreakpointID (const char *bp_id_str) -{ - BreakpointID temp_bp_id; - break_id_t bp_id; - break_id_t loc_id; +bool BreakpointIDList::AddBreakpointID(const char *bp_id_str) { + BreakpointID temp_bp_id; + break_id_t bp_id; + break_id_t loc_id; - bool success = BreakpointID::ParseCanonicalReference (bp_id_str, &bp_id, &loc_id); + bool success = + BreakpointID::ParseCanonicalReference(bp_id_str, &bp_id, &loc_id); - if (success) - { - temp_bp_id.SetID (bp_id, loc_id); - m_breakpoint_ids.push_back (temp_bp_id); - } + if (success) { + temp_bp_id.SetID(bp_id, loc_id); + m_breakpoint_ids.push_back(temp_bp_id); + } - return success; + return success; } -bool -BreakpointIDList::FindBreakpointID (BreakpointID &bp_id, size_t *position) -{ - for (size_t i = 0; i < m_breakpoint_ids.size(); ++i) - { - BreakpointID tmp_id = m_breakpoint_ids[i]; - if (tmp_id.GetBreakpointID() == bp_id.GetBreakpointID() - && tmp_id.GetLocationID() == bp_id.GetLocationID()) - { - *position = i; - return true; - } +bool BreakpointIDList::FindBreakpointID(BreakpointID &bp_id, size_t *position) { + for (size_t i = 0; i < m_breakpoint_ids.size(); ++i) { + BreakpointID tmp_id = m_breakpoint_ids[i]; + if (tmp_id.GetBreakpointID() == bp_id.GetBreakpointID() && + tmp_id.GetLocationID() == bp_id.GetLocationID()) { + *position = i; + return true; } + } + return false; +} + +bool BreakpointIDList::FindBreakpointID(const char *bp_id_str, + size_t *position) { + BreakpointID temp_bp_id; + break_id_t bp_id; + break_id_t loc_id; + + if (BreakpointID::ParseCanonicalReference(bp_id_str, &bp_id, &loc_id)) { + temp_bp_id.SetID(bp_id, loc_id); + return FindBreakpointID(temp_bp_id, position); + } else return false; } -bool -BreakpointIDList::FindBreakpointID (const char *bp_id_str, size_t *position) -{ - BreakpointID temp_bp_id; +void BreakpointIDList::InsertStringArray(const char **string_array, + size_t array_size, + CommandReturnObject &result) { + if (string_array == nullptr) + return; + + for (uint32_t i = 0; i < array_size; ++i) { break_id_t bp_id; break_id_t loc_id; - if (BreakpointID::ParseCanonicalReference (bp_id_str, &bp_id, &loc_id)) - { - temp_bp_id.SetID (bp_id, loc_id); - return FindBreakpointID (temp_bp_id, position); - } - else - return false; -} - -void -BreakpointIDList::InsertStringArray (const char **string_array, size_t array_size, CommandReturnObject &result) -{ - if (string_array == nullptr) + if (BreakpointID::ParseCanonicalReference(string_array[i], &bp_id, + &loc_id)) { + if (bp_id != LLDB_INVALID_BREAK_ID) { + BreakpointID temp_bp_id(bp_id, loc_id); + m_breakpoint_ids.push_back(temp_bp_id); + } else { + result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n", + string_array[i]); + result.SetStatus(eReturnStatusFailed); return; - - for (uint32_t i = 0; i < array_size; ++i) - { - break_id_t bp_id; - break_id_t loc_id; - - if (BreakpointID::ParseCanonicalReference (string_array[i], &bp_id, &loc_id)) - { - if (bp_id != LLDB_INVALID_BREAK_ID) - { - BreakpointID temp_bp_id(bp_id, loc_id); - m_breakpoint_ids.push_back (temp_bp_id); - } - else - { - result.AppendErrorWithFormat ("'%s' is not a valid breakpoint ID.\n", string_array[i]); - result.SetStatus (eReturnStatusFailed); - return; - } - } + } } - result.SetStatus (eReturnStatusSuccessFinishNoResult); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); } +// This function takes OLD_ARGS, which is usually the result of breaking the +// command string arguments into +// an array of space-separated strings, and searches through the arguments for +// any breakpoint ID range specifiers. +// Any string in the array that is not part of an ID range specifier is copied +// directly into NEW_ARGS. If any +// ID range specifiers are found, the range is interpreted and a list of +// canonical breakpoint IDs corresponding to +// all the current breakpoints and locations in the range are added to +// NEW_ARGS. When this function is done, +// NEW_ARGS should be a copy of OLD_ARGS, with and ID range specifiers replaced +// by the members of the range. + +void BreakpointIDList::FindAndReplaceIDRanges(Args &old_args, Target *target, + bool allow_locations, + CommandReturnObject &result, + Args &new_args) { + std::string range_start; + const char *range_end; + const char *current_arg; + const size_t num_old_args = old_args.GetArgumentCount(); + std::set names_found; + + for (size_t i = 0; i < num_old_args; ++i) { + bool is_range = false; + + current_arg = old_args.GetArgumentAtIndex(i); + if (!allow_locations && strchr(current_arg, '.') != nullptr) { + result.AppendErrorWithFormat( + "Breakpoint locations not allowed, saw location: %s.", current_arg); + new_args.Clear(); + return; + } -// This function takes OLD_ARGS, which is usually the result of breaking the command string arguments into -// an array of space-separated strings, and searches through the arguments for any breakpoint ID range specifiers. -// Any string in the array that is not part of an ID range specifier is copied directly into NEW_ARGS. If any -// ID range specifiers are found, the range is interpreted and a list of canonical breakpoint IDs corresponding to -// all the current breakpoints and locations in the range are added to NEW_ARGS. When this function is done, -// NEW_ARGS should be a copy of OLD_ARGS, with and ID range specifiers replaced by the members of the range. - -void -BreakpointIDList::FindAndReplaceIDRanges (Args &old_args, - Target *target, - bool allow_locations, - CommandReturnObject &result, - Args &new_args) -{ - std::string range_start; - const char *range_end; - const char *current_arg; - const size_t num_old_args = old_args.GetArgumentCount(); - std::set names_found; - - for (size_t i = 0; i < num_old_args; ++i) - { - bool is_range = false; - - current_arg = old_args.GetArgumentAtIndex (i); - if (!allow_locations && strchr(current_arg, '.') != nullptr) - { - result.AppendErrorWithFormat ("Breakpoint locations not allowed, saw location: %s.", current_arg); + size_t range_start_len = 0; + size_t range_end_pos = 0; + Error error; + + if (BreakpointIDList::StringContainsIDRangeExpression( + current_arg, &range_start_len, &range_end_pos)) { + is_range = true; + range_start.assign(current_arg, range_start_len); + range_end = current_arg + range_end_pos; + } else if (BreakpointID::StringIsBreakpointName(current_arg, error)) { + if (!error.Success()) { + new_args.Clear(); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return; + } else + names_found.insert(current_arg); + } else if ((i + 2 < num_old_args) && + BreakpointID::IsRangeIdentifier( + old_args.GetArgumentAtIndex(i + 1)) && + BreakpointID::IsValidIDExpression(current_arg) && + BreakpointID::IsValidIDExpression( + old_args.GetArgumentAtIndex(i + 2))) { + range_start.assign(current_arg); + range_end = old_args.GetArgumentAtIndex(i + 2); + is_range = true; + i = i + 2; + } else { + // See if user has specified id.* + std::string tmp_str = old_args.GetArgumentAtIndex(i); + size_t pos = tmp_str.find('.'); + if (pos != std::string::npos) { + std::string bp_id_str = tmp_str.substr(0, pos); + if (BreakpointID::IsValidIDExpression(bp_id_str.c_str()) && + tmp_str[pos + 1] == '*' && tmp_str.length() == (pos + 2)) { + break_id_t bp_id; + break_id_t bp_loc_id; + + BreakpointID::ParseCanonicalReference(bp_id_str.c_str(), &bp_id, + &bp_loc_id); + BreakpointSP breakpoint_sp = target->GetBreakpointByID(bp_id); + if (!breakpoint_sp) { new_args.Clear(); + result.AppendErrorWithFormat("'%d' is not a valid breakpoint ID.\n", + bp_id); + result.SetStatus(eReturnStatusFailed); return; + } + const size_t num_locations = breakpoint_sp->GetNumLocations(); + for (size_t j = 0; j < num_locations; ++j) { + BreakpointLocation *bp_loc = + breakpoint_sp->GetLocationAtIndex(j).get(); + StreamString canonical_id_str; + BreakpointID::GetCanonicalReference(&canonical_id_str, bp_id, + bp_loc->GetID()); + new_args.AppendArgument(canonical_id_str.GetData()); + } } + } + } - size_t range_start_len = 0; - size_t range_end_pos = 0; - Error error; - - if (BreakpointIDList::StringContainsIDRangeExpression (current_arg, &range_start_len, &range_end_pos)) - { - is_range = true; - range_start.assign (current_arg, range_start_len); - range_end = current_arg + range_end_pos; - } - else if (BreakpointID::StringIsBreakpointName(current_arg, error)) - { - if (!error.Success()) - { - new_args.Clear(); - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return; - } - else - names_found.insert(current_arg); - } - else if ((i + 2 < num_old_args) - && BreakpointID::IsRangeIdentifier (old_args.GetArgumentAtIndex (i+1)) - && BreakpointID::IsValidIDExpression (current_arg) - && BreakpointID::IsValidIDExpression (old_args.GetArgumentAtIndex (i+2))) - { - range_start.assign (current_arg); - range_end = old_args.GetArgumentAtIndex (i+2); - is_range = true; - i = i+2; - } - else - { - // See if user has specified id.* - std::string tmp_str = old_args.GetArgumentAtIndex (i); - size_t pos = tmp_str.find ('.'); - if (pos != std::string::npos) - { - std::string bp_id_str = tmp_str.substr (0, pos); - if (BreakpointID::IsValidIDExpression (bp_id_str.c_str()) - && tmp_str[pos+1] == '*' - && tmp_str.length() == (pos + 2)) - { - break_id_t bp_id; - break_id_t bp_loc_id; - - BreakpointID::ParseCanonicalReference (bp_id_str.c_str(), &bp_id, &bp_loc_id); - BreakpointSP breakpoint_sp = target->GetBreakpointByID (bp_id); - if (! breakpoint_sp) - { - new_args.Clear(); - result.AppendErrorWithFormat ("'%d' is not a valid breakpoint ID.\n", bp_id); - result.SetStatus (eReturnStatusFailed); - return; - } - const size_t num_locations = breakpoint_sp->GetNumLocations(); - for (size_t j = 0; j < num_locations; ++j) - { - BreakpointLocation *bp_loc = breakpoint_sp->GetLocationAtIndex(j).get(); - StreamString canonical_id_str; - BreakpointID::GetCanonicalReference (&canonical_id_str, bp_id, bp_loc->GetID()); - new_args.AppendArgument (canonical_id_str.GetData()); - } - } - - } + if (is_range) { + break_id_t start_bp_id; + break_id_t end_bp_id; + break_id_t start_loc_id; + break_id_t end_loc_id; + + BreakpointID::ParseCanonicalReference(range_start.c_str(), &start_bp_id, + &start_loc_id); + BreakpointID::ParseCanonicalReference(range_end, &end_bp_id, &end_loc_id); + + if ((start_bp_id == LLDB_INVALID_BREAK_ID) || + (!target->GetBreakpointByID(start_bp_id))) { + new_args.Clear(); + result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n", + range_start.c_str()); + result.SetStatus(eReturnStatusFailed); + return; + } + + if ((end_bp_id == LLDB_INVALID_BREAK_ID) || + (!target->GetBreakpointByID(end_bp_id))) { + new_args.Clear(); + result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n", + range_end); + result.SetStatus(eReturnStatusFailed); + return; + } + + if (((start_loc_id == LLDB_INVALID_BREAK_ID) && + (end_loc_id != LLDB_INVALID_BREAK_ID)) || + ((start_loc_id != LLDB_INVALID_BREAK_ID) && + (end_loc_id == LLDB_INVALID_BREAK_ID))) { + new_args.Clear(); + result.AppendErrorWithFormat("Invalid breakpoint id range: Either " + "both ends of range must specify" + " a breakpoint location, or neither can " + "specify a breakpoint location.\n"); + result.SetStatus(eReturnStatusFailed); + return; + } + + // We have valid range starting & ending breakpoint IDs. Go through all + // the breakpoints in the + // target and find all the breakpoints that fit into this range, and add + // them to new_args. + + // Next check to see if we have location id's. If so, make sure the + // start_bp_id and end_bp_id are + // for the same breakpoint; otherwise we have an illegal range: breakpoint + // id ranges that specify + // bp locations are NOT allowed to cross major bp id numbers. + + if ((start_loc_id != LLDB_INVALID_BREAK_ID) || + (end_loc_id != LLDB_INVALID_BREAK_ID)) { + if (start_bp_id != end_bp_id) { + new_args.Clear(); + result.AppendErrorWithFormat( + "Invalid range: Ranges that specify particular breakpoint " + "locations" + " must be within the same major breakpoint; you specified two" + " different major breakpoints, %d and %d.\n", + start_bp_id, end_bp_id); + result.SetStatus(eReturnStatusFailed); + return; } - - if (is_range) - { - break_id_t start_bp_id; - break_id_t end_bp_id; - break_id_t start_loc_id; - break_id_t end_loc_id; - - BreakpointID::ParseCanonicalReference (range_start.c_str(), &start_bp_id, &start_loc_id); - BreakpointID::ParseCanonicalReference (range_end, &end_bp_id, &end_loc_id); - - if ((start_bp_id == LLDB_INVALID_BREAK_ID) - || (! target->GetBreakpointByID (start_bp_id))) - { - new_args.Clear(); - result.AppendErrorWithFormat ("'%s' is not a valid breakpoint ID.\n", range_start.c_str()); - result.SetStatus (eReturnStatusFailed); - return; - } - - if ((end_bp_id == LLDB_INVALID_BREAK_ID) - || (! target->GetBreakpointByID (end_bp_id))) - { - new_args.Clear(); - result.AppendErrorWithFormat ("'%s' is not a valid breakpoint ID.\n", range_end); - result.SetStatus (eReturnStatusFailed); - return; - } - - - if (((start_loc_id == LLDB_INVALID_BREAK_ID) - && (end_loc_id != LLDB_INVALID_BREAK_ID)) - || ((start_loc_id != LLDB_INVALID_BREAK_ID) - && (end_loc_id == LLDB_INVALID_BREAK_ID))) - { - new_args.Clear (); - result.AppendErrorWithFormat ("Invalid breakpoint id range: Either both ends of range must specify" - " a breakpoint location, or neither can specify a breakpoint location.\n"); - result.SetStatus (eReturnStatusFailed); - return; + } + + const BreakpointList &breakpoints = target->GetBreakpointList(); + const size_t num_breakpoints = breakpoints.GetSize(); + for (size_t j = 0; j < num_breakpoints; ++j) { + Breakpoint *breakpoint = breakpoints.GetBreakpointAtIndex(j).get(); + break_id_t cur_bp_id = breakpoint->GetID(); + + if ((cur_bp_id < start_bp_id) || (cur_bp_id > end_bp_id)) + continue; + + const size_t num_locations = breakpoint->GetNumLocations(); + + if ((cur_bp_id == start_bp_id) && + (start_loc_id != LLDB_INVALID_BREAK_ID)) { + for (size_t k = 0; k < num_locations; ++k) { + BreakpointLocation *bp_loc = + breakpoint->GetLocationAtIndex(k).get(); + if ((bp_loc->GetID() >= start_loc_id) && + (bp_loc->GetID() <= end_loc_id)) { + StreamString canonical_id_str; + BreakpointID::GetCanonicalReference(&canonical_id_str, cur_bp_id, + bp_loc->GetID()); + new_args.AppendArgument(canonical_id_str.GetData()); } - - // We have valid range starting & ending breakpoint IDs. Go through all the breakpoints in the - // target and find all the breakpoints that fit into this range, and add them to new_args. - - // Next check to see if we have location id's. If so, make sure the start_bp_id and end_bp_id are - // for the same breakpoint; otherwise we have an illegal range: breakpoint id ranges that specify - // bp locations are NOT allowed to cross major bp id numbers. - - if ((start_loc_id != LLDB_INVALID_BREAK_ID) - || (end_loc_id != LLDB_INVALID_BREAK_ID)) - { - if (start_bp_id != end_bp_id) - { - new_args.Clear(); - result.AppendErrorWithFormat ("Invalid range: Ranges that specify particular breakpoint locations" - " must be within the same major breakpoint; you specified two" - " different major breakpoints, %d and %d.\n", - start_bp_id, end_bp_id); - result.SetStatus (eReturnStatusFailed); - return; - } - } - - const BreakpointList& breakpoints = target->GetBreakpointList(); - const size_t num_breakpoints = breakpoints.GetSize(); - for (size_t j = 0; j < num_breakpoints; ++j) - { - Breakpoint *breakpoint = breakpoints.GetBreakpointAtIndex (j).get(); - break_id_t cur_bp_id = breakpoint->GetID(); - - if ((cur_bp_id < start_bp_id) || (cur_bp_id > end_bp_id)) - continue; - - const size_t num_locations = breakpoint->GetNumLocations(); - - if ((cur_bp_id == start_bp_id) && (start_loc_id != LLDB_INVALID_BREAK_ID)) - { - for (size_t k = 0; k < num_locations; ++k) - { - BreakpointLocation * bp_loc = breakpoint->GetLocationAtIndex(k).get(); - if ((bp_loc->GetID() >= start_loc_id) && (bp_loc->GetID() <= end_loc_id)) - { - StreamString canonical_id_str; - BreakpointID::GetCanonicalReference (&canonical_id_str, cur_bp_id, bp_loc->GetID()); - new_args.AppendArgument (canonical_id_str.GetData()); - } - } - } - else if ((cur_bp_id == end_bp_id) && (end_loc_id != LLDB_INVALID_BREAK_ID)) - { - for (size_t k = 0; k < num_locations; ++k) - { - BreakpointLocation * bp_loc = breakpoint->GetLocationAtIndex(k).get(); - if (bp_loc->GetID() <= end_loc_id) - { - StreamString canonical_id_str; - BreakpointID::GetCanonicalReference (&canonical_id_str, cur_bp_id, bp_loc->GetID()); - new_args.AppendArgument (canonical_id_str.GetData()); - } - } - } - else - { - StreamString canonical_id_str; - BreakpointID::GetCanonicalReference (&canonical_id_str, cur_bp_id, LLDB_INVALID_BREAK_ID); - new_args.AppendArgument (canonical_id_str.GetData()); - } + } + } else if ((cur_bp_id == end_bp_id) && + (end_loc_id != LLDB_INVALID_BREAK_ID)) { + for (size_t k = 0; k < num_locations; ++k) { + BreakpointLocation *bp_loc = + breakpoint->GetLocationAtIndex(k).get(); + if (bp_loc->GetID() <= end_loc_id) { + StreamString canonical_id_str; + BreakpointID::GetCanonicalReference(&canonical_id_str, cur_bp_id, + bp_loc->GetID()); + new_args.AppendArgument(canonical_id_str.GetData()); } + } + } else { + StreamString canonical_id_str; + BreakpointID::GetCanonicalReference(&canonical_id_str, cur_bp_id, + LLDB_INVALID_BREAK_ID); + new_args.AppendArgument(canonical_id_str.GetData()); } - else // else is_range was false - { - new_args.AppendArgument (current_arg); - } - } - - // Okay, now see if we found any names, and if we did, add them: - if (target && names_found.size()) + } + } else // else is_range was false { - for (BreakpointSP bkpt_sp : target->GetBreakpointList().Breakpoints()) - { - for (std::string name : names_found) - { - if (bkpt_sp->MatchesName(name.c_str())) - { - StreamString canonical_id_str; - BreakpointID::GetCanonicalReference (&canonical_id_str, bkpt_sp->GetID(), LLDB_INVALID_BREAK_ID); - new_args.AppendArgument (canonical_id_str.GetData()); - } - } + new_args.AppendArgument(current_arg); + } + } + + // Okay, now see if we found any names, and if we did, add them: + if (target && names_found.size()) { + for (BreakpointSP bkpt_sp : target->GetBreakpointList().Breakpoints()) { + for (std::string name : names_found) { + if (bkpt_sp->MatchesName(name.c_str())) { + StreamString canonical_id_str; + BreakpointID::GetCanonicalReference( + &canonical_id_str, bkpt_sp->GetID(), LLDB_INVALID_BREAK_ID); + new_args.AppendArgument(canonical_id_str.GetData()); } + } } + } - result.SetStatus (eReturnStatusSuccessFinishNoResult); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } -bool -BreakpointIDList::StringContainsIDRangeExpression (const char *in_string, - size_t *range_start_len, - size_t *range_end_pos) -{ - bool is_range_expression = false; - std::string arg_str = in_string; - std::string::size_type idx; - std::string::size_type start_pos = 0; - - *range_start_len = 0; - *range_end_pos = 0; - - int specifiers_size = 0; - for (int i = 0; BreakpointID::g_range_specifiers[i] != nullptr; ++i) - ++specifiers_size; - - for (int i = 0; i < specifiers_size && !is_range_expression; ++i) - { - const char *specifier_str = BreakpointID::g_range_specifiers[i]; - size_t len = strlen (specifier_str); - idx = arg_str.find (BreakpointID::g_range_specifiers[i]); - if (idx != std::string::npos) - { - *range_start_len = idx - start_pos; - std::string start_str = arg_str.substr (start_pos, *range_start_len); - if (idx + len < arg_str.length()) - { - *range_end_pos = idx + len; - std::string end_str = arg_str.substr (*range_end_pos); - if (BreakpointID::IsValidIDExpression (start_str.c_str()) - && BreakpointID::IsValidIDExpression (end_str.c_str())) - { - is_range_expression = true; - //*range_start = start_str; - //*range_end = end_str; - } - } +bool BreakpointIDList::StringContainsIDRangeExpression(const char *in_string, + size_t *range_start_len, + size_t *range_end_pos) { + bool is_range_expression = false; + std::string arg_str = in_string; + std::string::size_type idx; + std::string::size_type start_pos = 0; + + *range_start_len = 0; + *range_end_pos = 0; + + int specifiers_size = 0; + for (int i = 0; BreakpointID::g_range_specifiers[i] != nullptr; ++i) + ++specifiers_size; + + for (int i = 0; i < specifiers_size && !is_range_expression; ++i) { + const char *specifier_str = BreakpointID::g_range_specifiers[i]; + size_t len = strlen(specifier_str); + idx = arg_str.find(BreakpointID::g_range_specifiers[i]); + if (idx != std::string::npos) { + *range_start_len = idx - start_pos; + std::string start_str = arg_str.substr(start_pos, *range_start_len); + if (idx + len < arg_str.length()) { + *range_end_pos = idx + len; + std::string end_str = arg_str.substr(*range_end_pos); + if (BreakpointID::IsValidIDExpression(start_str.c_str()) && + BreakpointID::IsValidIDExpression(end_str.c_str())) { + is_range_expression = true; + //*range_start = start_str; + //*range_end = end_str; } + } } + } - if (!is_range_expression) - { - *range_start_len = 0; - *range_end_pos = 0; - } + if (!is_range_expression) { + *range_start_len = 0; + *range_end_pos = 0; + } - return is_range_expression; + return is_range_expression; } diff --git a/lldb/source/Breakpoint/BreakpointList.cpp b/lldb/source/Breakpoint/BreakpointList.cpp index 9877c2d1246..a47a07d92e5 100644 --- a/lldb/source/Breakpoint/BreakpointList.cpp +++ b/lldb/source/Breakpoint/BreakpointList.cpp @@ -19,222 +19,183 @@ using namespace lldb; using namespace lldb_private; BreakpointList::BreakpointList(bool is_internal) - : m_mutex(), m_breakpoints(), m_next_break_id(0), m_is_internal(is_internal) -{ -} - -BreakpointList::~BreakpointList() -{ -} - - -break_id_t -BreakpointList::Add (BreakpointSP &bp_sp, bool notify) -{ - std::lock_guard guard(m_mutex); - // Internal breakpoint IDs are negative, normal ones are positive - bp_sp->SetID (m_is_internal ? --m_next_break_id : ++m_next_break_id); - - m_breakpoints.push_back(bp_sp); - if (notify) - { - if (bp_sp->GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - bp_sp->GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, - new Breakpoint::BreakpointEventData (eBreakpointEventTypeAdded, bp_sp)); - } - return bp_sp->GetID(); -} - -bool -BreakpointList::Remove (break_id_t break_id, bool notify) -{ - std::lock_guard guard(m_mutex); - bp_collection::iterator pos = GetBreakpointIDIterator(break_id); // Predicate - if (pos != m_breakpoints.end()) - { - BreakpointSP bp_sp (*pos); - m_breakpoints.erase(pos); - if (notify) - { - if (bp_sp->GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - bp_sp->GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, - new Breakpoint::BreakpointEventData (eBreakpointEventTypeRemoved, bp_sp)); - } - return true; + : m_mutex(), m_breakpoints(), m_next_break_id(0), + m_is_internal(is_internal) {} + +BreakpointList::~BreakpointList() {} + +break_id_t BreakpointList::Add(BreakpointSP &bp_sp, bool notify) { + std::lock_guard guard(m_mutex); + // Internal breakpoint IDs are negative, normal ones are positive + bp_sp->SetID(m_is_internal ? --m_next_break_id : ++m_next_break_id); + + m_breakpoints.push_back(bp_sp); + if (notify) { + if (bp_sp->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) + bp_sp->GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, + new Breakpoint::BreakpointEventData( + eBreakpointEventTypeAdded, bp_sp)); + } + return bp_sp->GetID(); +} + +bool BreakpointList::Remove(break_id_t break_id, bool notify) { + std::lock_guard guard(m_mutex); + bp_collection::iterator pos = GetBreakpointIDIterator(break_id); // Predicate + if (pos != m_breakpoints.end()) { + BreakpointSP bp_sp(*pos); + m_breakpoints.erase(pos); + if (notify) { + if (bp_sp->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) + bp_sp->GetTarget().BroadcastEvent( + Target::eBroadcastBitBreakpointChanged, + new Breakpoint::BreakpointEventData(eBreakpointEventTypeRemoved, + bp_sp)); } - return false; + return true; + } + return false; } -void -BreakpointList::RemoveInvalidLocations (const ArchSpec &arch) -{ - std::lock_guard guard(m_mutex); - for (const auto &bp_sp : m_breakpoints) - bp_sp->RemoveInvalidLocations(arch); +void BreakpointList::RemoveInvalidLocations(const ArchSpec &arch) { + std::lock_guard guard(m_mutex); + for (const auto &bp_sp : m_breakpoints) + bp_sp->RemoveInvalidLocations(arch); } - -void -BreakpointList::SetEnabledAll (bool enabled) -{ - std::lock_guard guard(m_mutex); - for (const auto &bp_sp : m_breakpoints) - bp_sp->SetEnabled (enabled); +void BreakpointList::SetEnabledAll(bool enabled) { + std::lock_guard guard(m_mutex); + for (const auto &bp_sp : m_breakpoints) + bp_sp->SetEnabled(enabled); } +void BreakpointList::RemoveAll(bool notify) { + std::lock_guard guard(m_mutex); + ClearAllBreakpointSites(); -void -BreakpointList::RemoveAll (bool notify) -{ - std::lock_guard guard(m_mutex); - ClearAllBreakpointSites (); - - if (notify) - { - bp_collection::iterator pos, end = m_breakpoints.end(); - for (pos = m_breakpoints.begin(); pos != end; ++pos) - { - if ((*pos)->GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - { - (*pos)->GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, - new Breakpoint::BreakpointEventData (eBreakpointEventTypeRemoved, - *pos)); - } - } + if (notify) { + bp_collection::iterator pos, end = m_breakpoints.end(); + for (pos = m_breakpoints.begin(); pos != end; ++pos) { + if ((*pos)->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) { + (*pos)->GetTarget().BroadcastEvent( + Target::eBroadcastBitBreakpointChanged, + new Breakpoint::BreakpointEventData(eBreakpointEventTypeRemoved, + *pos)); + } } - m_breakpoints.erase (m_breakpoints.begin(), m_breakpoints.end()); + } + m_breakpoints.erase(m_breakpoints.begin(), m_breakpoints.end()); } -class BreakpointIDMatches -{ +class BreakpointIDMatches { public: - BreakpointIDMatches (break_id_t break_id) : - m_break_id(break_id) - { - } + BreakpointIDMatches(break_id_t break_id) : m_break_id(break_id) {} - bool operator() (const BreakpointSP &bp) const - { - return m_break_id == bp->GetID(); - } + bool operator()(const BreakpointSP &bp) const { + return m_break_id == bp->GetID(); + } private: - const break_id_t m_break_id; + const break_id_t m_break_id; }; BreakpointList::bp_collection::iterator -BreakpointList::GetBreakpointIDIterator (break_id_t break_id) -{ - return std::find_if(m_breakpoints.begin(), m_breakpoints.end(), // Search full range - BreakpointIDMatches(break_id)); // Predicate +BreakpointList::GetBreakpointIDIterator(break_id_t break_id) { + return std::find_if(m_breakpoints.begin(), + m_breakpoints.end(), // Search full range + BreakpointIDMatches(break_id)); // Predicate } BreakpointList::bp_collection::const_iterator -BreakpointList::GetBreakpointIDConstIterator (break_id_t break_id) const -{ - return std::find_if(m_breakpoints.begin(), m_breakpoints.end(), // Search full range - BreakpointIDMatches(break_id)); // Predicate +BreakpointList::GetBreakpointIDConstIterator(break_id_t break_id) const { + return std::find_if(m_breakpoints.begin(), + m_breakpoints.end(), // Search full range + BreakpointIDMatches(break_id)); // Predicate } -BreakpointSP -BreakpointList::FindBreakpointByID (break_id_t break_id) -{ - std::lock_guard guard(m_mutex); - BreakpointSP stop_sp; - bp_collection::iterator pos = GetBreakpointIDIterator(break_id); - if (pos != m_breakpoints.end()) - stop_sp = *pos; +BreakpointSP BreakpointList::FindBreakpointByID(break_id_t break_id) { + std::lock_guard guard(m_mutex); + BreakpointSP stop_sp; + bp_collection::iterator pos = GetBreakpointIDIterator(break_id); + if (pos != m_breakpoints.end()) + stop_sp = *pos; - return stop_sp; -} - -const BreakpointSP -BreakpointList::FindBreakpointByID (break_id_t break_id) const -{ - std::lock_guard guard(m_mutex); - BreakpointSP stop_sp; - bp_collection::const_iterator pos = GetBreakpointIDConstIterator(break_id); - if (pos != m_breakpoints.end()) - stop_sp = *pos; - - return stop_sp; -} - -void -BreakpointList::Dump (Stream *s) const -{ - std::lock_guard guard(m_mutex); - s->Printf("%p: ", static_cast(this)); - s->Indent(); - s->Printf("BreakpointList with %u Breakpoints:\n", (uint32_t)m_breakpoints.size()); - s->IndentMore(); - for (const auto &bp_sp : m_breakpoints) - bp_sp->Dump(s); - s->IndentLess(); -} - - -BreakpointSP -BreakpointList::GetBreakpointAtIndex (size_t i) -{ - std::lock_guard guard(m_mutex); - BreakpointSP stop_sp; - bp_collection::iterator end = m_breakpoints.end(); - bp_collection::iterator pos; - size_t curr_i = 0; - for (pos = m_breakpoints.begin(), curr_i = 0; pos != end; ++pos, ++curr_i) - { - if (curr_i == i) - stop_sp = *pos; - } - return stop_sp; + return stop_sp; } const BreakpointSP -BreakpointList::GetBreakpointAtIndex (size_t i) const -{ - std::lock_guard guard(m_mutex); - BreakpointSP stop_sp; - bp_collection::const_iterator end = m_breakpoints.end(); - bp_collection::const_iterator pos; - size_t curr_i = 0; - for (pos = m_breakpoints.begin(), curr_i = 0; pos != end; ++pos, ++curr_i) - { - if (curr_i == i) - stop_sp = *pos; - } - return stop_sp; -} - -void -BreakpointList::UpdateBreakpoints (ModuleList& module_list, bool added, bool delete_locations) -{ - std::lock_guard guard(m_mutex); - for (const auto &bp_sp : m_breakpoints) - bp_sp->ModulesChanged (module_list, added, delete_locations); - -} - -void -BreakpointList::UpdateBreakpointsWhenModuleIsReplaced (ModuleSP old_module_sp, ModuleSP new_module_sp) -{ - std::lock_guard guard(m_mutex); - for (const auto &bp_sp : m_breakpoints) - bp_sp->ModuleReplaced (old_module_sp, new_module_sp); - -} - -void -BreakpointList::ClearAllBreakpointSites () -{ - std::lock_guard guard(m_mutex); - for (const auto &bp_sp : m_breakpoints) - bp_sp->ClearAllBreakpointSites (); - -} - -void -BreakpointList::GetListMutex(std::unique_lock &lock) -{ - lock = std::unique_lock(m_mutex); +BreakpointList::FindBreakpointByID(break_id_t break_id) const { + std::lock_guard guard(m_mutex); + BreakpointSP stop_sp; + bp_collection::const_iterator pos = GetBreakpointIDConstIterator(break_id); + if (pos != m_breakpoints.end()) + stop_sp = *pos; + + return stop_sp; +} + +void BreakpointList::Dump(Stream *s) const { + std::lock_guard guard(m_mutex); + s->Printf("%p: ", static_cast(this)); + s->Indent(); + s->Printf("BreakpointList with %u Breakpoints:\n", + (uint32_t)m_breakpoints.size()); + s->IndentMore(); + for (const auto &bp_sp : m_breakpoints) + bp_sp->Dump(s); + s->IndentLess(); +} + +BreakpointSP BreakpointList::GetBreakpointAtIndex(size_t i) { + std::lock_guard guard(m_mutex); + BreakpointSP stop_sp; + bp_collection::iterator end = m_breakpoints.end(); + bp_collection::iterator pos; + size_t curr_i = 0; + for (pos = m_breakpoints.begin(), curr_i = 0; pos != end; ++pos, ++curr_i) { + if (curr_i == i) + stop_sp = *pos; + } + return stop_sp; +} + +const BreakpointSP BreakpointList::GetBreakpointAtIndex(size_t i) const { + std::lock_guard guard(m_mutex); + BreakpointSP stop_sp; + bp_collection::const_iterator end = m_breakpoints.end(); + bp_collection::const_iterator pos; + size_t curr_i = 0; + for (pos = m_breakpoints.begin(), curr_i = 0; pos != end; ++pos, ++curr_i) { + if (curr_i == i) + stop_sp = *pos; + } + return stop_sp; +} + +void BreakpointList::UpdateBreakpoints(ModuleList &module_list, bool added, + bool delete_locations) { + std::lock_guard guard(m_mutex); + for (const auto &bp_sp : m_breakpoints) + bp_sp->ModulesChanged(module_list, added, delete_locations); +} + +void BreakpointList::UpdateBreakpointsWhenModuleIsReplaced( + ModuleSP old_module_sp, ModuleSP new_module_sp) { + std::lock_guard guard(m_mutex); + for (const auto &bp_sp : m_breakpoints) + bp_sp->ModuleReplaced(old_module_sp, new_module_sp); +} + +void BreakpointList::ClearAllBreakpointSites() { + std::lock_guard guard(m_mutex); + for (const auto &bp_sp : m_breakpoints) + bp_sp->ClearAllBreakpointSites(); +} + +void BreakpointList::GetListMutex( + std::unique_lock &lock) { + lock = std::unique_lock(m_mutex); } diff --git a/lldb/source/Breakpoint/BreakpointLocation.cpp b/lldb/source/Breakpoint/BreakpointLocation.cpp index e1b1af0fe78..c68bf6a05df 100644 --- a/lldb/source/Breakpoint/BreakpointLocation.cpp +++ b/lldb/source/Breakpoint/BreakpointLocation.cpp @@ -25,421 +25,336 @@ #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/TypeSystem.h" -#include "lldb/Target/Target.h" #include "lldb/Target/Process.h" +#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadSpec.h" using namespace lldb; using namespace lldb_private; -BreakpointLocation::BreakpointLocation(break_id_t loc_id, Breakpoint &owner, const Address &addr, lldb::tid_t tid, +BreakpointLocation::BreakpointLocation(break_id_t loc_id, Breakpoint &owner, + const Address &addr, lldb::tid_t tid, bool hardware, bool check_for_resolver) - : StoppointLocation(loc_id, addr.GetOpcodeLoadAddress(&owner.GetTarget()), hardware), - m_being_created(true), - m_should_resolve_indirect_functions(false), - m_is_reexported(false), - m_is_indirect(false), - m_address(addr), - m_owner(owner), - m_options_ap(), - m_bp_site_sp(), - m_condition_mutex() -{ - if (check_for_resolver) - { - Symbol *symbol = m_address.CalculateSymbolContextSymbol(); - if (symbol && symbol->IsIndirect()) - { - SetShouldResolveIndirectFunctions(true); - } + : StoppointLocation(loc_id, addr.GetOpcodeLoadAddress(&owner.GetTarget()), + hardware), + m_being_created(true), m_should_resolve_indirect_functions(false), + m_is_reexported(false), m_is_indirect(false), m_address(addr), + m_owner(owner), m_options_ap(), m_bp_site_sp(), m_condition_mutex() { + if (check_for_resolver) { + Symbol *symbol = m_address.CalculateSymbolContextSymbol(); + if (symbol && symbol->IsIndirect()) { + SetShouldResolveIndirectFunctions(true); } + } - SetThreadID(tid); - m_being_created = false; + SetThreadID(tid); + m_being_created = false; } -BreakpointLocation::~BreakpointLocation() -{ - ClearBreakpointSite(); -} +BreakpointLocation::~BreakpointLocation() { ClearBreakpointSite(); } -lldb::addr_t -BreakpointLocation::GetLoadAddress () const -{ - return m_address.GetOpcodeLoadAddress (&m_owner.GetTarget()); +lldb::addr_t BreakpointLocation::GetLoadAddress() const { + return m_address.GetOpcodeLoadAddress(&m_owner.GetTarget()); } -Address & -BreakpointLocation::GetAddress () -{ - return m_address; -} +Address &BreakpointLocation::GetAddress() { return m_address; } -Breakpoint & -BreakpointLocation::GetBreakpoint () -{ - return m_owner; -} +Breakpoint &BreakpointLocation::GetBreakpoint() { return m_owner; } -Target & -BreakpointLocation::GetTarget() -{ - return m_owner.GetTarget(); -} +Target &BreakpointLocation::GetTarget() { return m_owner.GetTarget(); } -bool -BreakpointLocation::IsEnabled () const -{ - if (!m_owner.IsEnabled()) - return false; - else if (m_options_ap.get() != nullptr) - return m_options_ap->IsEnabled(); - else - return true; +bool BreakpointLocation::IsEnabled() const { + if (!m_owner.IsEnabled()) + return false; + else if (m_options_ap.get() != nullptr) + return m_options_ap->IsEnabled(); + else + return true; } -void -BreakpointLocation::SetEnabled (bool enabled) -{ - GetLocationOptions()->SetEnabled(enabled); - if (enabled) - { - ResolveBreakpointSite(); - } - else - { - ClearBreakpointSite(); - } - SendBreakpointLocationChangedEvent (enabled ? eBreakpointEventTypeEnabled : eBreakpointEventTypeDisabled); +void BreakpointLocation::SetEnabled(bool enabled) { + GetLocationOptions()->SetEnabled(enabled); + if (enabled) { + ResolveBreakpointSite(); + } else { + ClearBreakpointSite(); + } + SendBreakpointLocationChangedEvent(enabled ? eBreakpointEventTypeEnabled + : eBreakpointEventTypeDisabled); } -void -BreakpointLocation::SetThreadID (lldb::tid_t thread_id) -{ - if (thread_id != LLDB_INVALID_THREAD_ID) - GetLocationOptions()->SetThreadID(thread_id); - else - { - // If we're resetting this to an invalid thread id, then - // don't make an options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->SetThreadID (thread_id); - } - SendBreakpointLocationChangedEvent (eBreakpointEventTypeThreadChanged); +void BreakpointLocation::SetThreadID(lldb::tid_t thread_id) { + if (thread_id != LLDB_INVALID_THREAD_ID) + GetLocationOptions()->SetThreadID(thread_id); + else { + // If we're resetting this to an invalid thread id, then + // don't make an options pointer just to do that. + if (m_options_ap.get() != nullptr) + m_options_ap->SetThreadID(thread_id); + } + SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } -lldb::tid_t -BreakpointLocation::GetThreadID () -{ - if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) - return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetTID(); - else - return LLDB_INVALID_THREAD_ID; +lldb::tid_t BreakpointLocation::GetThreadID() { + if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) + return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetTID(); + else + return LLDB_INVALID_THREAD_ID; } -void -BreakpointLocation::SetThreadIndex (uint32_t index) -{ - if (index != 0) - GetLocationOptions()->GetThreadSpec()->SetIndex(index); - else - { - // If we're resetting this to an invalid thread id, then - // don't make an options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetIndex(index); - } - SendBreakpointLocationChangedEvent (eBreakpointEventTypeThreadChanged); +void BreakpointLocation::SetThreadIndex(uint32_t index) { + if (index != 0) + GetLocationOptions()->GetThreadSpec()->SetIndex(index); + else { + // If we're resetting this to an invalid thread id, then + // don't make an options pointer just to do that. + if (m_options_ap.get() != nullptr) + m_options_ap->GetThreadSpec()->SetIndex(index); + } + SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } -uint32_t -BreakpointLocation::GetThreadIndex() const -{ - if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) - return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetIndex(); - else - return 0; +uint32_t BreakpointLocation::GetThreadIndex() const { + if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) + return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetIndex(); + else + return 0; } -void -BreakpointLocation::SetThreadName (const char *thread_name) -{ - if (thread_name != nullptr) - GetLocationOptions()->GetThreadSpec()->SetName(thread_name); - else - { - // If we're resetting this to an invalid thread id, then - // don't make an options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetName(thread_name); - } - SendBreakpointLocationChangedEvent (eBreakpointEventTypeThreadChanged); +void BreakpointLocation::SetThreadName(const char *thread_name) { + if (thread_name != nullptr) + GetLocationOptions()->GetThreadSpec()->SetName(thread_name); + else { + // If we're resetting this to an invalid thread id, then + // don't make an options pointer just to do that. + if (m_options_ap.get() != nullptr) + m_options_ap->GetThreadSpec()->SetName(thread_name); + } + SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } -const char * -BreakpointLocation::GetThreadName () const -{ - if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) - return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetName(); - else - return nullptr; +const char *BreakpointLocation::GetThreadName() const { + if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) + return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetName(); + else + return nullptr; } -void -BreakpointLocation::SetQueueName (const char *queue_name) -{ - if (queue_name != nullptr) - GetLocationOptions()->GetThreadSpec()->SetQueueName(queue_name); - else - { - // If we're resetting this to an invalid thread id, then - // don't make an options pointer just to do that. - if (m_options_ap.get() != nullptr) - m_options_ap->GetThreadSpec()->SetQueueName(queue_name); - } - SendBreakpointLocationChangedEvent (eBreakpointEventTypeThreadChanged); +void BreakpointLocation::SetQueueName(const char *queue_name) { + if (queue_name != nullptr) + GetLocationOptions()->GetThreadSpec()->SetQueueName(queue_name); + else { + // If we're resetting this to an invalid thread id, then + // don't make an options pointer just to do that. + if (m_options_ap.get() != nullptr) + m_options_ap->GetThreadSpec()->SetQueueName(queue_name); + } + SendBreakpointLocationChangedEvent(eBreakpointEventTypeThreadChanged); } -const char * -BreakpointLocation::GetQueueName () const -{ - if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) - return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetQueueName(); - else - return nullptr; +const char *BreakpointLocation::GetQueueName() const { + if (GetOptionsNoCreate()->GetThreadSpecNoCreate()) + return GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetQueueName(); + else + return nullptr; } -bool -BreakpointLocation::InvokeCallback (StoppointCallbackContext *context) -{ - if (m_options_ap.get() != nullptr && m_options_ap->HasCallback()) - return m_options_ap->InvokeCallback (context, m_owner.GetID(), GetID()); - else - return m_owner.InvokeCallback (context, GetID()); +bool BreakpointLocation::InvokeCallback(StoppointCallbackContext *context) { + if (m_options_ap.get() != nullptr && m_options_ap->HasCallback()) + return m_options_ap->InvokeCallback(context, m_owner.GetID(), GetID()); + else + return m_owner.InvokeCallback(context, GetID()); } -void -BreakpointLocation::SetCallback (BreakpointHitCallback callback, void *baton, - bool is_synchronous) -{ - // The default "Baton" class will keep a copy of "baton" and won't free - // or delete it when it goes goes out of scope. - GetLocationOptions()->SetCallback(callback, BatonSP (new Baton(baton)), is_synchronous); - SendBreakpointLocationChangedEvent (eBreakpointEventTypeCommandChanged); +void BreakpointLocation::SetCallback(BreakpointHitCallback callback, + void *baton, bool is_synchronous) { + // The default "Baton" class will keep a copy of "baton" and won't free + // or delete it when it goes goes out of scope. + GetLocationOptions()->SetCallback(callback, BatonSP(new Baton(baton)), + is_synchronous); + SendBreakpointLocationChangedEvent(eBreakpointEventTypeCommandChanged); } -void -BreakpointLocation::SetCallback (BreakpointHitCallback callback, const BatonSP &baton_sp, - bool is_synchronous) -{ - GetLocationOptions()->SetCallback (callback, baton_sp, is_synchronous); - SendBreakpointLocationChangedEvent (eBreakpointEventTypeCommandChanged); +void BreakpointLocation::SetCallback(BreakpointHitCallback callback, + const BatonSP &baton_sp, + bool is_synchronous) { + GetLocationOptions()->SetCallback(callback, baton_sp, is_synchronous); + SendBreakpointLocationChangedEvent(eBreakpointEventTypeCommandChanged); } -void -BreakpointLocation::ClearCallback () -{ - GetLocationOptions()->ClearCallback(); +void BreakpointLocation::ClearCallback() { + GetLocationOptions()->ClearCallback(); } -void -BreakpointLocation::SetCondition (const char *condition) -{ - GetLocationOptions()->SetCondition (condition); - SendBreakpointLocationChangedEvent (eBreakpointEventTypeConditionChanged); +void BreakpointLocation::SetCondition(const char *condition) { + GetLocationOptions()->SetCondition(condition); + SendBreakpointLocationChangedEvent(eBreakpointEventTypeConditionChanged); } -const char * -BreakpointLocation::GetConditionText (size_t *hash) const -{ - return GetOptionsNoCreate()->GetConditionText(hash); +const char *BreakpointLocation::GetConditionText(size_t *hash) const { + return GetOptionsNoCreate()->GetConditionText(hash); } -bool -BreakpointLocation::ConditionSaysStop (ExecutionContext &exe_ctx, Error &error) -{ - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS); +bool BreakpointLocation::ConditionSaysStop(ExecutionContext &exe_ctx, + Error &error) { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS); + + std::lock_guard guard(m_condition_mutex); - std::lock_guard guard(m_condition_mutex); + size_t condition_hash; + const char *condition_text = GetConditionText(&condition_hash); - size_t condition_hash; - const char *condition_text = GetConditionText(&condition_hash); - - if (!condition_text) - { - m_user_expression_sp.reset(); - return false; + if (!condition_text) { + m_user_expression_sp.reset(); + return false; + } + + error.Clear(); + + DiagnosticManager diagnostics; + + if (condition_hash != m_condition_hash || !m_user_expression_sp || + !m_user_expression_sp->MatchesContext(exe_ctx)) { + LanguageType language = eLanguageTypeUnknown; + // See if we can figure out the language from the frame, otherwise use the + // default language: + CompileUnit *comp_unit = m_address.CalculateSymbolContextCompileUnit(); + if (comp_unit) + language = comp_unit->GetLanguage(); + + m_user_expression_sp.reset(GetTarget().GetUserExpressionForLanguage( + condition_text, nullptr, language, Expression::eResultTypeAny, + EvaluateExpressionOptions(), error)); + if (error.Fail()) { + if (log) + log->Printf("Error getting condition expression: %s.", + error.AsCString()); + m_user_expression_sp.reset(); + return true; } - error.Clear(); - - DiagnosticManager diagnostics; - - if (condition_hash != m_condition_hash || !m_user_expression_sp || !m_user_expression_sp->MatchesContext(exe_ctx)) - { - LanguageType language = eLanguageTypeUnknown; - // See if we can figure out the language from the frame, otherwise use the default language: - CompileUnit *comp_unit = m_address.CalculateSymbolContextCompileUnit(); - if (comp_unit) - language = comp_unit->GetLanguage(); - - m_user_expression_sp.reset(GetTarget().GetUserExpressionForLanguage(condition_text, - nullptr, - language, - Expression::eResultTypeAny, - EvaluateExpressionOptions(), - error)); - if (error.Fail()) - { - if (log) - log->Printf("Error getting condition expression: %s.", error.AsCString()); - m_user_expression_sp.reset(); - return true; - } + if (!m_user_expression_sp->Parse(diagnostics, exe_ctx, + eExecutionPolicyOnlyWhenNeeded, true, + false)) { + error.SetErrorStringWithFormat( + "Couldn't parse conditional expression:\n%s", + diagnostics.GetString().c_str()); + m_user_expression_sp.reset(); + return true; + } - if (!m_user_expression_sp->Parse(diagnostics, exe_ctx, eExecutionPolicyOnlyWhenNeeded, true, false)) - { - error.SetErrorStringWithFormat("Couldn't parse conditional expression:\n%s", - diagnostics.GetString().c_str()); - m_user_expression_sp.reset(); - return true; - } + m_condition_hash = condition_hash; + } + + // We need to make sure the user sees any parse errors in their condition, so + // we'll hook the + // constructor errors up to the debugger's Async I/O. + + ValueObjectSP result_value_sp; + + EvaluateExpressionOptions options; + options.SetUnwindOnError(true); + options.SetIgnoreBreakpoints(true); + options.SetTryAllThreads(true); + options.SetResultIsInternal( + true); // Don't generate a user variable for condition expressions. + + Error expr_error; + + diagnostics.Clear(); - m_condition_hash = condition_hash; + ExpressionVariableSP result_variable_sp; + + ExpressionResults result_code = m_user_expression_sp->Execute( + diagnostics, exe_ctx, options, m_user_expression_sp, result_variable_sp); + + bool ret; + + if (result_code == eExpressionCompleted) { + if (!result_variable_sp) { + error.SetErrorString("Expression did not return a result"); + return false; } - // We need to make sure the user sees any parse errors in their condition, so we'll hook the - // constructor errors up to the debugger's Async I/O. - - ValueObjectSP result_value_sp; - - EvaluateExpressionOptions options; - options.SetUnwindOnError(true); - options.SetIgnoreBreakpoints(true); - options.SetTryAllThreads(true); - options.SetResultIsInternal(true); // Don't generate a user variable for condition expressions. - - Error expr_error; - - diagnostics.Clear(); - - ExpressionVariableSP result_variable_sp; - - ExpressionResults result_code = - m_user_expression_sp->Execute(diagnostics, exe_ctx, options, m_user_expression_sp, result_variable_sp); - - bool ret; - - if (result_code == eExpressionCompleted) - { - if (!result_variable_sp) - { - error.SetErrorString("Expression did not return a result"); - return false; - } - - result_value_sp = result_variable_sp->GetValueObject(); - - if (result_value_sp) - { - ret = result_value_sp->IsLogicalTrue(error); - if (log) - { - if (error.Success()) - { - log->Printf("Condition successfully evaluated, result is %s.\n", - ret ? "true" : "false"); - } - else - { - error.SetErrorString("Failed to get an integer result from the expression"); - ret = false; - } - - } + result_value_sp = result_variable_sp->GetValueObject(); + + if (result_value_sp) { + ret = result_value_sp->IsLogicalTrue(error); + if (log) { + if (error.Success()) { + log->Printf("Condition successfully evaluated, result is %s.\n", + ret ? "true" : "false"); + } else { + error.SetErrorString( + "Failed to get an integer result from the expression"); + ret = false; } - else - { - ret = false; - error.SetErrorString("Failed to get any result from the expression"); - } - } - else - { - ret = false; - error.SetErrorStringWithFormat("Couldn't execute expression:\n%s", diagnostics.GetString().c_str()); + } + } else { + ret = false; + error.SetErrorString("Failed to get any result from the expression"); } + } else { + ret = false; + error.SetErrorStringWithFormat("Couldn't execute expression:\n%s", + diagnostics.GetString().c_str()); + } - return ret; + return ret; } -uint32_t -BreakpointLocation::GetIgnoreCount () -{ - return GetOptionsNoCreate()->GetIgnoreCount(); +uint32_t BreakpointLocation::GetIgnoreCount() { + return GetOptionsNoCreate()->GetIgnoreCount(); } -void -BreakpointLocation::SetIgnoreCount (uint32_t n) -{ - GetLocationOptions()->SetIgnoreCount(n); - SendBreakpointLocationChangedEvent (eBreakpointEventTypeIgnoreChanged); +void BreakpointLocation::SetIgnoreCount(uint32_t n) { + GetLocationOptions()->SetIgnoreCount(n); + SendBreakpointLocationChangedEvent(eBreakpointEventTypeIgnoreChanged); } -void -BreakpointLocation::DecrementIgnoreCount() -{ - if (m_options_ap.get() != nullptr) - { - uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); - if (loc_ignore != 0) - m_options_ap->SetIgnoreCount(loc_ignore - 1); - } +void BreakpointLocation::DecrementIgnoreCount() { + if (m_options_ap.get() != nullptr) { + uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); + if (loc_ignore != 0) + m_options_ap->SetIgnoreCount(loc_ignore - 1); + } } -bool -BreakpointLocation::IgnoreCountShouldStop() -{ - if (m_options_ap.get() != nullptr) - { - uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); - if (loc_ignore != 0) - { - m_owner.DecrementIgnoreCount(); - DecrementIgnoreCount(); // Have to decrement our owners' ignore count, since it won't get a - // chance to. - return false; - } +bool BreakpointLocation::IgnoreCountShouldStop() { + if (m_options_ap.get() != nullptr) { + uint32_t loc_ignore = m_options_ap->GetIgnoreCount(); + if (loc_ignore != 0) { + m_owner.DecrementIgnoreCount(); + DecrementIgnoreCount(); // Have to decrement our owners' ignore count, + // since it won't get a + // chance to. + return false; } - return true; + } + return true; } -const BreakpointOptions * -BreakpointLocation::GetOptionsNoCreate () const -{ - if (m_options_ap.get() != nullptr) - return m_options_ap.get(); - else - return m_owner.GetOptions (); -} - -BreakpointOptions * -BreakpointLocation::GetLocationOptions () -{ - // If we make the copy we don't copy the callbacks because that is potentially - // expensive and we don't want to do that for the simple case where someone is - // just disabling the location. - if (m_options_ap.get() == nullptr) - m_options_ap.reset(BreakpointOptions::CopyOptionsNoCallback(*m_owner.GetOptions ())); - +const BreakpointOptions *BreakpointLocation::GetOptionsNoCreate() const { + if (m_options_ap.get() != nullptr) return m_options_ap.get(); + else + return m_owner.GetOptions(); +} + +BreakpointOptions *BreakpointLocation::GetLocationOptions() { + // If we make the copy we don't copy the callbacks because that is potentially + // expensive and we don't want to do that for the simple case where someone is + // just disabling the location. + if (m_options_ap.get() == nullptr) + m_options_ap.reset( + BreakpointOptions::CopyOptionsNoCallback(*m_owner.GetOptions())); + + return m_options_ap.get(); } -bool -BreakpointLocation::ValidForThisThread (Thread *thread) -{ - return thread->MatchesSpec(GetOptionsNoCreate()->GetThreadSpecNoCreate()); +bool BreakpointLocation::ValidForThisThread(Thread *thread) { + return thread->MatchesSpec(GetOptionsNoCreate()->GetThreadSpecNoCreate()); } // RETURNS - true if we should stop at this breakpoint, false if we @@ -447,309 +362,275 @@ BreakpointLocation::ValidForThisThread (Thread *thread) // here, since if the breakpoint is not for this thread, then the event won't // even get reported, so the check is redundant. -bool -BreakpointLocation::ShouldStop (StoppointCallbackContext *context) -{ - bool should_stop = true; - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS); - - // Do this first, if a location is disabled, it shouldn't increment its hit count. - if (!IsEnabled()) - return false; - - if (!IgnoreCountShouldStop()) - return false; - - if (!m_owner.IgnoreCountShouldStop()) - return false; - - // We only run synchronous callbacks in ShouldStop: - context->is_synchronous = true; - should_stop = InvokeCallback (context); - - if (log) - { - StreamString s; - GetDescription (&s, lldb::eDescriptionLevelVerbose); - log->Printf ("Hit breakpoint location: %s, %s.\n", s.GetData(), should_stop ? "stopping" : "continuing"); - } - - return should_stop; -} - -void -BreakpointLocation::BumpHitCount() -{ - if (IsEnabled()) - { - // Step our hit count, and also step the hit count of the owner. - IncrementHitCount(); - m_owner.IncrementHitCount(); - } +bool BreakpointLocation::ShouldStop(StoppointCallbackContext *context) { + bool should_stop = true; + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS); + + // Do this first, if a location is disabled, it shouldn't increment its hit + // count. + if (!IsEnabled()) + return false; + + if (!IgnoreCountShouldStop()) + return false; + + if (!m_owner.IgnoreCountShouldStop()) + return false; + + // We only run synchronous callbacks in ShouldStop: + context->is_synchronous = true; + should_stop = InvokeCallback(context); + + if (log) { + StreamString s; + GetDescription(&s, lldb::eDescriptionLevelVerbose); + log->Printf("Hit breakpoint location: %s, %s.\n", s.GetData(), + should_stop ? "stopping" : "continuing"); + } + + return should_stop; } -void -BreakpointLocation::UndoBumpHitCount() -{ - if (IsEnabled()) - { - // Step our hit count, and also step the hit count of the owner. - DecrementHitCount(); - m_owner.DecrementHitCount(); - } +void BreakpointLocation::BumpHitCount() { + if (IsEnabled()) { + // Step our hit count, and also step the hit count of the owner. + IncrementHitCount(); + m_owner.IncrementHitCount(); + } } -bool -BreakpointLocation::IsResolved () const -{ - return m_bp_site_sp.get() != nullptr; +void BreakpointLocation::UndoBumpHitCount() { + if (IsEnabled()) { + // Step our hit count, and also step the hit count of the owner. + DecrementHitCount(); + m_owner.DecrementHitCount(); + } } -lldb::BreakpointSiteSP -BreakpointLocation::GetBreakpointSite() const -{ - return m_bp_site_sp; +bool BreakpointLocation::IsResolved() const { + return m_bp_site_sp.get() != nullptr; } -bool -BreakpointLocation::ResolveBreakpointSite () -{ - if (m_bp_site_sp) - return true; +lldb::BreakpointSiteSP BreakpointLocation::GetBreakpointSite() const { + return m_bp_site_sp; +} - Process *process = m_owner.GetTarget().GetProcessSP().get(); - if (process == nullptr) - return false; +bool BreakpointLocation::ResolveBreakpointSite() { + if (m_bp_site_sp) + return true; - lldb::break_id_t new_id = process->CreateBreakpointSite (shared_from_this(), m_owner.IsHardware()); + Process *process = m_owner.GetTarget().GetProcessSP().get(); + if (process == nullptr) + return false; - if (new_id == LLDB_INVALID_BREAK_ID) - { - Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS); - if (log) - log->Warning ("Tried to add breakpoint site at 0x%" PRIx64 " but it was already present.\n", - m_address.GetOpcodeLoadAddress (&m_owner.GetTarget())); - return false; - } + lldb::break_id_t new_id = + process->CreateBreakpointSite(shared_from_this(), m_owner.IsHardware()); - return true; -} + if (new_id == LLDB_INVALID_BREAK_ID) { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS); + if (log) + log->Warning("Tried to add breakpoint site at 0x%" PRIx64 + " but it was already present.\n", + m_address.GetOpcodeLoadAddress(&m_owner.GetTarget())); + return false; + } -bool -BreakpointLocation::SetBreakpointSite (BreakpointSiteSP& bp_site_sp) -{ - m_bp_site_sp = bp_site_sp; - SendBreakpointLocationChangedEvent (eBreakpointEventTypeLocationsResolved); - return true; + return true; } -bool -BreakpointLocation::ClearBreakpointSite () -{ - if (m_bp_site_sp.get()) - { - ProcessSP process_sp(m_owner.GetTarget().GetProcessSP()); - // If the process exists, get it to remove the owner, it will remove the physical implementation - // of the breakpoint as well if there are no more owners. Otherwise just remove this owner. - if (process_sp) - process_sp->RemoveOwnerFromBreakpointSite (GetBreakpoint().GetID(), - GetID(), m_bp_site_sp); - else - m_bp_site_sp->RemoveOwner(GetBreakpoint().GetID(), GetID()); - - m_bp_site_sp.reset(); - return true; - } - return false; +bool BreakpointLocation::SetBreakpointSite(BreakpointSiteSP &bp_site_sp) { + m_bp_site_sp = bp_site_sp; + SendBreakpointLocationChangedEvent(eBreakpointEventTypeLocationsResolved); + return true; } -void -BreakpointLocation::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - SymbolContext sc; - - // If the description level is "initial" then the breakpoint is printing out our initial state, - // and we should let it decide how it wants to print our label. - if (level != eDescriptionLevelInitial) - { - s->Indent(); - BreakpointID::GetCanonicalReference(s, m_owner.GetID(), GetID()); - } - - if (level == lldb::eDescriptionLevelBrief) - return; - - if (level != eDescriptionLevelInitial) - s->PutCString(": "); - - if (level == lldb::eDescriptionLevelVerbose) - s->IndentMore(); - - if (m_address.IsSectionOffset()) - { - m_address.CalculateSymbolContext(&sc); - - if (level == lldb::eDescriptionLevelFull || level == eDescriptionLevelInitial) - { - if (IsReExported()) - s->PutCString ("re-exported target = "); - else - s->PutCString("where = "); - sc.DumpStopContext (s, m_owner.GetTarget().GetProcessSP().get(), m_address, false, true, false, true, true); - } - else - { - if (sc.module_sp) - { - s->EOL(); - s->Indent("module = "); - sc.module_sp->GetFileSpec().Dump (s); - } - - if (sc.comp_unit != nullptr) - { - s->EOL(); - s->Indent("compile unit = "); - static_cast(sc.comp_unit)->GetFilename().Dump (s); - - if (sc.function != nullptr) - { - s->EOL(); - s->Indent("function = "); - s->PutCString (sc.function->GetName().AsCString("")); - } - - if (sc.line_entry.line > 0) - { - s->EOL(); - s->Indent("location = "); - sc.line_entry.DumpStopContext (s, true); - } - - } - else - { - // If we don't have a comp unit, see if we have a symbol we can print. - if (sc.symbol) - { - s->EOL(); - if (IsReExported()) - s->Indent ("re-exported target = "); - else - s->Indent("symbol = "); - s->PutCString(sc.symbol->GetName().AsCString("")); - } - } - } - } +bool BreakpointLocation::ClearBreakpointSite() { + if (m_bp_site_sp.get()) { + ProcessSP process_sp(m_owner.GetTarget().GetProcessSP()); + // If the process exists, get it to remove the owner, it will remove the + // physical implementation + // of the breakpoint as well if there are no more owners. Otherwise just + // remove this owner. + if (process_sp) + process_sp->RemoveOwnerFromBreakpointSite(GetBreakpoint().GetID(), + GetID(), m_bp_site_sp); + else + m_bp_site_sp->RemoveOwner(GetBreakpoint().GetID(), GetID()); - if (level == lldb::eDescriptionLevelVerbose) - { + m_bp_site_sp.reset(); + return true; + } + return false; +} + +void BreakpointLocation::GetDescription(Stream *s, + lldb::DescriptionLevel level) { + SymbolContext sc; + + // If the description level is "initial" then the breakpoint is printing out + // our initial state, + // and we should let it decide how it wants to print our label. + if (level != eDescriptionLevelInitial) { + s->Indent(); + BreakpointID::GetCanonicalReference(s, m_owner.GetID(), GetID()); + } + + if (level == lldb::eDescriptionLevelBrief) + return; + + if (level != eDescriptionLevelInitial) + s->PutCString(": "); + + if (level == lldb::eDescriptionLevelVerbose) + s->IndentMore(); + + if (m_address.IsSectionOffset()) { + m_address.CalculateSymbolContext(&sc); + + if (level == lldb::eDescriptionLevelFull || + level == eDescriptionLevelInitial) { + if (IsReExported()) + s->PutCString("re-exported target = "); + else + s->PutCString("where = "); + sc.DumpStopContext(s, m_owner.GetTarget().GetProcessSP().get(), m_address, + false, true, false, true, true); + } else { + if (sc.module_sp) { s->EOL(); - s->Indent(); - } - - if (m_address.IsSectionOffset() && (level == eDescriptionLevelFull || level == eDescriptionLevelInitial)) - s->Printf (", "); - s->Printf ("address = "); - - ExecutionContextScope *exe_scope = nullptr; - Target *target = &m_owner.GetTarget(); - if (target) - exe_scope = target->GetProcessSP().get(); - if (exe_scope == nullptr) - exe_scope = target; - - if (level == eDescriptionLevelInitial) - m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleFileAddress); - else - m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress); - - if (IsIndirect() && m_bp_site_sp) - { - Address resolved_address; - resolved_address.SetLoadAddress(m_bp_site_sp->GetLoadAddress(), target); - Symbol *resolved_symbol = resolved_address.CalculateSymbolContextSymbol(); - if (resolved_symbol) - { - if (level == eDescriptionLevelFull || level == eDescriptionLevelInitial) - s->Printf (", "); - else if (level == lldb::eDescriptionLevelVerbose) - { - s->EOL(); - s->Indent(); - } - s->Printf ("indirect target = %s", resolved_symbol->GetName().GetCString()); - } - } + s->Indent("module = "); + sc.module_sp->GetFileSpec().Dump(s); + } - if (level == lldb::eDescriptionLevelVerbose) - { + if (sc.comp_unit != nullptr) { s->EOL(); - s->Indent(); - s->Printf("resolved = %s\n", IsResolved() ? "true" : "false"); + s->Indent("compile unit = "); + static_cast(sc.comp_unit)->GetFilename().Dump(s); - s->Indent(); - s->Printf ("hit count = %-4u\n", GetHitCount()); + if (sc.function != nullptr) { + s->EOL(); + s->Indent("function = "); + s->PutCString(sc.function->GetName().AsCString("")); + } - if (m_options_ap.get()) - { - s->Indent(); - m_options_ap->GetDescription (s, level); - s->EOL(); + if (sc.line_entry.line > 0) { + s->EOL(); + s->Indent("location = "); + sc.line_entry.DumpStopContext(s, true); } - s->IndentLess(); - } - else if (level != eDescriptionLevelInitial) - { - s->Printf(", %sresolved, hit count = %u ", - (IsResolved() ? "" : "un"), - GetHitCount()); - if (m_options_ap.get()) - { - m_options_ap->GetDescription (s, level); + + } else { + // If we don't have a comp unit, see if we have a symbol we can print. + if (sc.symbol) { + s->EOL(); + if (IsReExported()) + s->Indent("re-exported target = "); + else + s->Indent("symbol = "); + s->PutCString(sc.symbol->GetName().AsCString("")); } + } } -} - -void -BreakpointLocation::Dump(Stream *s) const -{ - if (s == nullptr) - return; - - s->Printf("BreakpointLocation %u: tid = %4.4" PRIx64 " load addr = 0x%8.8" PRIx64 " state = %s type = %s breakpoint " - "hw_index = %i hit_count = %-4u ignore_count = %-4u", - GetID(), - GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetTID(), - (uint64_t) m_address.GetOpcodeLoadAddress (&m_owner.GetTarget()), - (m_options_ap.get() ? m_options_ap->IsEnabled() : m_owner.IsEnabled()) ? "enabled " : "disabled", - IsHardware() ? "hardware" : "software", - GetHardwareIndex(), - GetHitCount(), - GetOptionsNoCreate()->GetIgnoreCount()); -} - -void -BreakpointLocation::SendBreakpointLocationChangedEvent (lldb::BreakpointEventType eventKind) -{ - if (!m_being_created - && !m_owner.IsInternal() - && m_owner.GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - { - Breakpoint::BreakpointEventData *data = new Breakpoint::BreakpointEventData (eventKind, - m_owner.shared_from_this()); - data->GetBreakpointLocationCollection().Add (shared_from_this()); - m_owner.GetTarget().BroadcastEvent (Target::eBroadcastBitBreakpointChanged, data); + } + + if (level == lldb::eDescriptionLevelVerbose) { + s->EOL(); + s->Indent(); + } + + if (m_address.IsSectionOffset() && + (level == eDescriptionLevelFull || level == eDescriptionLevelInitial)) + s->Printf(", "); + s->Printf("address = "); + + ExecutionContextScope *exe_scope = nullptr; + Target *target = &m_owner.GetTarget(); + if (target) + exe_scope = target->GetProcessSP().get(); + if (exe_scope == nullptr) + exe_scope = target; + + if (level == eDescriptionLevelInitial) + m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, + Address::DumpStyleFileAddress); + else + m_address.Dump(s, exe_scope, Address::DumpStyleLoadAddress, + Address::DumpStyleModuleWithFileAddress); + + if (IsIndirect() && m_bp_site_sp) { + Address resolved_address; + resolved_address.SetLoadAddress(m_bp_site_sp->GetLoadAddress(), target); + Symbol *resolved_symbol = resolved_address.CalculateSymbolContextSymbol(); + if (resolved_symbol) { + if (level == eDescriptionLevelFull || level == eDescriptionLevelInitial) + s->Printf(", "); + else if (level == lldb::eDescriptionLevelVerbose) { + s->EOL(); + s->Indent(); + } + s->Printf("indirect target = %s", + resolved_symbol->GetName().GetCString()); } -} + } -void -BreakpointLocation::SwapLocation (BreakpointLocationSP swap_from) -{ - m_address = swap_from->m_address; - m_should_resolve_indirect_functions = swap_from->m_should_resolve_indirect_functions; - m_is_reexported = swap_from->m_is_reexported; - m_is_indirect = swap_from->m_is_indirect; - m_user_expression_sp.reset(); + if (level == lldb::eDescriptionLevelVerbose) { + s->EOL(); + s->Indent(); + s->Printf("resolved = %s\n", IsResolved() ? "true" : "false"); + + s->Indent(); + s->Printf("hit count = %-4u\n", GetHitCount()); + + if (m_options_ap.get()) { + s->Indent(); + m_options_ap->GetDescription(s, level); + s->EOL(); + } + s->IndentLess(); + } else if (level != eDescriptionLevelInitial) { + s->Printf(", %sresolved, hit count = %u ", (IsResolved() ? "" : "un"), + GetHitCount()); + if (m_options_ap.get()) { + m_options_ap->GetDescription(s, level); + } + } +} + +void BreakpointLocation::Dump(Stream *s) const { + if (s == nullptr) + return; + + s->Printf( + "BreakpointLocation %u: tid = %4.4" PRIx64 " load addr = 0x%8.8" PRIx64 + " state = %s type = %s breakpoint " + "hw_index = %i hit_count = %-4u ignore_count = %-4u", + GetID(), GetOptionsNoCreate()->GetThreadSpecNoCreate()->GetTID(), + (uint64_t)m_address.GetOpcodeLoadAddress(&m_owner.GetTarget()), + (m_options_ap.get() ? m_options_ap->IsEnabled() : m_owner.IsEnabled()) + ? "enabled " + : "disabled", + IsHardware() ? "hardware" : "software", GetHardwareIndex(), GetHitCount(), + GetOptionsNoCreate()->GetIgnoreCount()); +} + +void BreakpointLocation::SendBreakpointLocationChangedEvent( + lldb::BreakpointEventType eventKind) { + if (!m_being_created && !m_owner.IsInternal() && + m_owner.GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) { + Breakpoint::BreakpointEventData *data = new Breakpoint::BreakpointEventData( + eventKind, m_owner.shared_from_this()); + data->GetBreakpointLocationCollection().Add(shared_from_this()); + m_owner.GetTarget().BroadcastEvent(Target::eBroadcastBitBreakpointChanged, + data); + } +} + +void BreakpointLocation::SwapLocation(BreakpointLocationSP swap_from) { + m_address = swap_from->m_address; + m_should_resolve_indirect_functions = + swap_from->m_should_resolve_indirect_functions; + m_is_reexported = swap_from->m_is_reexported; + m_is_indirect = swap_from->m_is_indirect; + m_user_expression_sp.reset(); } diff --git a/lldb/source/Breakpoint/BreakpointLocationCollection.cpp b/lldb/source/Breakpoint/BreakpointLocationCollection.cpp index 52698b2f15b..6536002bda6 100644 --- a/lldb/source/Breakpoint/BreakpointLocationCollection.cpp +++ b/lldb/source/Breakpoint/BreakpointLocationCollection.cpp @@ -7,15 +7,14 @@ // //===----------------------------------------------------------------------===// - // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Breakpoint/BreakpointLocationCollection.h" -#include "lldb/Core/ModuleList.h" #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/ModuleList.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadSpec.h" @@ -25,189 +24,162 @@ using namespace lldb_private; //---------------------------------------------------------------------- // BreakpointLocationCollection constructor //---------------------------------------------------------------------- -BreakpointLocationCollection::BreakpointLocationCollection() : - m_break_loc_collection(), - m_collection_mutex() -{ -} +BreakpointLocationCollection::BreakpointLocationCollection() + : m_break_loc_collection(), m_collection_mutex() {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -BreakpointLocationCollection::~BreakpointLocationCollection() -{ +BreakpointLocationCollection::~BreakpointLocationCollection() {} + +void BreakpointLocationCollection::Add(const BreakpointLocationSP &bp_loc) { + std::lock_guard guard(m_collection_mutex); + BreakpointLocationSP old_bp_loc = + FindByIDPair(bp_loc->GetBreakpoint().GetID(), bp_loc->GetID()); + if (!old_bp_loc.get()) + m_break_loc_collection.push_back(bp_loc); } -void -BreakpointLocationCollection::Add(const BreakpointLocationSP &bp_loc) -{ - std::lock_guard guard(m_collection_mutex); - BreakpointLocationSP old_bp_loc = FindByIDPair (bp_loc->GetBreakpoint().GetID(), bp_loc->GetID()); - if (!old_bp_loc.get()) - m_break_loc_collection.push_back(bp_loc); +bool BreakpointLocationCollection::Remove(lldb::break_id_t bp_id, + lldb::break_id_t bp_loc_id) { + std::lock_guard guard(m_collection_mutex); + collection::iterator pos = GetIDPairIterator(bp_id, bp_loc_id); // Predicate + if (pos != m_break_loc_collection.end()) { + m_break_loc_collection.erase(pos); + return true; + } + return false; } -bool -BreakpointLocationCollection::Remove (lldb::break_id_t bp_id, lldb::break_id_t bp_loc_id) -{ - std::lock_guard guard(m_collection_mutex); - collection::iterator pos = GetIDPairIterator(bp_id, bp_loc_id); // Predicate - if (pos != m_break_loc_collection.end()) - { - m_break_loc_collection.erase(pos); - return true; - } - return false; - -} - -class BreakpointIDPairMatches -{ +class BreakpointIDPairMatches { public: - BreakpointIDPairMatches (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) : - m_break_id(break_id), - m_break_loc_id (break_loc_id) - { - } + BreakpointIDPairMatches(lldb::break_id_t break_id, + lldb::break_id_t break_loc_id) + : m_break_id(break_id), m_break_loc_id(break_loc_id) {} - bool operator() (const BreakpointLocationSP &bp_loc) const - { - return m_break_id == bp_loc->GetBreakpoint().GetID() - && m_break_loc_id == bp_loc->GetID(); - } + bool operator()(const BreakpointLocationSP &bp_loc) const { + return m_break_id == bp_loc->GetBreakpoint().GetID() && + m_break_loc_id == bp_loc->GetID(); + } private: - const lldb::break_id_t m_break_id; - const lldb::break_id_t m_break_loc_id; + const lldb::break_id_t m_break_id; + const lldb::break_id_t m_break_loc_id; }; BreakpointLocationCollection::collection::iterator -BreakpointLocationCollection::GetIDPairIterator (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) -{ - return std::find_if(m_break_loc_collection.begin(), m_break_loc_collection.end(), // Search full range - BreakpointIDPairMatches(break_id, break_loc_id)); // Predicate +BreakpointLocationCollection::GetIDPairIterator(lldb::break_id_t break_id, + lldb::break_id_t break_loc_id) { + return std::find_if( + m_break_loc_collection.begin(), + m_break_loc_collection.end(), // Search full range + BreakpointIDPairMatches(break_id, break_loc_id)); // Predicate } BreakpointLocationCollection::collection::const_iterator -BreakpointLocationCollection::GetIDPairConstIterator (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) const -{ - return std::find_if(m_break_loc_collection.begin(), m_break_loc_collection.end(), // Search full range - BreakpointIDPairMatches(break_id, break_loc_id)); // Predicate +BreakpointLocationCollection::GetIDPairConstIterator( + lldb::break_id_t break_id, lldb::break_id_t break_loc_id) const { + return std::find_if( + m_break_loc_collection.begin(), + m_break_loc_collection.end(), // Search full range + BreakpointIDPairMatches(break_id, break_loc_id)); // Predicate } BreakpointLocationSP -BreakpointLocationCollection::FindByIDPair (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) -{ - BreakpointLocationSP stop_sp; - collection::iterator pos = GetIDPairIterator(break_id, break_loc_id); - if (pos != m_break_loc_collection.end()) - stop_sp = *pos; - - return stop_sp; +BreakpointLocationCollection::FindByIDPair(lldb::break_id_t break_id, + lldb::break_id_t break_loc_id) { + BreakpointLocationSP stop_sp; + collection::iterator pos = GetIDPairIterator(break_id, break_loc_id); + if (pos != m_break_loc_collection.end()) + stop_sp = *pos; + + return stop_sp; } -const BreakpointLocationSP -BreakpointLocationCollection::FindByIDPair (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) const -{ - BreakpointLocationSP stop_sp; - collection::const_iterator pos = GetIDPairConstIterator(break_id, break_loc_id); - if (pos != m_break_loc_collection.end()) - stop_sp = *pos; - - return stop_sp; +const BreakpointLocationSP BreakpointLocationCollection::FindByIDPair( + lldb::break_id_t break_id, lldb::break_id_t break_loc_id) const { + BreakpointLocationSP stop_sp; + collection::const_iterator pos = + GetIDPairConstIterator(break_id, break_loc_id); + if (pos != m_break_loc_collection.end()) + stop_sp = *pos; + + return stop_sp; } -BreakpointLocationSP -BreakpointLocationCollection::GetByIndex (size_t i) -{ - std::lock_guard guard(m_collection_mutex); - BreakpointLocationSP stop_sp; - if (i < m_break_loc_collection.size()) - stop_sp = m_break_loc_collection[i]; - - return stop_sp; +BreakpointLocationSP BreakpointLocationCollection::GetByIndex(size_t i) { + std::lock_guard guard(m_collection_mutex); + BreakpointLocationSP stop_sp; + if (i < m_break_loc_collection.size()) + stop_sp = m_break_loc_collection[i]; + + return stop_sp; } const BreakpointLocationSP -BreakpointLocationCollection::GetByIndex (size_t i) const -{ - std::lock_guard guard(m_collection_mutex); - BreakpointLocationSP stop_sp; - if (i < m_break_loc_collection.size()) - stop_sp = m_break_loc_collection[i]; - - return stop_sp; -} +BreakpointLocationCollection::GetByIndex(size_t i) const { + std::lock_guard guard(m_collection_mutex); + BreakpointLocationSP stop_sp; + if (i < m_break_loc_collection.size()) + stop_sp = m_break_loc_collection[i]; -bool -BreakpointLocationCollection::ShouldStop (StoppointCallbackContext *context) -{ - bool shouldStop = false; - size_t i = 0; - size_t prev_size = GetSize(); - while (i < prev_size) - { - // ShouldStop can remove the breakpoint from the list - if (GetByIndex(i)->ShouldStop(context)) - shouldStop = true; - - if (prev_size == GetSize()) - i++; - prev_size = GetSize(); - } - return shouldStop; + return stop_sp; } -bool -BreakpointLocationCollection::ValidForThisThread (Thread *thread) -{ - std::lock_guard guard(m_collection_mutex); - collection::iterator pos, - begin = m_break_loc_collection.begin(), - end = m_break_loc_collection.end(); - - for (pos = begin; pos != end; ++pos) - { - if ((*pos)->ValidForThisThread (thread)) - return true; - } - return false; +bool BreakpointLocationCollection::ShouldStop( + StoppointCallbackContext *context) { + bool shouldStop = false; + size_t i = 0; + size_t prev_size = GetSize(); + while (i < prev_size) { + // ShouldStop can remove the breakpoint from the list + if (GetByIndex(i)->ShouldStop(context)) + shouldStop = true; + + if (prev_size == GetSize()) + i++; + prev_size = GetSize(); + } + return shouldStop; } -bool -BreakpointLocationCollection::IsInternal () const -{ - std::lock_guard guard(m_collection_mutex); - collection::const_iterator pos, - begin = m_break_loc_collection.begin(), - end = m_break_loc_collection.end(); - - bool is_internal = true; - - for (pos = begin; pos != end; ++pos) - { - if (!(*pos)->GetBreakpoint().IsInternal ()) - { - is_internal = false; - break; - } - } - return is_internal; +bool BreakpointLocationCollection::ValidForThisThread(Thread *thread) { + std::lock_guard guard(m_collection_mutex); + collection::iterator pos, begin = m_break_loc_collection.begin(), + end = m_break_loc_collection.end(); + + for (pos = begin; pos != end; ++pos) { + if ((*pos)->ValidForThisThread(thread)) + return true; + } + return false; } -void -BreakpointLocationCollection::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - std::lock_guard guard(m_collection_mutex); - collection::iterator pos, - begin = m_break_loc_collection.begin(), - end = m_break_loc_collection.end(); - - for (pos = begin; pos != end; ++pos) - { - if (pos != begin) - s->PutChar(' '); - (*pos)->GetDescription(s, level); +bool BreakpointLocationCollection::IsInternal() const { + std::lock_guard guard(m_collection_mutex); + collection::const_iterator pos, begin = m_break_loc_collection.begin(), + end = m_break_loc_collection.end(); + + bool is_internal = true; + + for (pos = begin; pos != end; ++pos) { + if (!(*pos)->GetBreakpoint().IsInternal()) { + is_internal = false; + break; } + } + return is_internal; } +void BreakpointLocationCollection::GetDescription( + Stream *s, lldb::DescriptionLevel level) { + std::lock_guard guard(m_collection_mutex); + collection::iterator pos, begin = m_break_loc_collection.begin(), + end = m_break_loc_collection.end(); + + for (pos = begin; pos != end; ++pos) { + if (pos != begin) + s->PutChar(' '); + (*pos)->GetDescription(s, level); + } +} diff --git a/lldb/source/Breakpoint/BreakpointLocationList.cpp b/lldb/source/Breakpoint/BreakpointLocationList.cpp index 5e56299bfe7..b4cf0c38e9c 100644 --- a/lldb/source/Breakpoint/BreakpointLocationList.cpp +++ b/lldb/source/Breakpoint/BreakpointLocationList.cpp @@ -13,8 +13,8 @@ // Project includes #include "lldb/Breakpoint/BreakpointLocationList.h" -#include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Core/Module.h" #include "lldb/Core/Section.h" @@ -25,339 +25,286 @@ using namespace lldb; using namespace lldb_private; BreakpointLocationList::BreakpointLocationList(Breakpoint &owner) - : m_owner(owner), m_locations(), m_address_to_location(), m_mutex(), m_next_id(0), m_new_location_recorder(nullptr) -{ -} + : m_owner(owner), m_locations(), m_address_to_location(), m_mutex(), + m_next_id(0), m_new_location_recorder(nullptr) {} BreakpointLocationList::~BreakpointLocationList() = default; BreakpointLocationSP -BreakpointLocationList::Create (const Address &addr, bool resolve_indirect_symbols) -{ - std::lock_guard guard(m_mutex); - // The location ID is just the size of the location list + 1 - lldb::break_id_t bp_loc_id = ++m_next_id; - BreakpointLocationSP bp_loc_sp (new BreakpointLocation (bp_loc_id, m_owner, addr, LLDB_INVALID_THREAD_ID, m_owner.IsHardware(), resolve_indirect_symbols)); - m_locations.push_back (bp_loc_sp); - m_address_to_location[addr] = bp_loc_sp; - return bp_loc_sp; +BreakpointLocationList::Create(const Address &addr, + bool resolve_indirect_symbols) { + std::lock_guard guard(m_mutex); + // The location ID is just the size of the location list + 1 + lldb::break_id_t bp_loc_id = ++m_next_id; + BreakpointLocationSP bp_loc_sp( + new BreakpointLocation(bp_loc_id, m_owner, addr, LLDB_INVALID_THREAD_ID, + m_owner.IsHardware(), resolve_indirect_symbols)); + m_locations.push_back(bp_loc_sp); + m_address_to_location[addr] = bp_loc_sp; + return bp_loc_sp; } -bool -BreakpointLocationList::ShouldStop (StoppointCallbackContext *context, lldb::break_id_t break_id) -{ - BreakpointLocationSP bp = FindByID (break_id); - if (bp) - { - // Let the BreakpointLocation decide if it should stop here (could not have - // reached it's target hit count yet, or it could have a callback - // that decided it shouldn't stop (shared library loads/unloads). - return bp->ShouldStop (context); - } - // We should stop here since this BreakpointLocation isn't valid anymore or it - // doesn't exist. - return true; +bool BreakpointLocationList::ShouldStop(StoppointCallbackContext *context, + lldb::break_id_t break_id) { + BreakpointLocationSP bp = FindByID(break_id); + if (bp) { + // Let the BreakpointLocation decide if it should stop here (could not have + // reached it's target hit count yet, or it could have a callback + // that decided it shouldn't stop (shared library loads/unloads). + return bp->ShouldStop(context); + } + // We should stop here since this BreakpointLocation isn't valid anymore or it + // doesn't exist. + return true; } -lldb::break_id_t -BreakpointLocationList::FindIDByAddress (const Address &addr) -{ - BreakpointLocationSP bp_loc_sp = FindByAddress (addr); - if (bp_loc_sp) - { - return bp_loc_sp->GetID(); - } - return LLDB_INVALID_BREAK_ID; +lldb::break_id_t BreakpointLocationList::FindIDByAddress(const Address &addr) { + BreakpointLocationSP bp_loc_sp = FindByAddress(addr); + if (bp_loc_sp) { + return bp_loc_sp->GetID(); + } + return LLDB_INVALID_BREAK_ID; } -static bool -Compare (BreakpointLocationSP lhs, lldb::break_id_t val) -{ - return lhs->GetID() < val; +static bool Compare(BreakpointLocationSP lhs, lldb::break_id_t val) { + return lhs->GetID() < val; } BreakpointLocationSP -BreakpointLocationList::FindByID (lldb::break_id_t break_id) const -{ - std::lock_guard guard(m_mutex); - collection::const_iterator end = m_locations.end(); - collection::const_iterator pos = std::lower_bound(m_locations.begin(), end, break_id, Compare); - if (pos != end && (*pos)->GetID() == break_id) - return *(pos); - else - return BreakpointLocationSP(); +BreakpointLocationList::FindByID(lldb::break_id_t break_id) const { + std::lock_guard guard(m_mutex); + collection::const_iterator end = m_locations.end(); + collection::const_iterator pos = + std::lower_bound(m_locations.begin(), end, break_id, Compare); + if (pos != end && (*pos)->GetID() == break_id) + return *(pos); + else + return BreakpointLocationSP(); } -size_t -BreakpointLocationList::FindInModule (Module *module, - BreakpointLocationCollection& bp_loc_list) -{ - std::lock_guard guard(m_mutex); - const size_t orig_size = bp_loc_list.GetSize(); - collection::iterator pos, end = m_locations.end(); - - for (pos = m_locations.begin(); pos != end; ++pos) - { - BreakpointLocationSP break_loc = (*pos); - SectionSP section_sp (break_loc->GetAddress().GetSection()); - if (section_sp && section_sp->GetModule().get() == module) - { - bp_loc_list.Add (break_loc); - } +size_t BreakpointLocationList::FindInModule( + Module *module, BreakpointLocationCollection &bp_loc_list) { + std::lock_guard guard(m_mutex); + const size_t orig_size = bp_loc_list.GetSize(); + collection::iterator pos, end = m_locations.end(); + + for (pos = m_locations.begin(); pos != end; ++pos) { + BreakpointLocationSP break_loc = (*pos); + SectionSP section_sp(break_loc->GetAddress().GetSection()); + if (section_sp && section_sp->GetModule().get() == module) { + bp_loc_list.Add(break_loc); } - return bp_loc_list.GetSize() - orig_size; + } + return bp_loc_list.GetSize() - orig_size; } const BreakpointLocationSP -BreakpointLocationList::FindByAddress (const Address &addr) const -{ - std::lock_guard guard(m_mutex); - BreakpointLocationSP bp_loc_sp; - if (!m_locations.empty()) - { - Address so_addr; - - if (addr.IsSectionOffset()) - { - so_addr = addr; - } - else - { - // Try and resolve as a load address if possible. - m_owner.GetTarget().GetSectionLoadList().ResolveLoadAddress (addr.GetOffset(), so_addr); - if (!so_addr.IsValid()) - { - // The address didn't resolve, so just set to passed in addr. - so_addr = addr; - } - } - - addr_map::const_iterator pos = m_address_to_location.find (so_addr); - if (pos != m_address_to_location.end()) - bp_loc_sp = pos->second; +BreakpointLocationList::FindByAddress(const Address &addr) const { + std::lock_guard guard(m_mutex); + BreakpointLocationSP bp_loc_sp; + if (!m_locations.empty()) { + Address so_addr; + + if (addr.IsSectionOffset()) { + so_addr = addr; + } else { + // Try and resolve as a load address if possible. + m_owner.GetTarget().GetSectionLoadList().ResolveLoadAddress( + addr.GetOffset(), so_addr); + if (!so_addr.IsValid()) { + // The address didn't resolve, so just set to passed in addr. + so_addr = addr; + } } - return bp_loc_sp; + addr_map::const_iterator pos = m_address_to_location.find(so_addr); + if (pos != m_address_to_location.end()) + bp_loc_sp = pos->second; + } + + return bp_loc_sp; } -void -BreakpointLocationList::Dump (Stream *s) const -{ - s->Printf("%p: ", static_cast(this)); - //s->Indent(); - std::lock_guard guard(m_mutex); - s->Printf("BreakpointLocationList with %" PRIu64 " BreakpointLocations:\n", (uint64_t)m_locations.size()); - s->IndentMore(); - collection::const_iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - (*pos).get()->Dump(s); - s->IndentLess(); +void BreakpointLocationList::Dump(Stream *s) const { + s->Printf("%p: ", static_cast(this)); + // s->Indent(); + std::lock_guard guard(m_mutex); + s->Printf("BreakpointLocationList with %" PRIu64 " BreakpointLocations:\n", + (uint64_t)m_locations.size()); + s->IndentMore(); + collection::const_iterator pos, end = m_locations.end(); + for (pos = m_locations.begin(); pos != end; ++pos) + (*pos).get()->Dump(s); + s->IndentLess(); } -BreakpointLocationSP -BreakpointLocationList::GetByIndex (size_t i) -{ - std::lock_guard guard(m_mutex); - BreakpointLocationSP bp_loc_sp; - if (i < m_locations.size()) - bp_loc_sp = m_locations[i]; +BreakpointLocationSP BreakpointLocationList::GetByIndex(size_t i) { + std::lock_guard guard(m_mutex); + BreakpointLocationSP bp_loc_sp; + if (i < m_locations.size()) + bp_loc_sp = m_locations[i]; - return bp_loc_sp; + return bp_loc_sp; } -const BreakpointLocationSP -BreakpointLocationList::GetByIndex (size_t i) const -{ - std::lock_guard guard(m_mutex); - BreakpointLocationSP bp_loc_sp; - if (i < m_locations.size()) - bp_loc_sp = m_locations[i]; +const BreakpointLocationSP BreakpointLocationList::GetByIndex(size_t i) const { + std::lock_guard guard(m_mutex); + BreakpointLocationSP bp_loc_sp; + if (i < m_locations.size()) + bp_loc_sp = m_locations[i]; - return bp_loc_sp; + return bp_loc_sp; } -void -BreakpointLocationList::ClearAllBreakpointSites () -{ - std::lock_guard guard(m_mutex); - collection::iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - (*pos)->ClearBreakpointSite(); +void BreakpointLocationList::ClearAllBreakpointSites() { + std::lock_guard guard(m_mutex); + collection::iterator pos, end = m_locations.end(); + for (pos = m_locations.begin(); pos != end; ++pos) + (*pos)->ClearBreakpointSite(); } -void -BreakpointLocationList::ResolveAllBreakpointSites () -{ - std::lock_guard guard(m_mutex); - collection::iterator pos, end = m_locations.end(); +void BreakpointLocationList::ResolveAllBreakpointSites() { + std::lock_guard guard(m_mutex); + collection::iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - { - if ((*pos)->IsEnabled()) - (*pos)->ResolveBreakpointSite(); - } + for (pos = m_locations.begin(); pos != end; ++pos) { + if ((*pos)->IsEnabled()) + (*pos)->ResolveBreakpointSite(); + } } -uint32_t -BreakpointLocationList::GetHitCount () const -{ - uint32_t hit_count = 0; - std::lock_guard guard(m_mutex); - collection::const_iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - hit_count += (*pos)->GetHitCount(); - return hit_count; +uint32_t BreakpointLocationList::GetHitCount() const { + uint32_t hit_count = 0; + std::lock_guard guard(m_mutex); + collection::const_iterator pos, end = m_locations.end(); + for (pos = m_locations.begin(); pos != end; ++pos) + hit_count += (*pos)->GetHitCount(); + return hit_count; } -size_t -BreakpointLocationList::GetNumResolvedLocations() const -{ - std::lock_guard guard(m_mutex); - size_t resolve_count = 0; - collection::const_iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - { - if ((*pos)->IsResolved()) - ++resolve_count; - } - return resolve_count; +size_t BreakpointLocationList::GetNumResolvedLocations() const { + std::lock_guard guard(m_mutex); + size_t resolve_count = 0; + collection::const_iterator pos, end = m_locations.end(); + for (pos = m_locations.begin(); pos != end; ++pos) { + if ((*pos)->IsResolved()) + ++resolve_count; + } + return resolve_count; } -void -BreakpointLocationList::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - std::lock_guard guard(m_mutex); - collection::iterator pos, end = m_locations.end(); +void BreakpointLocationList::GetDescription(Stream *s, + lldb::DescriptionLevel level) { + std::lock_guard guard(m_mutex); + collection::iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - { - s->Printf(" "); - (*pos)->GetDescription(s, level); - } + for (pos = m_locations.begin(); pos != end; ++pos) { + s->Printf(" "); + (*pos)->GetDescription(s, level); + } } -BreakpointLocationSP -BreakpointLocationList::AddLocation (const Address &addr, bool resolve_indirect_symbols, bool *new_location) -{ - std::lock_guard guard(m_mutex); - - if (new_location) - *new_location = false; - BreakpointLocationSP bp_loc_sp (FindByAddress(addr)); - if (!bp_loc_sp) - { - bp_loc_sp = Create (addr, resolve_indirect_symbols); - if (bp_loc_sp) - { - bp_loc_sp->ResolveBreakpointSite(); - - if (new_location) - *new_location = true; - if(m_new_location_recorder) - { - m_new_location_recorder->Add(bp_loc_sp); - } - } - } - return bp_loc_sp; +BreakpointLocationSP BreakpointLocationList::AddLocation( + const Address &addr, bool resolve_indirect_symbols, bool *new_location) { + std::lock_guard guard(m_mutex); + + if (new_location) + *new_location = false; + BreakpointLocationSP bp_loc_sp(FindByAddress(addr)); + if (!bp_loc_sp) { + bp_loc_sp = Create(addr, resolve_indirect_symbols); + if (bp_loc_sp) { + bp_loc_sp->ResolveBreakpointSite(); + + if (new_location) + *new_location = true; + if (m_new_location_recorder) { + m_new_location_recorder->Add(bp_loc_sp); + } + } + } + return bp_loc_sp; } -void -BreakpointLocationList::SwapLocation (BreakpointLocationSP to_location_sp, BreakpointLocationSP from_location_sp) -{ - if (!from_location_sp || !to_location_sp) - return; - - m_address_to_location.erase(to_location_sp->GetAddress()); - to_location_sp->SwapLocation(from_location_sp); - RemoveLocation(from_location_sp); - m_address_to_location[to_location_sp->GetAddress()] = to_location_sp; - to_location_sp->ResolveBreakpointSite(); +void BreakpointLocationList::SwapLocation( + BreakpointLocationSP to_location_sp, + BreakpointLocationSP from_location_sp) { + if (!from_location_sp || !to_location_sp) + return; + + m_address_to_location.erase(to_location_sp->GetAddress()); + to_location_sp->SwapLocation(from_location_sp); + RemoveLocation(from_location_sp); + m_address_to_location[to_location_sp->GetAddress()] = to_location_sp; + to_location_sp->ResolveBreakpointSite(); } -bool -BreakpointLocationList::RemoveLocation (const lldb::BreakpointLocationSP &bp_loc_sp) -{ - if (bp_loc_sp) - { - std::lock_guard guard(m_mutex); - - m_address_to_location.erase (bp_loc_sp->GetAddress()); - - collection::iterator pos, end = m_locations.end(); - for (pos = m_locations.begin(); pos != end; ++pos) - { - if ((*pos).get() == bp_loc_sp.get()) - { - m_locations.erase (pos); - return true; - } - } +bool BreakpointLocationList::RemoveLocation( + const lldb::BreakpointLocationSP &bp_loc_sp) { + if (bp_loc_sp) { + std::lock_guard guard(m_mutex); + + m_address_to_location.erase(bp_loc_sp->GetAddress()); + + collection::iterator pos, end = m_locations.end(); + for (pos = m_locations.begin(); pos != end; ++pos) { + if ((*pos).get() == bp_loc_sp.get()) { + m_locations.erase(pos); + return true; + } } - return false; + } + return false; } -void -BreakpointLocationList::RemoveInvalidLocations (const ArchSpec &arch) -{ - std::lock_guard guard(m_mutex); - size_t idx = 0; - // Don't cache m_location.size() as it will change since we might - // remove locations from our vector... - while (idx < m_locations.size()) - { - BreakpointLocation *bp_loc = m_locations[idx].get(); - if (bp_loc->GetAddress().SectionWasDeleted()) - { - // Section was deleted which means this breakpoint comes from a module - // that is no longer valid, so we should remove it. - m_locations.erase(m_locations.begin() + idx); - continue; - } - if (arch.IsValid()) - { - ModuleSP module_sp (bp_loc->GetAddress().GetModule()); - if (module_sp) - { - if (!arch.IsCompatibleMatch(module_sp->GetArchitecture())) - { - // The breakpoint was in a module whose architecture is no longer - // compatible with "arch", so we need to remove it - m_locations.erase(m_locations.begin() + idx); - continue; - } - } +void BreakpointLocationList::RemoveInvalidLocations(const ArchSpec &arch) { + std::lock_guard guard(m_mutex); + size_t idx = 0; + // Don't cache m_location.size() as it will change since we might + // remove locations from our vector... + while (idx < m_locations.size()) { + BreakpointLocation *bp_loc = m_locations[idx].get(); + if (bp_loc->GetAddress().SectionWasDeleted()) { + // Section was deleted which means this breakpoint comes from a module + // that is no longer valid, so we should remove it. + m_locations.erase(m_locations.begin() + idx); + continue; + } + if (arch.IsValid()) { + ModuleSP module_sp(bp_loc->GetAddress().GetModule()); + if (module_sp) { + if (!arch.IsCompatibleMatch(module_sp->GetArchitecture())) { + // The breakpoint was in a module whose architecture is no longer + // compatible with "arch", so we need to remove it + m_locations.erase(m_locations.begin() + idx); + continue; } - // Only increment the index if we didn't remove the locations at index "idx" - ++idx; + } } + // Only increment the index if we didn't remove the locations at index "idx" + ++idx; + } } -void -BreakpointLocationList::StartRecordingNewLocations (BreakpointLocationCollection &new_locations) -{ - std::lock_guard guard(m_mutex); - assert(m_new_location_recorder == nullptr); - m_new_location_recorder = &new_locations; +void BreakpointLocationList::StartRecordingNewLocations( + BreakpointLocationCollection &new_locations) { + std::lock_guard guard(m_mutex); + assert(m_new_location_recorder == nullptr); + m_new_location_recorder = &new_locations; } -void -BreakpointLocationList::StopRecordingNewLocations () -{ - std::lock_guard guard(m_mutex); - m_new_location_recorder = nullptr; +void BreakpointLocationList::StopRecordingNewLocations() { + std::lock_guard guard(m_mutex); + m_new_location_recorder = nullptr; } -void -BreakpointLocationList::Compact() -{ - lldb::break_id_t highest_id = 0; - - for (BreakpointLocationSP loc_sp : m_locations) - { - lldb::break_id_t cur_id = loc_sp->GetID(); - if (cur_id > highest_id) - highest_id = cur_id; - } - m_next_id = highest_id; +void BreakpointLocationList::Compact() { + lldb::break_id_t highest_id = 0; + + for (BreakpointLocationSP loc_sp : m_locations) { + lldb::break_id_t cur_id = loc_sp->GetID(); + if (cur_id > highest_id) + highest_id = cur_id; + } + m_next_id = highest_id; } diff --git a/lldb/source/Breakpoint/BreakpointOptions.cpp b/lldb/source/Breakpoint/BreakpointOptions.cpp index d2a91975685..bb43e3a9b86 100644 --- a/lldb/source/Breakpoint/BreakpointOptions.cpp +++ b/lldb/source/Breakpoint/BreakpointOptions.cpp @@ -13,10 +13,10 @@ // Project includes #include "lldb/Breakpoint/BreakpointOptions.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StringList.h" #include "lldb/Core/Value.h" -#include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" @@ -24,78 +24,66 @@ using namespace lldb; using namespace lldb_private; -bool -BreakpointOptions::NullCallback (void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id) -{ - return true; +bool BreakpointOptions::NullCallback(void *baton, + StoppointCallbackContext *context, + lldb::user_id_t break_id, + lldb::user_id_t break_loc_id) { + return true; } //---------------------------------------------------------------------- // BreakpointOptions constructor //---------------------------------------------------------------------- -BreakpointOptions::BreakpointOptions() : - m_callback (BreakpointOptions::NullCallback), - m_callback_baton_sp (), - m_callback_is_synchronous (false), - m_enabled (true), - m_one_shot (false), - m_ignore_count (0), - m_thread_spec_ap (), - m_condition_text (), - m_condition_text_hash (0) -{ -} +BreakpointOptions::BreakpointOptions() + : m_callback(BreakpointOptions::NullCallback), m_callback_baton_sp(), + m_callback_is_synchronous(false), m_enabled(true), m_one_shot(false), + m_ignore_count(0), m_thread_spec_ap(), m_condition_text(), + m_condition_text_hash(0) {} //---------------------------------------------------------------------- // BreakpointOptions copy constructor //---------------------------------------------------------------------- -BreakpointOptions::BreakpointOptions(const BreakpointOptions& rhs) : - m_callback (rhs.m_callback), - m_callback_baton_sp (rhs.m_callback_baton_sp), - m_callback_is_synchronous (rhs.m_callback_is_synchronous), - m_enabled (rhs.m_enabled), - m_one_shot (rhs.m_one_shot), - m_ignore_count (rhs.m_ignore_count), - m_thread_spec_ap () -{ - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get())); - m_condition_text = rhs.m_condition_text; - m_condition_text_hash = rhs.m_condition_text_hash; +BreakpointOptions::BreakpointOptions(const BreakpointOptions &rhs) + : m_callback(rhs.m_callback), m_callback_baton_sp(rhs.m_callback_baton_sp), + m_callback_is_synchronous(rhs.m_callback_is_synchronous), + m_enabled(rhs.m_enabled), m_one_shot(rhs.m_one_shot), + m_ignore_count(rhs.m_ignore_count), m_thread_spec_ap() { + if (rhs.m_thread_spec_ap.get() != nullptr) + m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + m_condition_text = rhs.m_condition_text; + m_condition_text_hash = rhs.m_condition_text_hash; } //---------------------------------------------------------------------- // BreakpointOptions assignment operator //---------------------------------------------------------------------- -const BreakpointOptions& -BreakpointOptions::operator=(const BreakpointOptions& rhs) -{ - m_callback = rhs.m_callback; - m_callback_baton_sp = rhs.m_callback_baton_sp; - m_callback_is_synchronous = rhs.m_callback_is_synchronous; - m_enabled = rhs.m_enabled; - m_one_shot = rhs.m_one_shot; - m_ignore_count = rhs.m_ignore_count; - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); - m_condition_text = rhs.m_condition_text; - m_condition_text_hash = rhs.m_condition_text_hash; - return *this; +const BreakpointOptions &BreakpointOptions:: +operator=(const BreakpointOptions &rhs) { + m_callback = rhs.m_callback; + m_callback_baton_sp = rhs.m_callback_baton_sp; + m_callback_is_synchronous = rhs.m_callback_is_synchronous; + m_enabled = rhs.m_enabled; + m_one_shot = rhs.m_one_shot; + m_ignore_count = rhs.m_ignore_count; + if (rhs.m_thread_spec_ap.get() != nullptr) + m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + m_condition_text = rhs.m_condition_text; + m_condition_text_hash = rhs.m_condition_text_hash; + return *this; } BreakpointOptions * -BreakpointOptions::CopyOptionsNoCallback (BreakpointOptions &orig) -{ - BreakpointHitCallback orig_callback = orig.m_callback; - lldb::BatonSP orig_callback_baton_sp = orig.m_callback_baton_sp; - bool orig_is_sync = orig.m_callback_is_synchronous; - - orig.ClearCallback(); - BreakpointOptions *ret_val = new BreakpointOptions(orig); - - orig.SetCallback (orig_callback, orig_callback_baton_sp, orig_is_sync); - - return ret_val; +BreakpointOptions::CopyOptionsNoCallback(BreakpointOptions &orig) { + BreakpointHitCallback orig_callback = orig.m_callback; + lldb::BatonSP orig_callback_baton_sp = orig.m_callback_baton_sp; + bool orig_is_sync = orig.m_callback_is_synchronous; + + orig.ClearCallback(); + BreakpointOptions *ret_val = new BreakpointOptions(orig); + + orig.SetCallback(orig_callback, orig_callback_baton_sp, orig_is_sync); + + return ret_val; } //---------------------------------------------------------------------- @@ -106,187 +94,148 @@ BreakpointOptions::~BreakpointOptions() = default; //------------------------------------------------------------------ // Callbacks //------------------------------------------------------------------ -void -BreakpointOptions::SetCallback (BreakpointHitCallback callback, const BatonSP &callback_baton_sp, bool callback_is_synchronous) -{ - m_callback_is_synchronous = callback_is_synchronous; - m_callback = callback; - m_callback_baton_sp = callback_baton_sp; +void BreakpointOptions::SetCallback(BreakpointHitCallback callback, + const BatonSP &callback_baton_sp, + bool callback_is_synchronous) { + m_callback_is_synchronous = callback_is_synchronous; + m_callback = callback; + m_callback_baton_sp = callback_baton_sp; } -void -BreakpointOptions::ClearCallback () -{ - m_callback = BreakpointOptions::NullCallback; - m_callback_is_synchronous = false; - m_callback_baton_sp.reset(); +void BreakpointOptions::ClearCallback() { + m_callback = BreakpointOptions::NullCallback; + m_callback_is_synchronous = false; + m_callback_baton_sp.reset(); } -Baton * -BreakpointOptions::GetBaton () -{ - return m_callback_baton_sp.get(); -} +Baton *BreakpointOptions::GetBaton() { return m_callback_baton_sp.get(); } -const Baton * -BreakpointOptions::GetBaton () const -{ - return m_callback_baton_sp.get(); +const Baton *BreakpointOptions::GetBaton() const { + return m_callback_baton_sp.get(); } -bool -BreakpointOptions::InvokeCallback (StoppointCallbackContext *context, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id) -{ - if (m_callback && context->is_synchronous == IsCallbackSynchronous()) - { - return m_callback(m_callback_baton_sp ? m_callback_baton_sp->m_data : nullptr, - context, - break_id, - break_loc_id); - } - else - return true; +bool BreakpointOptions::InvokeCallback(StoppointCallbackContext *context, + lldb::user_id_t break_id, + lldb::user_id_t break_loc_id) { + if (m_callback && context->is_synchronous == IsCallbackSynchronous()) { + return m_callback(m_callback_baton_sp ? m_callback_baton_sp->m_data + : nullptr, + context, break_id, break_loc_id); + } else + return true; } -bool -BreakpointOptions::HasCallback () const -{ - return m_callback != BreakpointOptions::NullCallback; +bool BreakpointOptions::HasCallback() const { + return m_callback != BreakpointOptions::NullCallback; } -void -BreakpointOptions::SetCondition (const char *condition) -{ - if (!condition) - condition = ""; - - m_condition_text.assign(condition); - std::hash hasher; - m_condition_text_hash = hasher(m_condition_text); +void BreakpointOptions::SetCondition(const char *condition) { + if (!condition) + condition = ""; + + m_condition_text.assign(condition); + std::hash hasher; + m_condition_text_hash = hasher(m_condition_text); } -const char * -BreakpointOptions::GetConditionText (size_t *hash) const -{ - if (!m_condition_text.empty()) - { - if (hash) - *hash = m_condition_text_hash; - - return m_condition_text.c_str(); - } - else - { - return nullptr; - } +const char *BreakpointOptions::GetConditionText(size_t *hash) const { + if (!m_condition_text.empty()) { + if (hash) + *hash = m_condition_text_hash; + + return m_condition_text.c_str(); + } else { + return nullptr; + } } -const ThreadSpec * -BreakpointOptions::GetThreadSpecNoCreate () const -{ - return m_thread_spec_ap.get(); +const ThreadSpec *BreakpointOptions::GetThreadSpecNoCreate() const { + return m_thread_spec_ap.get(); } -ThreadSpec * -BreakpointOptions::GetThreadSpec () -{ - if (m_thread_spec_ap.get() == nullptr) - m_thread_spec_ap.reset (new ThreadSpec()); - - return m_thread_spec_ap.get(); +ThreadSpec *BreakpointOptions::GetThreadSpec() { + if (m_thread_spec_ap.get() == nullptr) + m_thread_spec_ap.reset(new ThreadSpec()); + + return m_thread_spec_ap.get(); } -void -BreakpointOptions::SetThreadID (lldb::tid_t thread_id) -{ - GetThreadSpec()->SetTID(thread_id); +void BreakpointOptions::SetThreadID(lldb::tid_t thread_id) { + GetThreadSpec()->SetTID(thread_id); } -void -BreakpointOptions::GetDescription (Stream *s, lldb::DescriptionLevel level) const -{ - // Figure out if there are any options not at their default value, and only print - // anything if there are: - - if (m_ignore_count != 0 || !m_enabled || m_one_shot || (GetThreadSpecNoCreate() != nullptr && GetThreadSpecNoCreate()->HasSpecification ())) - { - if (level == lldb::eDescriptionLevelVerbose) - { - s->EOL (); - s->IndentMore(); - s->Indent(); - s->PutCString("Breakpoint Options:\n"); - s->IndentMore(); - s->Indent(); - } - else - s->PutCString(" Options: "); - - if (m_ignore_count > 0) - s->Printf("ignore: %d ", m_ignore_count); - s->Printf("%sabled ", m_enabled ? "en" : "dis"); - - if (m_one_shot) - s->Printf ("one-shot "); - - if (m_thread_spec_ap.get()) - m_thread_spec_ap->GetDescription (s, level); - - if (level == lldb::eDescriptionLevelFull) - { - s->IndentLess(); - s->IndentMore(); - } +void BreakpointOptions::GetDescription(Stream *s, + lldb::DescriptionLevel level) const { + // Figure out if there are any options not at their default value, and only + // print + // anything if there are: + + if (m_ignore_count != 0 || !m_enabled || m_one_shot || + (GetThreadSpecNoCreate() != nullptr && + GetThreadSpecNoCreate()->HasSpecification())) { + if (level == lldb::eDescriptionLevelVerbose) { + s->EOL(); + s->IndentMore(); + s->Indent(); + s->PutCString("Breakpoint Options:\n"); + s->IndentMore(); + s->Indent(); + } else + s->PutCString(" Options: "); + + if (m_ignore_count > 0) + s->Printf("ignore: %d ", m_ignore_count); + s->Printf("%sabled ", m_enabled ? "en" : "dis"); + + if (m_one_shot) + s->Printf("one-shot "); + + if (m_thread_spec_ap.get()) + m_thread_spec_ap->GetDescription(s, level); + + if (level == lldb::eDescriptionLevelFull) { + s->IndentLess(); + s->IndentMore(); } - - if (m_callback_baton_sp.get()) - { - if (level != eDescriptionLevelBrief) - { - s->EOL(); - m_callback_baton_sp->GetDescription (s, level); - } + } + + if (m_callback_baton_sp.get()) { + if (level != eDescriptionLevelBrief) { + s->EOL(); + m_callback_baton_sp->GetDescription(s, level); + } + } + if (!m_condition_text.empty()) { + if (level != eDescriptionLevelBrief) { + s->EOL(); + s->Printf("Condition: %s\n", m_condition_text.c_str()); } - if (!m_condition_text.empty()) - { - if (level != eDescriptionLevelBrief) - { - s->EOL(); - s->Printf("Condition: %s\n", m_condition_text.c_str()); - } - } + } } -void -BreakpointOptions::CommandBaton::GetDescription (Stream *s, lldb::DescriptionLevel level) const -{ - CommandData *data = (CommandData *)m_data; +void BreakpointOptions::CommandBaton::GetDescription( + Stream *s, lldb::DescriptionLevel level) const { + CommandData *data = (CommandData *)m_data; - if (level == eDescriptionLevelBrief) - { - s->Printf (", commands = %s", (data && data->user_source.GetSize() > 0) ? "yes" : "no"); - return; - } - - s->IndentMore (); - s->Indent("Breakpoint commands:\n"); - - s->IndentMore (); - if (data && data->user_source.GetSize() > 0) - { - const size_t num_strings = data->user_source.GetSize(); - for (size_t i = 0; i < num_strings; ++i) - { - s->Indent(data->user_source.GetStringAtIndex(i)); - s->EOL(); - } - } - else - { - s->PutCString ("No commands.\n"); + if (level == eDescriptionLevelBrief) { + s->Printf(", commands = %s", + (data && data->user_source.GetSize() > 0) ? "yes" : "no"); + return; + } + + s->IndentMore(); + s->Indent("Breakpoint commands:\n"); + + s->IndentMore(); + if (data && data->user_source.GetSize() > 0) { + const size_t num_strings = data->user_source.GetSize(); + for (size_t i = 0; i < num_strings; ++i) { + s->Indent(data->user_source.GetStringAtIndex(i)); + s->EOL(); } - s->IndentLess (); - s->IndentLess (); + } else { + s->PutCString("No commands.\n"); + } + s->IndentLess(); + s->IndentLess(); } diff --git a/lldb/source/Breakpoint/BreakpointResolver.cpp b/lldb/source/Breakpoint/BreakpointResolver.cpp index e757b388550..ee6e4c8fbbe 100644 --- a/lldb/source/Breakpoint/BreakpointResolver.cpp +++ b/lldb/source/Breakpoint/BreakpointResolver.cpp @@ -13,18 +13,18 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Core/Address.h" #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Core/Address.h" #include "lldb/Core/Log.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/SearchFilter.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamString.h" -#include "lldb/Symbol/SymbolContext.h" -#include "lldb/Target/Target.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Function.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Target/Target.h" using namespace lldb_private; using namespace lldb; @@ -32,196 +32,169 @@ using namespace lldb; //---------------------------------------------------------------------- // BreakpointResolver: //---------------------------------------------------------------------- -BreakpointResolver::BreakpointResolver (Breakpoint *bkpt, const unsigned char resolverTy, lldb::addr_t offset) : - m_breakpoint (bkpt), - m_offset(offset), - SubclassID (resolverTy) -{ -} +BreakpointResolver::BreakpointResolver(Breakpoint *bkpt, + const unsigned char resolverTy, + lldb::addr_t offset) + : m_breakpoint(bkpt), m_offset(offset), SubclassID(resolverTy) {} -BreakpointResolver::~BreakpointResolver () -{ +BreakpointResolver::~BreakpointResolver() {} +void BreakpointResolver::SetBreakpoint(Breakpoint *bkpt) { + m_breakpoint = bkpt; } -void -BreakpointResolver::SetBreakpoint (Breakpoint *bkpt) -{ - m_breakpoint = bkpt; +void BreakpointResolver::ResolveBreakpointInModules(SearchFilter &filter, + ModuleList &modules) { + filter.SearchInModuleList(*this, modules); } -void -BreakpointResolver::ResolveBreakpointInModules (SearchFilter &filter, ModuleList &modules) -{ - filter.SearchInModuleList(*this, modules); +void BreakpointResolver::ResolveBreakpoint(SearchFilter &filter) { + filter.Search(*this); } -void -BreakpointResolver::ResolveBreakpoint (SearchFilter &filter) -{ - filter.Search (*this); -} +void BreakpointResolver::SetSCMatchesByLine(SearchFilter &filter, + SymbolContextList &sc_list, + bool skip_prologue, + const char *log_ident) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + + while (sc_list.GetSize() > 0) { + SymbolContextList tmp_sc_list; + unsigned current_idx = 0; + SymbolContext sc; + bool first_entry = true; + + FileSpec match_file_spec; + FileSpec match_original_file_spec; + uint32_t closest_line_number = UINT32_MAX; + + // Pull out the first entry, and all the others that match its file spec, + // and stuff them in the tmp list. + while (current_idx < sc_list.GetSize()) { + bool matches; + + sc_list.GetContextAtIndex(current_idx, sc); + if (first_entry) { + match_file_spec = sc.line_entry.file; + match_original_file_spec = sc.line_entry.original_file; + matches = true; + first_entry = false; + } else + matches = ((sc.line_entry.file == match_file_spec) || + (sc.line_entry.original_file == match_original_file_spec)); + + if (matches) { + tmp_sc_list.Append(sc); + sc_list.RemoveContextAtIndex(current_idx); + + // ResolveSymbolContext will always return a number that is >= the line + // number you pass in. + // So the smaller line number is always better. + if (sc.line_entry.line < closest_line_number) + closest_line_number = sc.line_entry.line; + } else + current_idx++; + } -void -BreakpointResolver::SetSCMatchesByLine (SearchFilter &filter, SymbolContextList &sc_list, bool skip_prologue, const char *log_ident) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - - while (sc_list.GetSize() > 0) - { - SymbolContextList tmp_sc_list; - unsigned current_idx = 0; - SymbolContext sc; - bool first_entry = true; - - FileSpec match_file_spec; - FileSpec match_original_file_spec; - uint32_t closest_line_number = UINT32_MAX; - - // Pull out the first entry, and all the others that match its file spec, and stuff them in the tmp list. - while (current_idx < sc_list.GetSize()) - { - bool matches; - - sc_list.GetContextAtIndex (current_idx, sc); - if (first_entry) - { - match_file_spec = sc.line_entry.file; - match_original_file_spec = sc.line_entry.original_file; - matches = true; - first_entry = false; - } - else - matches = ((sc.line_entry.file == match_file_spec) || - (sc.line_entry.original_file == match_original_file_spec)); - - if (matches) - { - tmp_sc_list.Append (sc); - sc_list.RemoveContextAtIndex(current_idx); - - // ResolveSymbolContext will always return a number that is >= the line number you pass in. - // So the smaller line number is always better. - if (sc.line_entry.line < closest_line_number) - closest_line_number = sc.line_entry.line; - } - else - current_idx++; - } - - // Okay, we've found the closest line number match, now throw away all the others: - - current_idx = 0; - while (current_idx < tmp_sc_list.GetSize()) - { - if (tmp_sc_list.GetContextAtIndex(current_idx, sc)) - { - if (sc.line_entry.line != closest_line_number) - tmp_sc_list.RemoveContextAtIndex(current_idx); - else - current_idx++; - } - } - - // Next go through and see if there are line table entries that are contiguous, and if so keep only the - // first of the contiguous range: - - current_idx = 0; - std::map blocks_with_breakpoints; - - while (current_idx < tmp_sc_list.GetSize()) - { - if (tmp_sc_list.GetContextAtIndex(current_idx, sc)) - { - if (blocks_with_breakpoints.find (sc.block) != blocks_with_breakpoints.end()) - tmp_sc_list.RemoveContextAtIndex(current_idx); - else - { - blocks_with_breakpoints.insert (std::pair(sc.block, sc.line_entry.range.GetBaseAddress().GetFileAddress())); - current_idx++; - } - } + // Okay, we've found the closest line number match, now throw away all the + // others: + + current_idx = 0; + while (current_idx < tmp_sc_list.GetSize()) { + if (tmp_sc_list.GetContextAtIndex(current_idx, sc)) { + if (sc.line_entry.line != closest_line_number) + tmp_sc_list.RemoveContextAtIndex(current_idx); + else + current_idx++; + } + } + + // Next go through and see if there are line table entries that are + // contiguous, and if so keep only the + // first of the contiguous range: + + current_idx = 0; + std::map blocks_with_breakpoints; + + while (current_idx < tmp_sc_list.GetSize()) { + if (tmp_sc_list.GetContextAtIndex(current_idx, sc)) { + if (blocks_with_breakpoints.find(sc.block) != + blocks_with_breakpoints.end()) + tmp_sc_list.RemoveContextAtIndex(current_idx); + else { + blocks_with_breakpoints.insert(std::pair( + sc.block, sc.line_entry.range.GetBaseAddress().GetFileAddress())); + current_idx++; } - - // and make breakpoints out of the closest line number match. - - uint32_t tmp_sc_list_size = tmp_sc_list.GetSize(); - - for (uint32_t i = 0; i < tmp_sc_list_size; i++) - { - if (tmp_sc_list.GetContextAtIndex(i, sc)) - { - Address line_start = sc.line_entry.range.GetBaseAddress(); - if (line_start.IsValid()) - { - if (filter.AddressPasses(line_start)) - { - // If the line number is before the prologue end, move it there... - bool skipped_prologue = false; - if (skip_prologue) - { - if (sc.function) - { - Address prologue_addr(sc.function->GetAddressRange().GetBaseAddress()); - if (prologue_addr.IsValid() && (line_start == prologue_addr)) - { - const uint32_t prologue_byte_size = sc.function->GetPrologueByteSize(); - if (prologue_byte_size) - { - prologue_addr.Slide(prologue_byte_size); - - if (filter.AddressPasses(prologue_addr)) - { - skipped_prologue = true; - line_start = prologue_addr; - } - } - } - } - } - - BreakpointLocationSP bp_loc_sp (AddLocation(line_start)); - if (log && bp_loc_sp && !m_breakpoint->IsInternal()) - { - StreamString s; - bp_loc_sp->GetDescription (&s, lldb::eDescriptionLevelVerbose); - log->Printf ("Added location (skipped prologue: %s): %s \n", skipped_prologue ? "yes" : "no", s.GetData()); - } - } - else if (log) - { - log->Printf ("Breakpoint %s at file address 0x%" PRIx64 " didn't pass the filter.\n", - log_ident ? log_ident : "", - line_start.GetFileAddress()); + } + } + + // and make breakpoints out of the closest line number match. + + uint32_t tmp_sc_list_size = tmp_sc_list.GetSize(); + + for (uint32_t i = 0; i < tmp_sc_list_size; i++) { + if (tmp_sc_list.GetContextAtIndex(i, sc)) { + Address line_start = sc.line_entry.range.GetBaseAddress(); + if (line_start.IsValid()) { + if (filter.AddressPasses(line_start)) { + // If the line number is before the prologue end, move it there... + bool skipped_prologue = false; + if (skip_prologue) { + if (sc.function) { + Address prologue_addr( + sc.function->GetAddressRange().GetBaseAddress()); + if (prologue_addr.IsValid() && (line_start == prologue_addr)) { + const uint32_t prologue_byte_size = + sc.function->GetPrologueByteSize(); + if (prologue_byte_size) { + prologue_addr.Slide(prologue_byte_size); + + if (filter.AddressPasses(prologue_addr)) { + skipped_prologue = true; + line_start = prologue_addr; } + } } - else - { - if (log) - log->Printf ("error: Unable to set breakpoint %s at file address 0x%" PRIx64 "\n", - log_ident ? log_ident : "", - line_start.GetFileAddress()); - } + } } + + BreakpointLocationSP bp_loc_sp(AddLocation(line_start)); + if (log && bp_loc_sp && !m_breakpoint->IsInternal()) { + StreamString s; + bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); + log->Printf("Added location (skipped prologue: %s): %s \n", + skipped_prologue ? "yes" : "no", s.GetData()); + } + } else if (log) { + log->Printf("Breakpoint %s at file address 0x%" PRIx64 + " didn't pass the filter.\n", + log_ident ? log_ident : "", + line_start.GetFileAddress()); + } + } else { + if (log) + log->Printf( + "error: Unable to set breakpoint %s at file address 0x%" PRIx64 + "\n", + log_ident ? log_ident : "", line_start.GetFileAddress()); } + } } + } } -BreakpointLocationSP -BreakpointResolver::AddLocation(Address loc_addr, bool *new_location) -{ - loc_addr.Slide(m_offset); - return m_breakpoint->AddLocation(loc_addr, new_location); +BreakpointLocationSP BreakpointResolver::AddLocation(Address loc_addr, + bool *new_location) { + loc_addr.Slide(m_offset); + return m_breakpoint->AddLocation(loc_addr, new_location); } - -void -BreakpointResolver::SetOffset (lldb::addr_t offset) -{ - // There may already be an offset, so we are actually adjusting location addresses by the difference. - // lldb::addr_t slide = offset - m_offset; - // FIXME: We should go fix up all the already set locations for the new slide. +void BreakpointResolver::SetOffset(lldb::addr_t offset) { + // There may already be an offset, so we are actually adjusting location + // addresses by the difference. + // lldb::addr_t slide = offset - m_offset; + // FIXME: We should go fix up all the already set locations for the new slide. - m_offset = offset; + m_offset = offset; } - diff --git a/lldb/source/Breakpoint/BreakpointResolverAddress.cpp b/lldb/source/Breakpoint/BreakpointResolverAddress.cpp index 14942014d80..e52ec9ca9de 100644 --- a/lldb/source/Breakpoint/BreakpointResolverAddress.cpp +++ b/lldb/source/Breakpoint/BreakpointResolverAddress.cpp @@ -27,149 +27,111 @@ using namespace lldb_private; //---------------------------------------------------------------------- // BreakpointResolverAddress: //---------------------------------------------------------------------- -BreakpointResolverAddress::BreakpointResolverAddress -( - Breakpoint *bkpt, - const Address &addr, - const FileSpec &module_spec -) : - BreakpointResolver (bkpt, BreakpointResolver::AddressResolver), - m_addr (addr), - m_resolved_addr(LLDB_INVALID_ADDRESS), - m_module_filespec(module_spec) -{ +BreakpointResolverAddress::BreakpointResolverAddress( + Breakpoint *bkpt, const Address &addr, const FileSpec &module_spec) + : BreakpointResolver(bkpt, BreakpointResolver::AddressResolver), + m_addr(addr), m_resolved_addr(LLDB_INVALID_ADDRESS), + m_module_filespec(module_spec) {} + +BreakpointResolverAddress::BreakpointResolverAddress(Breakpoint *bkpt, + const Address &addr) + : BreakpointResolver(bkpt, BreakpointResolver::AddressResolver), + m_addr(addr), m_resolved_addr(LLDB_INVALID_ADDRESS), m_module_filespec() { } -BreakpointResolverAddress::BreakpointResolverAddress -( - Breakpoint *bkpt, - const Address &addr -) : - BreakpointResolver (bkpt, BreakpointResolver::AddressResolver), - m_addr (addr), - m_resolved_addr(LLDB_INVALID_ADDRESS), - m_module_filespec() -{ +BreakpointResolverAddress::~BreakpointResolverAddress() {} + +void BreakpointResolverAddress::ResolveBreakpoint(SearchFilter &filter) { + // If the address is not section relative, then we should not try to + // re-resolve it, it is just some + // random address and we wouldn't know what to do on reload. But if it is + // section relative, we need to + // re-resolve it since the section it's in may have shifted on re-run. + bool re_resolve = false; + if (m_addr.GetSection() || m_module_filespec) + re_resolve = true; + else if (m_breakpoint->GetNumLocations() == 0) + re_resolve = true; + + if (re_resolve) + BreakpointResolver::ResolveBreakpoint(filter); } -BreakpointResolverAddress::~BreakpointResolverAddress () -{ - -} - -void -BreakpointResolverAddress::ResolveBreakpoint (SearchFilter &filter) -{ - // If the address is not section relative, then we should not try to re-resolve it, it is just some - // random address and we wouldn't know what to do on reload. But if it is section relative, we need to - // re-resolve it since the section it's in may have shifted on re-run. - bool re_resolve = false; - if (m_addr.GetSection() || m_module_filespec) - re_resolve = true; - else if (m_breakpoint->GetNumLocations() == 0) - re_resolve = true; - - if (re_resolve) - BreakpointResolver::ResolveBreakpoint(filter); -} - -void -BreakpointResolverAddress::ResolveBreakpointInModules -( - SearchFilter &filter, - ModuleList &modules -) -{ - // See comment in ResolveBreakpoint. - bool re_resolve = false; - if (m_addr.GetSection()) - re_resolve = true; - else if (m_breakpoint->GetNumLocations() == 0) - re_resolve = true; - - if (re_resolve) - BreakpointResolver::ResolveBreakpointInModules (filter, modules); +void BreakpointResolverAddress::ResolveBreakpointInModules( + SearchFilter &filter, ModuleList &modules) { + // See comment in ResolveBreakpoint. + bool re_resolve = false; + if (m_addr.GetSection()) + re_resolve = true; + else if (m_breakpoint->GetNumLocations() == 0) + re_resolve = true; + + if (re_resolve) + BreakpointResolver::ResolveBreakpointInModules(filter, modules); } Searcher::CallbackReturn -BreakpointResolverAddress::SearchCallback -( - SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing -) -{ - assert (m_breakpoint != NULL); - - if (filter.AddressPasses (m_addr)) - { - if (m_breakpoint->GetNumLocations() == 0) - { - // If the address is just an offset, and we're given a module, see if we can find the appropriate module - // loaded in the binary, and fix up m_addr to use that. - if (!m_addr.IsSectionOffset() && m_module_filespec) - { - Target &target = m_breakpoint->GetTarget(); - ModuleSpec module_spec(m_module_filespec); - ModuleSP module_sp = target.GetImages().FindFirstModule(module_spec); - if (module_sp) - { - Address tmp_address; - if (module_sp->ResolveFileAddress(m_addr.GetOffset(), tmp_address)) - m_addr = tmp_address; - } - } - - m_resolved_addr = m_addr.GetLoadAddress(&m_breakpoint->GetTarget()); - BreakpointLocationSP bp_loc_sp(AddLocation(m_addr)); - if (bp_loc_sp && !m_breakpoint->IsInternal()) - { - StreamString s; - bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - if (log) - log->Printf ("Added location: %s\n", s.GetData()); - } - } - else - { - BreakpointLocationSP loc_sp = m_breakpoint->GetLocationAtIndex(0); - lldb::addr_t cur_load_location = m_addr.GetLoadAddress(&m_breakpoint->GetTarget()); - if (cur_load_location != m_resolved_addr) - { - m_resolved_addr = cur_load_location; - loc_sp->ClearBreakpointSite(); - loc_sp->ResolveBreakpointSite(); - } +BreakpointResolverAddress::SearchCallback(SearchFilter &filter, + SymbolContext &context, Address *addr, + bool containing) { + assert(m_breakpoint != NULL); + + if (filter.AddressPasses(m_addr)) { + if (m_breakpoint->GetNumLocations() == 0) { + // If the address is just an offset, and we're given a module, see if we + // can find the appropriate module + // loaded in the binary, and fix up m_addr to use that. + if (!m_addr.IsSectionOffset() && m_module_filespec) { + Target &target = m_breakpoint->GetTarget(); + ModuleSpec module_spec(m_module_filespec); + ModuleSP module_sp = target.GetImages().FindFirstModule(module_spec); + if (module_sp) { + Address tmp_address; + if (module_sp->ResolveFileAddress(m_addr.GetOffset(), tmp_address)) + m_addr = tmp_address; } + } + + m_resolved_addr = m_addr.GetLoadAddress(&m_breakpoint->GetTarget()); + BreakpointLocationSP bp_loc_sp(AddLocation(m_addr)); + if (bp_loc_sp && !m_breakpoint->IsInternal()) { + StreamString s; + bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); + Log *log( + lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + if (log) + log->Printf("Added location: %s\n", s.GetData()); + } + } else { + BreakpointLocationSP loc_sp = m_breakpoint->GetLocationAtIndex(0); + lldb::addr_t cur_load_location = + m_addr.GetLoadAddress(&m_breakpoint->GetTarget()); + if (cur_load_location != m_resolved_addr) { + m_resolved_addr = cur_load_location; + loc_sp->ClearBreakpointSite(); + loc_sp->ResolveBreakpointSite(); + } } - return Searcher::eCallbackReturnStop; + } + return Searcher::eCallbackReturnStop; } -Searcher::Depth -BreakpointResolverAddress::GetDepth() -{ - return Searcher::eDepthTarget; +Searcher::Depth BreakpointResolverAddress::GetDepth() { + return Searcher::eDepthTarget; } -void -BreakpointResolverAddress::GetDescription (Stream *s) -{ - s->PutCString ("address = "); - m_addr.Dump(s, m_breakpoint->GetTarget().GetProcessSP().get(), Address::DumpStyleModuleWithFileAddress, Address::DumpStyleLoadAddress); +void BreakpointResolverAddress::GetDescription(Stream *s) { + s->PutCString("address = "); + m_addr.Dump(s, m_breakpoint->GetTarget().GetProcessSP().get(), + Address::DumpStyleModuleWithFileAddress, + Address::DumpStyleLoadAddress); } -void -BreakpointResolverAddress::Dump (Stream *s) const -{ - -} +void BreakpointResolverAddress::Dump(Stream *s) const {} lldb::BreakpointResolverSP -BreakpointResolverAddress::CopyForBreakpoint (Breakpoint &breakpoint) -{ - lldb::BreakpointResolverSP ret_sp(new BreakpointResolverAddress(&breakpoint, m_addr)); - return ret_sp; +BreakpointResolverAddress::CopyForBreakpoint(Breakpoint &breakpoint) { + lldb::BreakpointResolverSP ret_sp( + new BreakpointResolverAddress(&breakpoint, m_addr)); + return ret_sp; } - diff --git a/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp b/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp index e1fb87a9d87..482b1658251 100644 --- a/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp +++ b/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp @@ -26,102 +26,79 @@ using namespace lldb_private; //---------------------------------------------------------------------- // BreakpointResolverFileLine: //---------------------------------------------------------------------- -BreakpointResolverFileLine::BreakpointResolverFileLine -( - Breakpoint *bkpt, - const FileSpec &file_spec, - uint32_t line_no, - lldb::addr_t offset, - bool check_inlines, - bool skip_prologue, - bool exact_match -) : - BreakpointResolver (bkpt, BreakpointResolver::FileLineResolver, offset), - m_file_spec (file_spec), - m_line_number (line_no), - m_inlines (check_inlines), - m_skip_prologue(skip_prologue), - m_exact_match(exact_match) -{ -} +BreakpointResolverFileLine::BreakpointResolverFileLine( + Breakpoint *bkpt, const FileSpec &file_spec, uint32_t line_no, + lldb::addr_t offset, bool check_inlines, bool skip_prologue, + bool exact_match) + : BreakpointResolver(bkpt, BreakpointResolver::FileLineResolver, offset), + m_file_spec(file_spec), m_line_number(line_no), m_inlines(check_inlines), + m_skip_prologue(skip_prologue), m_exact_match(exact_match) {} -BreakpointResolverFileLine::~BreakpointResolverFileLine () -{ -} +BreakpointResolverFileLine::~BreakpointResolverFileLine() {} Searcher::CallbackReturn -BreakpointResolverFileLine::SearchCallback -( - SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing -) -{ - SymbolContextList sc_list; - - assert (m_breakpoint != NULL); - - // There is a tricky bit here. You can have two compilation units that #include the same file, and - // in one of them the function at m_line_number is used (and so code and a line entry for it is generated) but in the - // other it isn't. If we considered the CU's independently, then in the second inclusion, we'd move the breakpoint - // to the next function that actually generated code in the header file. That would end up being confusing. - // So instead, we do the CU iterations by hand here, then scan through the complete list of matches, and figure out - // the closest line number match, and only set breakpoints on that match. - - // Note also that if file_spec only had a file name and not a directory, there may be many different file spec's in - // the resultant list. The closest line match for one will not be right for some totally different file. - // So we go through the match list and pull out the sets that have the same file spec in their line_entry - // and treat each set separately. - - const size_t num_comp_units = context.module_sp->GetNumCompileUnits(); - for (size_t i = 0; i < num_comp_units; i++) - { - CompUnitSP cu_sp (context.module_sp->GetCompileUnitAtIndex (i)); - if (cu_sp) - { - if (filter.CompUnitPasses(*cu_sp)) - cu_sp->ResolveSymbolContext (m_file_spec, m_line_number, m_inlines, m_exact_match, eSymbolContextEverything, sc_list); - } +BreakpointResolverFileLine::SearchCallback(SearchFilter &filter, + SymbolContext &context, + Address *addr, bool containing) { + SymbolContextList sc_list; + + assert(m_breakpoint != NULL); + + // There is a tricky bit here. You can have two compilation units that + // #include the same file, and + // in one of them the function at m_line_number is used (and so code and a + // line entry for it is generated) but in the + // other it isn't. If we considered the CU's independently, then in the + // second inclusion, we'd move the breakpoint + // to the next function that actually generated code in the header file. That + // would end up being confusing. + // So instead, we do the CU iterations by hand here, then scan through the + // complete list of matches, and figure out + // the closest line number match, and only set breakpoints on that match. + + // Note also that if file_spec only had a file name and not a directory, there + // may be many different file spec's in + // the resultant list. The closest line match for one will not be right for + // some totally different file. + // So we go through the match list and pull out the sets that have the same + // file spec in their line_entry + // and treat each set separately. + + const size_t num_comp_units = context.module_sp->GetNumCompileUnits(); + for (size_t i = 0; i < num_comp_units; i++) { + CompUnitSP cu_sp(context.module_sp->GetCompileUnitAtIndex(i)); + if (cu_sp) { + if (filter.CompUnitPasses(*cu_sp)) + cu_sp->ResolveSymbolContext(m_file_spec, m_line_number, m_inlines, + m_exact_match, eSymbolContextEverything, + sc_list); } - StreamString s; - s.Printf ("for %s:%d ", - m_file_spec.GetFilename().AsCString(""), - m_line_number); + } + StreamString s; + s.Printf("for %s:%d ", m_file_spec.GetFilename().AsCString(""), + m_line_number); - SetSCMatchesByLine (filter, sc_list, m_skip_prologue, s.GetData()); + SetSCMatchesByLine(filter, sc_list, m_skip_prologue, s.GetData()); - return Searcher::eCallbackReturnContinue; + return Searcher::eCallbackReturnContinue; } -Searcher::Depth -BreakpointResolverFileLine::GetDepth() -{ - return Searcher::eDepthModule; +Searcher::Depth BreakpointResolverFileLine::GetDepth() { + return Searcher::eDepthModule; } -void -BreakpointResolverFileLine::GetDescription (Stream *s) -{ - s->Printf ("file = '%s', line = %u, exact_match = %d", m_file_spec.GetPath().c_str(), m_line_number, m_exact_match); +void BreakpointResolverFileLine::GetDescription(Stream *s) { + s->Printf("file = '%s', line = %u, exact_match = %d", + m_file_spec.GetPath().c_str(), m_line_number, m_exact_match); } -void -BreakpointResolverFileLine::Dump (Stream *s) const -{ - -} +void BreakpointResolverFileLine::Dump(Stream *s) const {} lldb::BreakpointResolverSP -BreakpointResolverFileLine::CopyForBreakpoint (Breakpoint &breakpoint) -{ - lldb::BreakpointResolverSP ret_sp(new BreakpointResolverFileLine(&breakpoint, - m_file_spec, - m_line_number, - m_offset, - m_inlines, - m_skip_prologue, - m_exact_match)); - - return ret_sp; +BreakpointResolverFileLine::CopyForBreakpoint(Breakpoint &breakpoint) { + lldb::BreakpointResolverSP ret_sp(new BreakpointResolverFileLine( + &breakpoint, m_file_spec, m_line_number, m_offset, m_inlines, + m_skip_prologue, m_exact_match)); + + return ret_sp; } diff --git a/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp b/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp index ae7f58acb91..8d08908f9a3 100644 --- a/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp +++ b/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp @@ -1,4 +1,5 @@ -//===-- BreakpointResolverFileRegex.cpp --------------------------*- C++ -*-===// +//===-- BreakpointResolverFileRegex.cpp --------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -14,8 +15,8 @@ // Other libraries and framework includes // Project includes #include "lldb/Breakpoint/BreakpointLocation.h" -#include "lldb/Core/SourceManager.h" #include "lldb/Core/Log.h" +#include "lldb/Core/SourceManager.h" #include "lldb/Core/StreamString.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Target/Target.h" @@ -26,113 +27,90 @@ using namespace lldb_private; //---------------------------------------------------------------------- // BreakpointResolverFileRegex: //---------------------------------------------------------------------- -BreakpointResolverFileRegex::BreakpointResolverFileRegex -( - Breakpoint *bkpt, - RegularExpression ®ex, - const std::unordered_set &func_names, - bool exact_match -) : - BreakpointResolver (bkpt, BreakpointResolver::FileLineResolver), - m_regex (regex), - m_exact_match (exact_match), - m_function_names(func_names) -{ +BreakpointResolverFileRegex::BreakpointResolverFileRegex( + Breakpoint *bkpt, RegularExpression ®ex, + const std::unordered_set &func_names, bool exact_match) + : BreakpointResolver(bkpt, BreakpointResolver::FileLineResolver), + m_regex(regex), m_exact_match(exact_match), m_function_names(func_names) { } -BreakpointResolverFileRegex::~BreakpointResolverFileRegex () -{ -} +BreakpointResolverFileRegex::~BreakpointResolverFileRegex() {} Searcher::CallbackReturn -BreakpointResolverFileRegex::SearchCallback -( - SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing -) -{ - - assert (m_breakpoint != NULL); - if (!context.target_sp) - return eCallbackReturnContinue; - - CompileUnit *cu = context.comp_unit; - FileSpec cu_file_spec = *(static_cast(cu)); - std::vector line_matches; - context.target_sp->GetSourceManager().FindLinesMatchingRegex(cu_file_spec, m_regex, 1, UINT32_MAX, line_matches); - - uint32_t num_matches = line_matches.size(); - for (uint32_t i = 0; i < num_matches; i++) - { - SymbolContextList sc_list; - const bool search_inlines = false; - - cu->ResolveSymbolContext (cu_file_spec, line_matches[i], search_inlines, m_exact_match, eSymbolContextEverything, sc_list); - // Find all the function names: - if (!m_function_names.empty()) - { - std::vector sc_to_remove; - for (size_t i = 0; i < sc_list.GetSize(); i++) - { - SymbolContext sc_ctx; - sc_list.GetContextAtIndex(i, sc_ctx); - std::string name(sc_ctx.GetFunctionName(Mangled::NamePreference::ePreferDemangledWithoutArguments).AsCString()); - if (!m_function_names.count(name)) - { - sc_to_remove.push_back(i); - } - } - - if (!sc_to_remove.empty()) - { - std::vector::reverse_iterator iter; - std::vector::reverse_iterator rend = sc_to_remove.rend(); - for (iter = sc_to_remove.rbegin(); iter != rend; iter++) - { - sc_list.RemoveContextAtIndex(*iter); - } - } +BreakpointResolverFileRegex::SearchCallback(SearchFilter &filter, + SymbolContext &context, + Address *addr, bool containing) { + + assert(m_breakpoint != NULL); + if (!context.target_sp) + return eCallbackReturnContinue; + + CompileUnit *cu = context.comp_unit; + FileSpec cu_file_spec = *(static_cast(cu)); + std::vector line_matches; + context.target_sp->GetSourceManager().FindLinesMatchingRegex( + cu_file_spec, m_regex, 1, UINT32_MAX, line_matches); + + uint32_t num_matches = line_matches.size(); + for (uint32_t i = 0; i < num_matches; i++) { + SymbolContextList sc_list; + const bool search_inlines = false; + + cu->ResolveSymbolContext(cu_file_spec, line_matches[i], search_inlines, + m_exact_match, eSymbolContextEverything, sc_list); + // Find all the function names: + if (!m_function_names.empty()) { + std::vector sc_to_remove; + for (size_t i = 0; i < sc_list.GetSize(); i++) { + SymbolContext sc_ctx; + sc_list.GetContextAtIndex(i, sc_ctx); + std::string name( + sc_ctx + .GetFunctionName( + Mangled::NamePreference::ePreferDemangledWithoutArguments) + .AsCString()); + if (!m_function_names.count(name)) { + sc_to_remove.push_back(i); + } + } + + if (!sc_to_remove.empty()) { + std::vector::reverse_iterator iter; + std::vector::reverse_iterator rend = sc_to_remove.rend(); + for (iter = sc_to_remove.rbegin(); iter != rend; iter++) { + sc_list.RemoveContextAtIndex(*iter); } - - const bool skip_prologue = true; - - BreakpointResolver::SetSCMatchesByLine (filter, sc_list, skip_prologue, m_regex.GetText()); + } } - assert (m_breakpoint != NULL); - return Searcher::eCallbackReturnContinue; -} + const bool skip_prologue = true; -Searcher::Depth -BreakpointResolverFileRegex::GetDepth() -{ - return Searcher::eDepthCompUnit; -} + BreakpointResolver::SetSCMatchesByLine(filter, sc_list, skip_prologue, + m_regex.GetText()); + } + assert(m_breakpoint != NULL); -void -BreakpointResolverFileRegex::GetDescription (Stream *s) -{ - s->Printf ("source regex = \"%s\", exact_match = %d", m_regex.GetText(), m_exact_match); + return Searcher::eCallbackReturnContinue; } -void -BreakpointResolverFileRegex::Dump (Stream *s) const -{ +Searcher::Depth BreakpointResolverFileRegex::GetDepth() { + return Searcher::eDepthCompUnit; +} +void BreakpointResolverFileRegex::GetDescription(Stream *s) { + s->Printf("source regex = \"%s\", exact_match = %d", m_regex.GetText(), + m_exact_match); } +void BreakpointResolverFileRegex::Dump(Stream *s) const {} + lldb::BreakpointResolverSP -BreakpointResolverFileRegex::CopyForBreakpoint (Breakpoint &breakpoint) -{ - lldb::BreakpointResolverSP ret_sp(new BreakpointResolverFileRegex(&breakpoint, m_regex, m_function_names, m_exact_match)); - return ret_sp; +BreakpointResolverFileRegex::CopyForBreakpoint(Breakpoint &breakpoint) { + lldb::BreakpointResolverSP ret_sp(new BreakpointResolverFileRegex( + &breakpoint, m_regex, m_function_names, m_exact_match)); + return ret_sp; } -void -BreakpointResolverFileRegex::AddFunctionName(const char *func_name) -{ - m_function_names.insert(func_name); +void BreakpointResolverFileRegex::AddFunctionName(const char *func_name) { + m_function_names.insert(func_name); } - diff --git a/lldb/source/Breakpoint/BreakpointResolverName.cpp b/lldb/source/Breakpoint/BreakpointResolverName.cpp index dfa09c2342f..64d0318eb1f 100644 --- a/lldb/source/Breakpoint/BreakpointResolverName.cpp +++ b/lldb/source/Breakpoint/BreakpointResolverName.cpp @@ -13,6 +13,8 @@ // Project includes #include "lldb/Breakpoint/BreakpointResolverName.h" +#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" +#include "Plugins/Language/ObjC/ObjCLanguage.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" @@ -21,372 +23,288 @@ #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/SymbolContext.h" -#include "Plugins/Language/ObjC/ObjCLanguage.h" -#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" using namespace lldb; using namespace lldb_private; -BreakpointResolverName::BreakpointResolverName (Breakpoint *bkpt, - const char *name_cstr, - uint32_t name_type_mask, - LanguageType language, - Breakpoint::MatchType type, - lldb::addr_t offset, - bool skip_prologue) : - BreakpointResolver (bkpt, BreakpointResolver::NameResolver, offset), - m_class_name (), - m_regex (), - m_match_type (type), - m_language (language), - m_skip_prologue (skip_prologue) -{ - if (m_match_type == Breakpoint::Regexp) - { - if (!m_regex.Compile (name_cstr)) - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - - if (log) - log->Warning ("function name regexp: \"%s\" did not compile.", name_cstr); - } - } - else - { - AddNameLookup (ConstString(name_cstr), name_type_mask); - } -} +BreakpointResolverName::BreakpointResolverName( + Breakpoint *bkpt, const char *name_cstr, uint32_t name_type_mask, + LanguageType language, Breakpoint::MatchType type, lldb::addr_t offset, + bool skip_prologue) + : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset), + m_class_name(), m_regex(), m_match_type(type), m_language(language), + m_skip_prologue(skip_prologue) { + if (m_match_type == Breakpoint::Regexp) { + if (!m_regex.Compile(name_cstr)) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); -BreakpointResolverName::BreakpointResolverName (Breakpoint *bkpt, - const char *names[], - size_t num_names, - uint32_t name_type_mask, - LanguageType language, - lldb::addr_t offset, - bool skip_prologue) : - BreakpointResolver (bkpt, BreakpointResolver::NameResolver, offset), - m_match_type (Breakpoint::Exact), - m_language (language), - m_skip_prologue (skip_prologue) -{ - for (size_t i = 0; i < num_names; i++) - { - AddNameLookup (ConstString (names[i]), name_type_mask); + if (log) + log->Warning("function name regexp: \"%s\" did not compile.", + name_cstr); } + } else { + AddNameLookup(ConstString(name_cstr), name_type_mask); + } } -BreakpointResolverName::BreakpointResolverName (Breakpoint *bkpt, - std::vector names, - uint32_t name_type_mask, - LanguageType language, - lldb::addr_t offset, - bool skip_prologue) : - BreakpointResolver (bkpt, BreakpointResolver::NameResolver, offset), - m_match_type (Breakpoint::Exact), - m_language (language), - m_skip_prologue (skip_prologue) -{ - for (const std::string& name : names) - { - AddNameLookup (ConstString (name.c_str(), name.size()), name_type_mask); - } +BreakpointResolverName::BreakpointResolverName( + Breakpoint *bkpt, const char *names[], size_t num_names, + uint32_t name_type_mask, LanguageType language, lldb::addr_t offset, + bool skip_prologue) + : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset), + m_match_type(Breakpoint::Exact), m_language(language), + m_skip_prologue(skip_prologue) { + for (size_t i = 0; i < num_names; i++) { + AddNameLookup(ConstString(names[i]), name_type_mask); + } } -BreakpointResolverName::BreakpointResolverName (Breakpoint *bkpt, - RegularExpression &func_regex, - lldb::LanguageType language, - lldb::addr_t offset, - bool skip_prologue) : - BreakpointResolver (bkpt, BreakpointResolver::NameResolver, offset), - m_class_name (nullptr), - m_regex (func_regex), - m_match_type (Breakpoint::Regexp), - m_language (language), - m_skip_prologue (skip_prologue) -{ +BreakpointResolverName::BreakpointResolverName( + Breakpoint *bkpt, std::vector names, uint32_t name_type_mask, + LanguageType language, lldb::addr_t offset, bool skip_prologue) + : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset), + m_match_type(Breakpoint::Exact), m_language(language), + m_skip_prologue(skip_prologue) { + for (const std::string &name : names) { + AddNameLookup(ConstString(name.c_str(), name.size()), name_type_mask); + } } -BreakpointResolverName::BreakpointResolverName -( - Breakpoint *bkpt, - const char *class_name, - const char *method, - Breakpoint::MatchType type, - lldb::addr_t offset, - bool skip_prologue -) : - BreakpointResolver (bkpt, BreakpointResolver::NameResolver, offset), - m_class_name (class_name), - m_regex (), - m_match_type (type), - m_language (eLanguageTypeUnknown), - m_skip_prologue (skip_prologue) -{ - Module::LookupInfo lookup; - lookup.SetName(ConstString(method)); - lookup.SetLookupName(lookup.GetName()); - lookup.SetNameTypeMask(eFunctionNameTypeMethod); - m_lookups.push_back (lookup); +BreakpointResolverName::BreakpointResolverName(Breakpoint *bkpt, + RegularExpression &func_regex, + lldb::LanguageType language, + lldb::addr_t offset, + bool skip_prologue) + : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset), + m_class_name(nullptr), m_regex(func_regex), + m_match_type(Breakpoint::Regexp), m_language(language), + m_skip_prologue(skip_prologue) {} + +BreakpointResolverName::BreakpointResolverName( + Breakpoint *bkpt, const char *class_name, const char *method, + Breakpoint::MatchType type, lldb::addr_t offset, bool skip_prologue) + : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset), + m_class_name(class_name), m_regex(), m_match_type(type), + m_language(eLanguageTypeUnknown), m_skip_prologue(skip_prologue) { + Module::LookupInfo lookup; + lookup.SetName(ConstString(method)); + lookup.SetLookupName(lookup.GetName()); + lookup.SetNameTypeMask(eFunctionNameTypeMethod); + m_lookups.push_back(lookup); } BreakpointResolverName::~BreakpointResolverName() = default; -BreakpointResolverName::BreakpointResolverName(const BreakpointResolverName &rhs) : - BreakpointResolver(rhs.m_breakpoint, BreakpointResolver::NameResolver, rhs.m_offset), - m_lookups(rhs.m_lookups), - m_class_name(rhs.m_class_name), - m_regex(rhs.m_regex), - m_match_type (rhs.m_match_type), - m_language (rhs.m_language), - m_skip_prologue (rhs.m_skip_prologue) -{ -} +BreakpointResolverName::BreakpointResolverName( + const BreakpointResolverName &rhs) + : BreakpointResolver(rhs.m_breakpoint, BreakpointResolver::NameResolver, + rhs.m_offset), + m_lookups(rhs.m_lookups), m_class_name(rhs.m_class_name), + m_regex(rhs.m_regex), m_match_type(rhs.m_match_type), + m_language(rhs.m_language), m_skip_prologue(rhs.m_skip_prologue) {} -void -BreakpointResolverName::AddNameLookup (const ConstString &name, uint32_t name_type_mask) -{ - ObjCLanguage::MethodName objc_method(name.GetCString(), false); - if (objc_method.IsValid(false)) - { - std::vector objc_names; - objc_method.GetFullNames(objc_names, true); - for (ConstString objc_name : objc_names) - { - Module::LookupInfo lookup; - lookup.SetName(name); - lookup.SetLookupName(objc_name); - lookup.SetNameTypeMask(eFunctionNameTypeFull); - m_lookups.push_back (lookup); - } - } - else - { - Module::LookupInfo lookup(name, name_type_mask, m_language); - m_lookups.push_back (lookup); +void BreakpointResolverName::AddNameLookup(const ConstString &name, + uint32_t name_type_mask) { + ObjCLanguage::MethodName objc_method(name.GetCString(), false); + if (objc_method.IsValid(false)) { + std::vector objc_names; + objc_method.GetFullNames(objc_names, true); + for (ConstString objc_name : objc_names) { + Module::LookupInfo lookup; + lookup.SetName(name); + lookup.SetLookupName(objc_name); + lookup.SetNameTypeMask(eFunctionNameTypeFull); + m_lookups.push_back(lookup); } + } else { + Module::LookupInfo lookup(name, name_type_mask, m_language); + m_lookups.push_back(lookup); + } } -// FIXME: Right now we look at the module level, and call the module's "FindFunctions". -// Greg says he will add function tables, maybe at the CompileUnit level to accelerate function -// lookup. At that point, we should switch the depth to CompileUnit, and look in these tables. +// FIXME: Right now we look at the module level, and call the module's +// "FindFunctions". +// Greg says he will add function tables, maybe at the CompileUnit level to +// accelerate function +// lookup. At that point, we should switch the depth to CompileUnit, and look +// in these tables. Searcher::CallbackReturn BreakpointResolverName::SearchCallback(SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing) -{ - SymbolContextList func_list; - //SymbolContextList sym_list; - - uint32_t i; - bool new_location; - Address break_addr; - assert (m_breakpoint != nullptr); - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - - if (m_class_name) - { - if (log) - log->Warning ("Class/method function specification not supported yet.\n"); - return Searcher::eCallbackReturnStop; + SymbolContext &context, Address *addr, + bool containing) { + SymbolContextList func_list; + // SymbolContextList sym_list; + + uint32_t i; + bool new_location; + Address break_addr; + assert(m_breakpoint != nullptr); + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + + if (m_class_name) { + if (log) + log->Warning("Class/method function specification not supported yet.\n"); + return Searcher::eCallbackReturnStop; + } + bool filter_by_cu = + (filter.GetFilterRequiredItems() & eSymbolContextCompUnit) != 0; + bool filter_by_language = (m_language != eLanguageTypeUnknown); + const bool include_symbols = !filter_by_cu; + const bool include_inlines = true; + const bool append = true; + + switch (m_match_type) { + case Breakpoint::Exact: + if (context.module_sp) { + for (const auto &lookup : m_lookups) { + const size_t start_func_idx = func_list.GetSize(); + context.module_sp->FindFunctions( + lookup.GetLookupName(), nullptr, lookup.GetNameTypeMask(), + include_symbols, include_inlines, append, func_list); + + const size_t end_func_idx = func_list.GetSize(); + + if (start_func_idx < end_func_idx) + lookup.Prune(func_list, start_func_idx); + } } - bool filter_by_cu = (filter.GetFilterRequiredItems() & eSymbolContextCompUnit) != 0; - bool filter_by_language = (m_language != eLanguageTypeUnknown); - const bool include_symbols = !filter_by_cu; - const bool include_inlines = true; - const bool append = true; - - switch (m_match_type) - { - case Breakpoint::Exact: - if (context.module_sp) - { - for (const auto &lookup : m_lookups) - { - const size_t start_func_idx = func_list.GetSize(); - context.module_sp->FindFunctions(lookup.GetLookupName(), - nullptr, - lookup.GetNameTypeMask(), - include_symbols, - include_inlines, - append, - func_list); - - const size_t end_func_idx = func_list.GetSize(); - - if (start_func_idx < end_func_idx) - lookup.Prune (func_list, start_func_idx); - } - } - break; - case Breakpoint::Regexp: - if (context.module_sp) - { - context.module_sp->FindFunctions (m_regex, - !filter_by_cu, // include symbols only if we aren't filtering by CU - include_inlines, - append, - func_list); - } - break; - case Breakpoint::Glob: - if (log) - log->Warning ("glob is not supported yet."); - break; + break; + case Breakpoint::Regexp: + if (context.module_sp) { + context.module_sp->FindFunctions( + m_regex, + !filter_by_cu, // include symbols only if we aren't filtering by CU + include_inlines, append, func_list); } + break; + case Breakpoint::Glob: + if (log) + log->Warning("glob is not supported yet."); + break; + } - // If the filter specifies a Compilation Unit, remove the ones that don't pass at this point. - if (filter_by_cu || filter_by_language) - { - uint32_t num_functions = func_list.GetSize(); - - for (size_t idx = 0; idx < num_functions; idx++) - { - bool remove_it = false; - SymbolContext sc; - func_list.GetContextAtIndex(idx, sc); - if (filter_by_cu) - { - if (!sc.comp_unit || !filter.CompUnitPasses(*sc.comp_unit)) - remove_it = true; - } - - if (filter_by_language) - { - LanguageType sym_language = sc.GetLanguage(); - if ((Language::GetPrimaryLanguage(sym_language) != - Language::GetPrimaryLanguage(m_language)) && - (sym_language != eLanguageTypeUnknown)) - { - remove_it = true; - } - } - - if (remove_it) - { - func_list.RemoveContextAtIndex(idx); - num_functions--; - idx--; - } + // If the filter specifies a Compilation Unit, remove the ones that don't pass + // at this point. + if (filter_by_cu || filter_by_language) { + uint32_t num_functions = func_list.GetSize(); + + for (size_t idx = 0; idx < num_functions; idx++) { + bool remove_it = false; + SymbolContext sc; + func_list.GetContextAtIndex(idx, sc); + if (filter_by_cu) { + if (!sc.comp_unit || !filter.CompUnitPasses(*sc.comp_unit)) + remove_it = true; + } + + if (filter_by_language) { + LanguageType sym_language = sc.GetLanguage(); + if ((Language::GetPrimaryLanguage(sym_language) != + Language::GetPrimaryLanguage(m_language)) && + (sym_language != eLanguageTypeUnknown)) { + remove_it = true; } + } + + if (remove_it) { + func_list.RemoveContextAtIndex(idx); + num_functions--; + idx--; + } } + } + + // Remove any duplicates between the function list and the symbol list + SymbolContext sc; + if (func_list.GetSize()) { + for (i = 0; i < func_list.GetSize(); i++) { + if (func_list.GetContextAtIndex(i, sc)) { + bool is_reexported = false; - // Remove any duplicates between the function list and the symbol list - SymbolContext sc; - if (func_list.GetSize()) - { - for (i = 0; i < func_list.GetSize(); i++) - { - if (func_list.GetContextAtIndex(i, sc)) - { - bool is_reexported = false; - - if (sc.block && sc.block->GetInlinedFunctionInfo()) - { - if (!sc.block->GetStartAddress(break_addr)) - break_addr.Clear(); - } - else if (sc.function) - { - break_addr = sc.function->GetAddressRange().GetBaseAddress(); - if (m_skip_prologue && break_addr.IsValid()) - { - const uint32_t prologue_byte_size = sc.function->GetPrologueByteSize(); - if (prologue_byte_size) - break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size); - } - } - else if (sc.symbol) - { - if (sc.symbol->GetType() == eSymbolTypeReExported) - { - const Symbol *actual_symbol = sc.symbol->ResolveReExportedSymbol(m_breakpoint->GetTarget()); - if (actual_symbol) - { - is_reexported = true; - break_addr = actual_symbol->GetAddress(); - } - } - else - { - break_addr = sc.symbol->GetAddress(); - } - - if (m_skip_prologue && break_addr.IsValid()) - { - const uint32_t prologue_byte_size = sc.symbol->GetPrologueByteSize(); - if (prologue_byte_size) - break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size); - } - } - - if (break_addr.IsValid()) - { - if (filter.AddressPasses(break_addr)) - { - BreakpointLocationSP bp_loc_sp (AddLocation(break_addr, &new_location)); - bp_loc_sp->SetIsReExported(is_reexported); - if (bp_loc_sp && new_location && !m_breakpoint->IsInternal()) - { - if (log) - { - StreamString s; - bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); - log->Printf ("Added location: %s\n", s.GetData()); - } - } - } - } + if (sc.block && sc.block->GetInlinedFunctionInfo()) { + if (!sc.block->GetStartAddress(break_addr)) + break_addr.Clear(); + } else if (sc.function) { + break_addr = sc.function->GetAddressRange().GetBaseAddress(); + if (m_skip_prologue && break_addr.IsValid()) { + const uint32_t prologue_byte_size = + sc.function->GetPrologueByteSize(); + if (prologue_byte_size) + break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size); + } + } else if (sc.symbol) { + if (sc.symbol->GetType() == eSymbolTypeReExported) { + const Symbol *actual_symbol = + sc.symbol->ResolveReExportedSymbol(m_breakpoint->GetTarget()); + if (actual_symbol) { + is_reexported = true; + break_addr = actual_symbol->GetAddress(); } + } else { + break_addr = sc.symbol->GetAddress(); + } + + if (m_skip_prologue && break_addr.IsValid()) { + const uint32_t prologue_byte_size = + sc.symbol->GetPrologueByteSize(); + if (prologue_byte_size) + break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size); + } } + + if (break_addr.IsValid()) { + if (filter.AddressPasses(break_addr)) { + BreakpointLocationSP bp_loc_sp( + AddLocation(break_addr, &new_location)); + bp_loc_sp->SetIsReExported(is_reexported); + if (bp_loc_sp && new_location && !m_breakpoint->IsInternal()) { + if (log) { + StreamString s; + bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); + log->Printf("Added location: %s\n", s.GetData()); + } + } + } + } + } } - - return Searcher::eCallbackReturnContinue; + } + + return Searcher::eCallbackReturnContinue; } -Searcher::Depth -BreakpointResolverName::GetDepth() -{ - return Searcher::eDepthModule; +Searcher::Depth BreakpointResolverName::GetDepth() { + return Searcher::eDepthModule; } -void -BreakpointResolverName::GetDescription (Stream *s) -{ - if (m_match_type == Breakpoint::Regexp) - s->Printf("regex = '%s'", m_regex.GetText()); - else - { - size_t num_names = m_lookups.size(); - if (num_names == 1) - s->Printf("name = '%s'", m_lookups[0].GetName().GetCString()); - else - { - s->Printf("names = {"); - for (size_t i = 0; i < num_names; i++) - { - s->Printf ("%s'%s'", (i == 0 ? "" : ", "), m_lookups[i].GetName().GetCString()); - } - s->Printf ("}"); - } - } - if (m_language != eLanguageTypeUnknown) - { - s->Printf (", language = %s", Language::GetNameForLanguageType(m_language)); +void BreakpointResolverName::GetDescription(Stream *s) { + if (m_match_type == Breakpoint::Regexp) + s->Printf("regex = '%s'", m_regex.GetText()); + else { + size_t num_names = m_lookups.size(); + if (num_names == 1) + s->Printf("name = '%s'", m_lookups[0].GetName().GetCString()); + else { + s->Printf("names = {"); + for (size_t i = 0; i < num_names; i++) { + s->Printf("%s'%s'", (i == 0 ? "" : ", "), + m_lookups[i].GetName().GetCString()); + } + s->Printf("}"); } + } + if (m_language != eLanguageTypeUnknown) { + s->Printf(", language = %s", Language::GetNameForLanguageType(m_language)); + } } -void -BreakpointResolverName::Dump (Stream *s) const -{ -} +void BreakpointResolverName::Dump(Stream *s) const {} lldb::BreakpointResolverSP -BreakpointResolverName::CopyForBreakpoint (Breakpoint &breakpoint) -{ - lldb::BreakpointResolverSP ret_sp(new BreakpointResolverName(*this)); - ret_sp->SetBreakpoint(&breakpoint); - return ret_sp; +BreakpointResolverName::CopyForBreakpoint(Breakpoint &breakpoint) { + lldb::BreakpointResolverSP ret_sp(new BreakpointResolverName(*this)); + ret_sp->SetBreakpoint(&breakpoint); + return ret_sp; } diff --git a/lldb/source/Breakpoint/BreakpointSite.cpp b/lldb/source/Breakpoint/BreakpointSite.cpp index b4112f7fc01..28ba37b1b50 100644 --- a/lldb/source/Breakpoint/BreakpointSite.cpp +++ b/lldb/source/Breakpoint/BreakpointSite.cpp @@ -23,240 +23,181 @@ using namespace lldb; using namespace lldb_private; -BreakpointSite::BreakpointSite(BreakpointSiteList *list, const BreakpointLocationSP &owner, lldb::addr_t addr, - bool use_hardware) +BreakpointSite::BreakpointSite(BreakpointSiteList *list, + const BreakpointLocationSP &owner, + lldb::addr_t addr, bool use_hardware) : StoppointLocation(GetNextID(), addr, 0, use_hardware), - m_type(eSoftware), // Process subclasses need to set this correctly using SetType() - m_saved_opcode(), - m_trap_opcode(), - m_enabled(false), // Need to create it disabled, so the first enable turns it on. - m_owners(), - m_owners_mutex() -{ - m_owners.Add(owner); + m_type(eSoftware), // Process subclasses need to set this correctly using + // SetType() + m_saved_opcode(), m_trap_opcode(), + m_enabled(false), // Need to create it disabled, so the first enable turns + // it on. + m_owners(), m_owners_mutex() { + m_owners.Add(owner); } -BreakpointSite::~BreakpointSite() -{ - BreakpointLocationSP bp_loc_sp; - const size_t owner_count = m_owners.GetSize(); - for (size_t i = 0; i < owner_count; i++) - { - m_owners.GetByIndex(i)->ClearBreakpointSite(); - } +BreakpointSite::~BreakpointSite() { + BreakpointLocationSP bp_loc_sp; + const size_t owner_count = m_owners.GetSize(); + for (size_t i = 0; i < owner_count; i++) { + m_owners.GetByIndex(i)->ClearBreakpointSite(); + } } -break_id_t -BreakpointSite::GetNextID() -{ - static break_id_t g_next_id = 0; - return ++g_next_id; +break_id_t BreakpointSite::GetNextID() { + static break_id_t g_next_id = 0; + return ++g_next_id; } // RETURNS - true if we should stop at this breakpoint, false if we // should continue. -bool -BreakpointSite::ShouldStop (StoppointCallbackContext *context) -{ - std::lock_guard guard(m_owners_mutex); - IncrementHitCount(); - return m_owners.ShouldStop (context); +bool BreakpointSite::ShouldStop(StoppointCallbackContext *context) { + std::lock_guard guard(m_owners_mutex); + IncrementHitCount(); + return m_owners.ShouldStop(context); } -bool -BreakpointSite::IsBreakpointAtThisSite (lldb::break_id_t bp_id) -{ - std::lock_guard guard(m_owners_mutex); - const size_t owner_count = m_owners.GetSize(); - for (size_t i = 0; i < owner_count; i++) - { - if (m_owners.GetByIndex(i)->GetBreakpoint().GetID() == bp_id) - return true; - } - return false; +bool BreakpointSite::IsBreakpointAtThisSite(lldb::break_id_t bp_id) { + std::lock_guard guard(m_owners_mutex); + const size_t owner_count = m_owners.GetSize(); + for (size_t i = 0; i < owner_count; i++) { + if (m_owners.GetByIndex(i)->GetBreakpoint().GetID() == bp_id) + return true; + } + return false; } -void -BreakpointSite::Dump(Stream *s) const -{ - if (s == nullptr) - return; +void BreakpointSite::Dump(Stream *s) const { + if (s == nullptr) + return; - s->Printf("BreakpointSite %u: addr = 0x%8.8" PRIx64 " type = %s breakpoint hw_index = %i hit_count = %-4u", - GetID(), - (uint64_t)m_addr, - IsHardware() ? "hardware" : "software", - GetHardwareIndex(), - GetHitCount()); + s->Printf("BreakpointSite %u: addr = 0x%8.8" PRIx64 + " type = %s breakpoint hw_index = %i hit_count = %-4u", + GetID(), (uint64_t)m_addr, IsHardware() ? "hardware" : "software", + GetHardwareIndex(), GetHitCount()); } -void -BreakpointSite::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - std::lock_guard guard(m_owners_mutex); - if (level != lldb::eDescriptionLevelBrief) - s->Printf ("breakpoint site: %d at 0x%8.8" PRIx64, GetID(), GetLoadAddress()); - m_owners.GetDescription (s, level); +void BreakpointSite::GetDescription(Stream *s, lldb::DescriptionLevel level) { + std::lock_guard guard(m_owners_mutex); + if (level != lldb::eDescriptionLevelBrief) + s->Printf("breakpoint site: %d at 0x%8.8" PRIx64, GetID(), + GetLoadAddress()); + m_owners.GetDescription(s, level); } -bool -BreakpointSite::IsInternal() const -{ - return m_owners.IsInternal(); -} +bool BreakpointSite::IsInternal() const { return m_owners.IsInternal(); } -uint8_t * -BreakpointSite::GetTrapOpcodeBytes() -{ - return &m_trap_opcode[0]; -} +uint8_t *BreakpointSite::GetTrapOpcodeBytes() { return &m_trap_opcode[0]; } -const uint8_t * -BreakpointSite::GetTrapOpcodeBytes() const -{ - return &m_trap_opcode[0]; +const uint8_t *BreakpointSite::GetTrapOpcodeBytes() const { + return &m_trap_opcode[0]; } -size_t -BreakpointSite::GetTrapOpcodeMaxByteSize() const -{ - return sizeof(m_trap_opcode); +size_t BreakpointSite::GetTrapOpcodeMaxByteSize() const { + return sizeof(m_trap_opcode); } -bool -BreakpointSite::SetTrapOpcode (const uint8_t *trap_opcode, uint32_t trap_opcode_size) -{ - if (trap_opcode_size > 0 && trap_opcode_size <= sizeof(m_trap_opcode)) - { - m_byte_size = trap_opcode_size; - ::memcpy (m_trap_opcode, trap_opcode, trap_opcode_size); - return true; - } - m_byte_size = 0; - return false; +bool BreakpointSite::SetTrapOpcode(const uint8_t *trap_opcode, + uint32_t trap_opcode_size) { + if (trap_opcode_size > 0 && trap_opcode_size <= sizeof(m_trap_opcode)) { + m_byte_size = trap_opcode_size; + ::memcpy(m_trap_opcode, trap_opcode, trap_opcode_size); + return true; + } + m_byte_size = 0; + return false; } -uint8_t * -BreakpointSite::GetSavedOpcodeBytes() -{ - return &m_saved_opcode[0]; -} +uint8_t *BreakpointSite::GetSavedOpcodeBytes() { return &m_saved_opcode[0]; } -const uint8_t * -BreakpointSite::GetSavedOpcodeBytes() const -{ - return &m_saved_opcode[0]; +const uint8_t *BreakpointSite::GetSavedOpcodeBytes() const { + return &m_saved_opcode[0]; } -bool -BreakpointSite::IsEnabled () const -{ - return m_enabled; -} +bool BreakpointSite::IsEnabled() const { return m_enabled; } -void -BreakpointSite::SetEnabled (bool enabled) -{ - m_enabled = enabled; -} +void BreakpointSite::SetEnabled(bool enabled) { m_enabled = enabled; } -void -BreakpointSite::AddOwner (const BreakpointLocationSP &owner) -{ - std::lock_guard guard(m_owners_mutex); - m_owners.Add(owner); +void BreakpointSite::AddOwner(const BreakpointLocationSP &owner) { + std::lock_guard guard(m_owners_mutex); + m_owners.Add(owner); } -size_t -BreakpointSite::RemoveOwner (lldb::break_id_t break_id, lldb::break_id_t break_loc_id) -{ - std::lock_guard guard(m_owners_mutex); - m_owners.Remove(break_id, break_loc_id); - return m_owners.GetSize(); +size_t BreakpointSite::RemoveOwner(lldb::break_id_t break_id, + lldb::break_id_t break_loc_id) { + std::lock_guard guard(m_owners_mutex); + m_owners.Remove(break_id, break_loc_id); + return m_owners.GetSize(); } -size_t -BreakpointSite::GetNumberOfOwners () -{ - std::lock_guard guard(m_owners_mutex); - return m_owners.GetSize(); +size_t BreakpointSite::GetNumberOfOwners() { + std::lock_guard guard(m_owners_mutex); + return m_owners.GetSize(); } -BreakpointLocationSP -BreakpointSite::GetOwnerAtIndex (size_t index) -{ - std::lock_guard guard(m_owners_mutex); - return m_owners.GetByIndex (index); +BreakpointLocationSP BreakpointSite::GetOwnerAtIndex(size_t index) { + std::lock_guard guard(m_owners_mutex); + return m_owners.GetByIndex(index); } -bool -BreakpointSite::ValidForThisThread (Thread *thread) -{ - std::lock_guard guard(m_owners_mutex); - return m_owners.ValidForThisThread(thread); +bool BreakpointSite::ValidForThisThread(Thread *thread) { + std::lock_guard guard(m_owners_mutex); + return m_owners.ValidForThisThread(thread); } -void -BreakpointSite::BumpHitCounts() -{ - std::lock_guard guard(m_owners_mutex); - for (BreakpointLocationSP loc_sp : m_owners.BreakpointLocations()) - { - loc_sp->BumpHitCount(); - } +void BreakpointSite::BumpHitCounts() { + std::lock_guard guard(m_owners_mutex); + for (BreakpointLocationSP loc_sp : m_owners.BreakpointLocations()) { + loc_sp->BumpHitCount(); + } } -bool -BreakpointSite::IntersectsRange(lldb::addr_t addr, size_t size, lldb::addr_t *intersect_addr, size_t *intersect_size, size_t *opcode_offset) const -{ - // We only use software traps for software breakpoints - if (!IsHardware()) - { - if (m_byte_size > 0) - { - const lldb::addr_t bp_end_addr = m_addr + m_byte_size; - const lldb::addr_t end_addr = addr + size; - // Is the breakpoint end address before the passed in start address? - if (bp_end_addr <= addr) - return false; - // Is the breakpoint start address after passed in end address? - if (end_addr <= m_addr) - return false; - if (intersect_addr || intersect_size || opcode_offset) - { - if (m_addr < addr) - { - if (intersect_addr) - *intersect_addr = addr; - if (intersect_size) - *intersect_size = std::min(bp_end_addr, end_addr) - addr; - if (opcode_offset) - *opcode_offset = addr - m_addr; - } - else - { - if (intersect_addr) - *intersect_addr = m_addr; - if (intersect_size) - *intersect_size = std::min(bp_end_addr, end_addr) - m_addr; - if (opcode_offset) - *opcode_offset = 0; - } - } - return true; +bool BreakpointSite::IntersectsRange(lldb::addr_t addr, size_t size, + lldb::addr_t *intersect_addr, + size_t *intersect_size, + size_t *opcode_offset) const { + // We only use software traps for software breakpoints + if (!IsHardware()) { + if (m_byte_size > 0) { + const lldb::addr_t bp_end_addr = m_addr + m_byte_size; + const lldb::addr_t end_addr = addr + size; + // Is the breakpoint end address before the passed in start address? + if (bp_end_addr <= addr) + return false; + // Is the breakpoint start address after passed in end address? + if (end_addr <= m_addr) + return false; + if (intersect_addr || intersect_size || opcode_offset) { + if (m_addr < addr) { + if (intersect_addr) + *intersect_addr = addr; + if (intersect_size) + *intersect_size = + std::min(bp_end_addr, end_addr) - addr; + if (opcode_offset) + *opcode_offset = addr - m_addr; + } else { + if (intersect_addr) + *intersect_addr = m_addr; + if (intersect_size) + *intersect_size = + std::min(bp_end_addr, end_addr) - m_addr; + if (opcode_offset) + *opcode_offset = 0; } + } + return true; } - return false; + } + return false; } size_t -BreakpointSite::CopyOwnersList (BreakpointLocationCollection &out_collection) -{ - std::lock_guard guard(m_owners_mutex); - for (BreakpointLocationSP loc_sp : m_owners.BreakpointLocations()) - { - out_collection.Add(loc_sp); - } - return out_collection.GetSize(); +BreakpointSite::CopyOwnersList(BreakpointLocationCollection &out_collection) { + std::lock_guard guard(m_owners_mutex); + for (BreakpointLocationSP loc_sp : m_owners.BreakpointLocations()) { + out_collection.Add(loc_sp); + } + return out_collection.GetSize(); } diff --git a/lldb/source/Breakpoint/BreakpointSiteList.cpp b/lldb/source/Breakpoint/BreakpointSiteList.cpp index de9a5ad0b31..06155ee8b79 100644 --- a/lldb/source/Breakpoint/BreakpointSiteList.cpp +++ b/lldb/source/Breakpoint/BreakpointSiteList.cpp @@ -19,220 +19,188 @@ using namespace lldb; using namespace lldb_private; -BreakpointSiteList::BreakpointSiteList() : m_mutex(), m_bp_site_list() -{ -} +BreakpointSiteList::BreakpointSiteList() : m_mutex(), m_bp_site_list() {} -BreakpointSiteList::~BreakpointSiteList() -{ -} +BreakpointSiteList::~BreakpointSiteList() {} -// Add breakpoint site to the list. However, if the element already exists in the +// Add breakpoint site to the list. However, if the element already exists in +// the // list, then we don't add it, and return LLDB_INVALID_BREAK_ID. -lldb::break_id_t -BreakpointSiteList::Add(const BreakpointSiteSP &bp) -{ - lldb::addr_t bp_site_load_addr = bp->GetLoadAddress(); - std::lock_guard guard(m_mutex); - collection::iterator iter = m_bp_site_list.find (bp_site_load_addr); - - if (iter == m_bp_site_list.end()) - { - m_bp_site_list.insert (iter, collection::value_type (bp_site_load_addr, bp)); - return bp->GetID(); - } - else - { - return LLDB_INVALID_BREAK_ID; - } -} +lldb::break_id_t BreakpointSiteList::Add(const BreakpointSiteSP &bp) { + lldb::addr_t bp_site_load_addr = bp->GetLoadAddress(); + std::lock_guard guard(m_mutex); + collection::iterator iter = m_bp_site_list.find(bp_site_load_addr); -bool -BreakpointSiteList::ShouldStop (StoppointCallbackContext *context, lldb::break_id_t site_id) -{ - BreakpointSiteSP site_sp (FindByID (site_id)); - if (site_sp) - { - // Let the BreakpointSite decide if it should stop here (could not have - // reached it's target hit count yet, or it could have a callback - // that decided it shouldn't stop (shared library loads/unloads). - return site_sp->ShouldStop (context); - } - // We should stop here since this BreakpointSite isn't valid anymore or it - // doesn't exist. - return true; -} -lldb::break_id_t -BreakpointSiteList::FindIDByAddress (lldb::addr_t addr) -{ - BreakpointSiteSP bp = FindByAddress (addr); - if (bp) - { - //DBLogIf(PD_LOG_BREAKPOINTS, "BreakpointSiteList::%s ( addr = 0x%8.8" PRIx64 " ) => %u", __FUNCTION__, (uint64_t)addr, bp->GetID()); - return bp.get()->GetID(); - } - //DBLogIf(PD_LOG_BREAKPOINTS, "BreakpointSiteList::%s ( addr = 0x%8.8" PRIx64 " ) => NONE", __FUNCTION__, (uint64_t)addr); + if (iter == m_bp_site_list.end()) { + m_bp_site_list.insert(iter, collection::value_type(bp_site_load_addr, bp)); + return bp->GetID(); + } else { return LLDB_INVALID_BREAK_ID; + } +} + +bool BreakpointSiteList::ShouldStop(StoppointCallbackContext *context, + lldb::break_id_t site_id) { + BreakpointSiteSP site_sp(FindByID(site_id)); + if (site_sp) { + // Let the BreakpointSite decide if it should stop here (could not have + // reached it's target hit count yet, or it could have a callback + // that decided it shouldn't stop (shared library loads/unloads). + return site_sp->ShouldStop(context); + } + // We should stop here since this BreakpointSite isn't valid anymore or it + // doesn't exist. + return true; +} +lldb::break_id_t BreakpointSiteList::FindIDByAddress(lldb::addr_t addr) { + BreakpointSiteSP bp = FindByAddress(addr); + if (bp) { + // DBLogIf(PD_LOG_BREAKPOINTS, "BreakpointSiteList::%s ( addr = 0x%8.8" + // PRIx64 " ) => %u", __FUNCTION__, (uint64_t)addr, bp->GetID()); + return bp.get()->GetID(); + } + // DBLogIf(PD_LOG_BREAKPOINTS, "BreakpointSiteList::%s ( addr = 0x%8.8" PRIx64 + // " ) => NONE", __FUNCTION__, (uint64_t)addr); + return LLDB_INVALID_BREAK_ID; +} + +bool BreakpointSiteList::Remove(lldb::break_id_t break_id) { + std::lock_guard guard(m_mutex); + collection::iterator pos = GetIDIterator(break_id); // Predicate + if (pos != m_bp_site_list.end()) { + m_bp_site_list.erase(pos); + return true; + } + return false; } -bool -BreakpointSiteList::Remove (lldb::break_id_t break_id) -{ - std::lock_guard guard(m_mutex); - collection::iterator pos = GetIDIterator(break_id); // Predicate - if (pos != m_bp_site_list.end()) - { - m_bp_site_list.erase(pos); - return true; - } - return false; -} - -bool -BreakpointSiteList::RemoveByAddress (lldb::addr_t address) -{ - std::lock_guard guard(m_mutex); - collection::iterator pos = m_bp_site_list.find(address); - if (pos != m_bp_site_list.end()) - { - m_bp_site_list.erase(pos); - return true; - } - return false; +bool BreakpointSiteList::RemoveByAddress(lldb::addr_t address) { + std::lock_guard guard(m_mutex); + collection::iterator pos = m_bp_site_list.find(address); + if (pos != m_bp_site_list.end()) { + m_bp_site_list.erase(pos); + return true; + } + return false; } -class BreakpointSiteIDMatches -{ +class BreakpointSiteIDMatches { public: - BreakpointSiteIDMatches (lldb::break_id_t break_id) : - m_break_id(break_id) - { - } + BreakpointSiteIDMatches(lldb::break_id_t break_id) : m_break_id(break_id) {} - bool operator() (std::pair val_pair) const - { - return m_break_id == val_pair.second.get()->GetID(); - } + bool operator()(std::pair val_pair) const { + return m_break_id == val_pair.second.get()->GetID(); + } private: - const lldb::break_id_t m_break_id; + const lldb::break_id_t m_break_id; }; BreakpointSiteList::collection::iterator -BreakpointSiteList::GetIDIterator (lldb::break_id_t break_id) -{ - std::lock_guard guard(m_mutex); - return std::find_if(m_bp_site_list.begin(), m_bp_site_list.end(), // Search full range - BreakpointSiteIDMatches(break_id)); // Predicate +BreakpointSiteList::GetIDIterator(lldb::break_id_t break_id) { + std::lock_guard guard(m_mutex); + return std::find_if(m_bp_site_list.begin(), + m_bp_site_list.end(), // Search full range + BreakpointSiteIDMatches(break_id)); // Predicate } BreakpointSiteList::collection::const_iterator -BreakpointSiteList::GetIDConstIterator (lldb::break_id_t break_id) const -{ - std::lock_guard guard(m_mutex); - return std::find_if(m_bp_site_list.begin(), m_bp_site_list.end(), // Search full range - BreakpointSiteIDMatches(break_id)); // Predicate +BreakpointSiteList::GetIDConstIterator(lldb::break_id_t break_id) const { + std::lock_guard guard(m_mutex); + return std::find_if(m_bp_site_list.begin(), + m_bp_site_list.end(), // Search full range + BreakpointSiteIDMatches(break_id)); // Predicate } -BreakpointSiteSP -BreakpointSiteList::FindByID (lldb::break_id_t break_id) -{ - std::lock_guard guard(m_mutex); - BreakpointSiteSP stop_sp; - collection::iterator pos = GetIDIterator(break_id); - if (pos != m_bp_site_list.end()) - stop_sp = pos->second; +BreakpointSiteSP BreakpointSiteList::FindByID(lldb::break_id_t break_id) { + std::lock_guard guard(m_mutex); + BreakpointSiteSP stop_sp; + collection::iterator pos = GetIDIterator(break_id); + if (pos != m_bp_site_list.end()) + stop_sp = pos->second; - return stop_sp; + return stop_sp; } const BreakpointSiteSP -BreakpointSiteList::FindByID (lldb::break_id_t break_id) const -{ - std::lock_guard guard(m_mutex); - BreakpointSiteSP stop_sp; - collection::const_iterator pos = GetIDConstIterator(break_id); - if (pos != m_bp_site_list.end()) - stop_sp = pos->second; - - return stop_sp; -} - -BreakpointSiteSP -BreakpointSiteList::FindByAddress (lldb::addr_t addr) -{ - BreakpointSiteSP found_sp; - std::lock_guard guard(m_mutex); - collection::iterator iter = m_bp_site_list.find(addr); - if (iter != m_bp_site_list.end()) - found_sp = iter->second; - return found_sp; -} - -bool -BreakpointSiteList::BreakpointSiteContainsBreakpoint (lldb::break_id_t bp_site_id, lldb::break_id_t bp_id) -{ - std::lock_guard guard(m_mutex); - collection::const_iterator pos = GetIDConstIterator(bp_site_id); - if (pos != m_bp_site_list.end()) - return pos->second->IsBreakpointAtThisSite (bp_id); - +BreakpointSiteList::FindByID(lldb::break_id_t break_id) const { + std::lock_guard guard(m_mutex); + BreakpointSiteSP stop_sp; + collection::const_iterator pos = GetIDConstIterator(break_id); + if (pos != m_bp_site_list.end()) + stop_sp = pos->second; + + return stop_sp; +} + +BreakpointSiteSP BreakpointSiteList::FindByAddress(lldb::addr_t addr) { + BreakpointSiteSP found_sp; + std::lock_guard guard(m_mutex); + collection::iterator iter = m_bp_site_list.find(addr); + if (iter != m_bp_site_list.end()) + found_sp = iter->second; + return found_sp; +} + +bool BreakpointSiteList::BreakpointSiteContainsBreakpoint( + lldb::break_id_t bp_site_id, lldb::break_id_t bp_id) { + std::lock_guard guard(m_mutex); + collection::const_iterator pos = GetIDConstIterator(bp_site_id); + if (pos != m_bp_site_list.end()) + return pos->second->IsBreakpointAtThisSite(bp_id); + + return false; +} + +void BreakpointSiteList::Dump(Stream *s) const { + s->Printf("%p: ", static_cast(this)); + // s->Indent(); + s->Printf("BreakpointSiteList with %u BreakpointSites:\n", + (uint32_t)m_bp_site_list.size()); + s->IndentMore(); + collection::const_iterator pos; + collection::const_iterator end = m_bp_site_list.end(); + for (pos = m_bp_site_list.begin(); pos != end; ++pos) + pos->second.get()->Dump(s); + s->IndentLess(); +} + +void BreakpointSiteList::ForEach( + std::function const &callback) { + std::lock_guard guard(m_mutex); + for (auto pair : m_bp_site_list) + callback(pair.second.get()); +} + +bool BreakpointSiteList::FindInRange(lldb::addr_t lower_bound, + lldb::addr_t upper_bound, + BreakpointSiteList &bp_site_list) const { + if (lower_bound > upper_bound) return false; -} -void -BreakpointSiteList::Dump (Stream *s) const -{ - s->Printf("%p: ", static_cast(this)); - //s->Indent(); - s->Printf("BreakpointSiteList with %u BreakpointSites:\n", (uint32_t)m_bp_site_list.size()); - s->IndentMore(); - collection::const_iterator pos; - collection::const_iterator end = m_bp_site_list.end(); - for (pos = m_bp_site_list.begin(); pos != end; ++pos) - pos->second.get()->Dump(s); - s->IndentLess(); -} - -void -BreakpointSiteList::ForEach (std::function const &callback) -{ - std::lock_guard guard(m_mutex); - for (auto pair : m_bp_site_list) - callback (pair.second.get()); -} + std::lock_guard guard(m_mutex); + collection::const_iterator lower, upper, pos; + lower = m_bp_site_list.lower_bound(lower_bound); + if (lower == m_bp_site_list.end() || (*lower).first >= upper_bound) + return false; -bool -BreakpointSiteList::FindInRange (lldb::addr_t lower_bound, lldb::addr_t upper_bound, BreakpointSiteList &bp_site_list) const -{ - if (lower_bound > upper_bound) - return false; - - std::lock_guard guard(m_mutex); - collection::const_iterator lower, upper, pos; - lower = m_bp_site_list.lower_bound(lower_bound); - if (lower == m_bp_site_list.end() - || (*lower).first >= upper_bound) - return false; - - // This is one tricky bit. The breakpoint might overlap the bottom end of the range. So we grab the - // breakpoint prior to the lower bound, and check that that + its byte size isn't in our range. - if (lower != m_bp_site_list.begin()) - { - collection::const_iterator prev_pos = lower; - prev_pos--; - const BreakpointSiteSP &prev_bp = (*prev_pos).second; - if (prev_bp->GetLoadAddress() + prev_bp->GetByteSize() > lower_bound) - bp_site_list.Add (prev_bp); - - } - - upper = m_bp_site_list.upper_bound(upper_bound); - - for (pos = lower; pos != upper; pos++) - { - bp_site_list.Add ((*pos).second); - } - return true; + // This is one tricky bit. The breakpoint might overlap the bottom end of the + // range. So we grab the + // breakpoint prior to the lower bound, and check that that + its byte size + // isn't in our range. + if (lower != m_bp_site_list.begin()) { + collection::const_iterator prev_pos = lower; + prev_pos--; + const BreakpointSiteSP &prev_bp = (*prev_pos).second; + if (prev_bp->GetLoadAddress() + prev_bp->GetByteSize() > lower_bound) + bp_site_list.Add(prev_bp); + } + + upper = m_bp_site_list.upper_bound(upper_bound); + + for (pos = lower; pos != upper; pos++) { + bp_site_list.Add((*pos).second); + } + return true; } diff --git a/lldb/source/Breakpoint/Stoppoint.cpp b/lldb/source/Breakpoint/Stoppoint.cpp index 583ab47005f..dbc832b4307 100644 --- a/lldb/source/Breakpoint/Stoppoint.cpp +++ b/lldb/source/Breakpoint/Stoppoint.cpp @@ -7,8 +7,8 @@ // //===----------------------------------------------------------------------===// -#include "lldb/lldb-private.h" #include "lldb/Breakpoint/Stoppoint.h" +#include "lldb/lldb-private.h" // C Includes // C++ Includes @@ -21,26 +21,13 @@ using namespace lldb_private; //---------------------------------------------------------------------- // Stoppoint constructor //---------------------------------------------------------------------- -Stoppoint::Stoppoint() : - m_bid (LLDB_INVALID_BREAK_ID) -{ -} +Stoppoint::Stoppoint() : m_bid(LLDB_INVALID_BREAK_ID) {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -Stoppoint::~Stoppoint() -{ -} +Stoppoint::~Stoppoint() {} -break_id_t -Stoppoint::GetID () const -{ - return m_bid; -} +break_id_t Stoppoint::GetID() const { return m_bid; } -void -Stoppoint::SetID (break_id_t bid) -{ - m_bid = bid; -} +void Stoppoint::SetID(break_id_t bid) { m_bid = bid; } diff --git a/lldb/source/Breakpoint/StoppointCallbackContext.cpp b/lldb/source/Breakpoint/StoppointCallbackContext.cpp index 9932843714f..3d24eb78c45 100644 --- a/lldb/source/Breakpoint/StoppointCallbackContext.cpp +++ b/lldb/source/Breakpoint/StoppointCallbackContext.cpp @@ -15,24 +15,15 @@ using namespace lldb_private; -StoppointCallbackContext::StoppointCallbackContext() : - event (nullptr), - exe_ctx_ref (), - is_synchronous (false) -{ -} +StoppointCallbackContext::StoppointCallbackContext() + : event(nullptr), exe_ctx_ref(), is_synchronous(false) {} -StoppointCallbackContext::StoppointCallbackContext(Event *e, const ExecutionContext &exe_ctx, bool synchronously) : - event (e), - exe_ctx_ref (exe_ctx), - is_synchronous(synchronously) -{ -} +StoppointCallbackContext::StoppointCallbackContext( + Event *e, const ExecutionContext &exe_ctx, bool synchronously) + : event(e), exe_ctx_ref(exe_ctx), is_synchronous(synchronously) {} -void -StoppointCallbackContext::Clear() -{ - event = nullptr; - exe_ctx_ref.Clear(); - is_synchronous = false; +void StoppointCallbackContext::Clear() { + event = nullptr; + exe_ctx_ref.Clear(); + is_synchronous = false; } diff --git a/lldb/source/Breakpoint/StoppointLocation.cpp b/lldb/source/Breakpoint/StoppointLocation.cpp index 35e5979bd9e..d624ddbfa51 100644 --- a/lldb/source/Breakpoint/StoppointLocation.cpp +++ b/lldb/source/Breakpoint/StoppointLocation.cpp @@ -20,36 +20,22 @@ using namespace lldb_private; //---------------------------------------------------------------------- // StoppointLocation constructor //---------------------------------------------------------------------- -StoppointLocation::StoppointLocation (break_id_t bid, addr_t addr, bool hardware) : - m_loc_id(bid), - m_addr(addr), - m_hardware(hardware), - m_hardware_index(LLDB_INVALID_INDEX32), - m_byte_size(0), - m_hit_count(0) -{ -} +StoppointLocation::StoppointLocation(break_id_t bid, addr_t addr, bool hardware) + : m_loc_id(bid), m_addr(addr), m_hardware(hardware), + m_hardware_index(LLDB_INVALID_INDEX32), m_byte_size(0), m_hit_count(0) {} -StoppointLocation::StoppointLocation (break_id_t bid, addr_t addr, uint32_t byte_size, bool hardware) : - m_loc_id(bid), - m_addr(addr), - m_hardware(hardware), - m_hardware_index(LLDB_INVALID_INDEX32), - m_byte_size(byte_size), - m_hit_count(0) -{ -} +StoppointLocation::StoppointLocation(break_id_t bid, addr_t addr, + uint32_t byte_size, bool hardware) + : m_loc_id(bid), m_addr(addr), m_hardware(hardware), + m_hardware_index(LLDB_INVALID_INDEX32), m_byte_size(byte_size), + m_hit_count(0) {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- -StoppointLocation::~StoppointLocation() -{ -} +StoppointLocation::~StoppointLocation() {} -void -StoppointLocation::DecrementHitCount () -{ - assert (m_hit_count > 0); - --m_hit_count; +void StoppointLocation::DecrementHitCount() { + assert(m_hit_count > 0); + --m_hit_count; } diff --git a/lldb/source/Breakpoint/Watchpoint.cpp b/lldb/source/Breakpoint/Watchpoint.cpp index 00a328e3039..15fcff68399 100644 --- a/lldb/source/Breakpoint/Watchpoint.cpp +++ b/lldb/source/Breakpoint/Watchpoint.cpp @@ -18,487 +18,370 @@ #include "lldb/Core/Value.h" #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectMemory.h" +#include "lldb/Expression/UserExpression.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" -#include "lldb/Expression/UserExpression.h" using namespace lldb; using namespace lldb_private; -Watchpoint::Watchpoint (Target& target, lldb::addr_t addr, uint32_t size, const CompilerType *type, bool hardware) : - StoppointLocation (0, addr, size, hardware), - m_target(target), - m_enabled(false), - m_is_hardware(hardware), - m_is_watch_variable(false), - m_is_ephemeral(false), - m_disabled_count(0), - m_watch_read(0), - m_watch_write(0), - m_watch_was_read(0), - m_watch_was_written(0), - m_ignore_count(0), - m_false_alarms(0), - m_decl_str(), - m_watch_spec_str(), - m_type(), - m_error(), - m_options (), - m_being_created(true) -{ - if (type && type->IsValid()) - m_type = *type; - else - { - // If we don't have a known type, then we force it to unsigned int of the right size. - ClangASTContext *ast_context = target.GetScratchClangASTContext(); - m_type = ast_context->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 8 * size); - } - - // Set the initial value of the watched variable: - if (m_target.GetProcessSP()) - { - ExecutionContext exe_ctx; - m_target.GetProcessSP()->CalculateExecutionContext(exe_ctx); - CaptureWatchedValue (exe_ctx); - } - m_being_created = false; +Watchpoint::Watchpoint(Target &target, lldb::addr_t addr, uint32_t size, + const CompilerType *type, bool hardware) + : StoppointLocation(0, addr, size, hardware), m_target(target), + m_enabled(false), m_is_hardware(hardware), m_is_watch_variable(false), + m_is_ephemeral(false), m_disabled_count(0), m_watch_read(0), + m_watch_write(0), m_watch_was_read(0), m_watch_was_written(0), + m_ignore_count(0), m_false_alarms(0), m_decl_str(), m_watch_spec_str(), + m_type(), m_error(), m_options(), m_being_created(true) { + if (type && type->IsValid()) + m_type = *type; + else { + // If we don't have a known type, then we force it to unsigned int of the + // right size. + ClangASTContext *ast_context = target.GetScratchClangASTContext(); + m_type = ast_context->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, + 8 * size); + } + + // Set the initial value of the watched variable: + if (m_target.GetProcessSP()) { + ExecutionContext exe_ctx; + m_target.GetProcessSP()->CalculateExecutionContext(exe_ctx); + CaptureWatchedValue(exe_ctx); + } + m_being_created = false; } Watchpoint::~Watchpoint() = default; // This function is used when "baton" doesn't need to be freed -void -Watchpoint::SetCallback (WatchpointHitCallback callback, void *baton, bool is_synchronous) -{ - // The default "Baton" class will keep a copy of "baton" and won't free - // or delete it when it goes goes out of scope. - m_options.SetCallback(callback, BatonSP (new Baton(baton)), is_synchronous); - - SendWatchpointChangedEvent (eWatchpointEventTypeCommandChanged); +void Watchpoint::SetCallback(WatchpointHitCallback callback, void *baton, + bool is_synchronous) { + // The default "Baton" class will keep a copy of "baton" and won't free + // or delete it when it goes goes out of scope. + m_options.SetCallback(callback, BatonSP(new Baton(baton)), is_synchronous); + + SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged); } -// This function is used when a baton needs to be freed and therefore is +// This function is used when a baton needs to be freed and therefore is // contained in a "Baton" subclass. -void -Watchpoint::SetCallback (WatchpointHitCallback callback, const BatonSP &callback_baton_sp, bool is_synchronous) -{ - m_options.SetCallback(callback, callback_baton_sp, is_synchronous); - SendWatchpointChangedEvent (eWatchpointEventTypeCommandChanged); +void Watchpoint::SetCallback(WatchpointHitCallback callback, + const BatonSP &callback_baton_sp, + bool is_synchronous) { + m_options.SetCallback(callback, callback_baton_sp, is_synchronous); + SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged); } -void -Watchpoint::ClearCallback () -{ - m_options.ClearCallback (); - SendWatchpointChangedEvent (eWatchpointEventTypeCommandChanged); +void Watchpoint::ClearCallback() { + m_options.ClearCallback(); + SendWatchpointChangedEvent(eWatchpointEventTypeCommandChanged); } -void -Watchpoint::SetDeclInfo (const std::string &str) -{ - m_decl_str = str; -} +void Watchpoint::SetDeclInfo(const std::string &str) { m_decl_str = str; } -std::string -Watchpoint::GetWatchSpec() -{ - return m_watch_spec_str; -} +std::string Watchpoint::GetWatchSpec() { return m_watch_spec_str; } -void -Watchpoint::SetWatchSpec (const std::string &str) -{ - m_watch_spec_str = str; +void Watchpoint::SetWatchSpec(const std::string &str) { + m_watch_spec_str = str; } // Override default impl of StoppointLocation::IsHardware() since m_is_hardware // member field is more accurate. -bool -Watchpoint::IsHardware () const -{ - return m_is_hardware; -} - -bool -Watchpoint::IsWatchVariable() const -{ - return m_is_watch_variable; -} - -void -Watchpoint::SetWatchVariable(bool val) -{ - m_is_watch_variable = val; -} - -bool -Watchpoint::CaptureWatchedValue (const ExecutionContext &exe_ctx) -{ - ConstString watch_name("$__lldb__watch_value"); - m_old_value_sp = m_new_value_sp; - Address watch_address(GetLoadAddress()); - if (!m_type.IsValid()) - { - // Don't know how to report new & old values, since we couldn't make a scalar type for this watchpoint. - // This works around an assert in ValueObjectMemory::Create. - // FIXME: This should not happen, but if it does in some case we care about, - // we can go grab the value raw and print it as unsigned. - return false; - } - m_new_value_sp = ValueObjectMemory::Create (exe_ctx.GetBestExecutionContextScope(), watch_name.AsCString(), watch_address, m_type); - m_new_value_sp = m_new_value_sp->CreateConstantValue(watch_name); - return (m_new_value_sp && m_new_value_sp->GetError().Success()); -} - -void -Watchpoint::IncrementFalseAlarmsAndReviseHitCount() -{ - ++m_false_alarms; - if (m_false_alarms) - { - if (m_hit_count >= m_false_alarms) - { - m_hit_count -= m_false_alarms; - m_false_alarms = 0; - } - else - { - m_false_alarms -= m_hit_count; - m_hit_count = 0; - } +bool Watchpoint::IsHardware() const { return m_is_hardware; } + +bool Watchpoint::IsWatchVariable() const { return m_is_watch_variable; } + +void Watchpoint::SetWatchVariable(bool val) { m_is_watch_variable = val; } + +bool Watchpoint::CaptureWatchedValue(const ExecutionContext &exe_ctx) { + ConstString watch_name("$__lldb__watch_value"); + m_old_value_sp = m_new_value_sp; + Address watch_address(GetLoadAddress()); + if (!m_type.IsValid()) { + // Don't know how to report new & old values, since we couldn't make a + // scalar type for this watchpoint. + // This works around an assert in ValueObjectMemory::Create. + // FIXME: This should not happen, but if it does in some case we care about, + // we can go grab the value raw and print it as unsigned. + return false; + } + m_new_value_sp = + ValueObjectMemory::Create(exe_ctx.GetBestExecutionContextScope(), + watch_name.AsCString(), watch_address, m_type); + m_new_value_sp = m_new_value_sp->CreateConstantValue(watch_name); + return (m_new_value_sp && m_new_value_sp->GetError().Success()); +} + +void Watchpoint::IncrementFalseAlarmsAndReviseHitCount() { + ++m_false_alarms; + if (m_false_alarms) { + if (m_hit_count >= m_false_alarms) { + m_hit_count -= m_false_alarms; + m_false_alarms = 0; + } else { + m_false_alarms -= m_hit_count; + m_hit_count = 0; } + } } // RETURNS - true if we should stop at this breakpoint, false if we // should continue. -bool -Watchpoint::ShouldStop (StoppointCallbackContext *context) -{ - IncrementHitCount(); +bool Watchpoint::ShouldStop(StoppointCallbackContext *context) { + IncrementHitCount(); - if (!IsEnabled()) - return false; + if (!IsEnabled()) + return false; - return true; + return true; } -void -Watchpoint::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - DumpWithLevel(s, level); +void Watchpoint::GetDescription(Stream *s, lldb::DescriptionLevel level) { + DumpWithLevel(s, level); } -void -Watchpoint::Dump(Stream *s) const -{ - DumpWithLevel(s, lldb::eDescriptionLevelBrief); +void Watchpoint::Dump(Stream *s) const { + DumpWithLevel(s, lldb::eDescriptionLevelBrief); } -// If prefix is nullptr, we display the watch id and ignore the prefix altogether. -void -Watchpoint::DumpSnapshots(Stream *s, const char *prefix) const -{ - if (!prefix) - { - s->Printf("\nWatchpoint %u hit:", GetID()); - prefix = ""; - } +// If prefix is nullptr, we display the watch id and ignore the prefix +// altogether. +void Watchpoint::DumpSnapshots(Stream *s, const char *prefix) const { + if (!prefix) { + s->Printf("\nWatchpoint %u hit:", GetID()); + prefix = ""; + } - if (m_old_value_sp) - { - const char *old_value_cstr = m_old_value_sp->GetValueAsCString(); - if (old_value_cstr && old_value_cstr[0]) - s->Printf("\n%sold value: %s", prefix, old_value_cstr); - else - { - const char *old_summary_cstr = m_old_value_sp-> GetSummaryAsCString(); - if (old_summary_cstr && old_summary_cstr[0]) - s->Printf("\n%sold value: %s", prefix, old_summary_cstr); - } + if (m_old_value_sp) { + const char *old_value_cstr = m_old_value_sp->GetValueAsCString(); + if (old_value_cstr && old_value_cstr[0]) + s->Printf("\n%sold value: %s", prefix, old_value_cstr); + else { + const char *old_summary_cstr = m_old_value_sp->GetSummaryAsCString(); + if (old_summary_cstr && old_summary_cstr[0]) + s->Printf("\n%sold value: %s", prefix, old_summary_cstr); } - - if (m_new_value_sp) - { - const char *new_value_cstr = m_new_value_sp->GetValueAsCString(); - if (new_value_cstr && new_value_cstr[0]) - s->Printf("\n%snew value: %s", prefix, new_value_cstr); - else - { - const char *new_summary_cstr = m_new_value_sp-> GetSummaryAsCString(); - if (new_summary_cstr && new_summary_cstr[0]) - s->Printf("\n%snew value: %s", prefix, new_summary_cstr); - } + } + + if (m_new_value_sp) { + const char *new_value_cstr = m_new_value_sp->GetValueAsCString(); + if (new_value_cstr && new_value_cstr[0]) + s->Printf("\n%snew value: %s", prefix, new_value_cstr); + else { + const char *new_summary_cstr = m_new_value_sp->GetSummaryAsCString(); + if (new_summary_cstr && new_summary_cstr[0]) + s->Printf("\n%snew value: %s", prefix, new_summary_cstr); } + } } -void -Watchpoint::DumpWithLevel(Stream *s, lldb::DescriptionLevel description_level) const -{ - if (s == nullptr) - return; - - assert(description_level >= lldb::eDescriptionLevelBrief && - description_level <= lldb::eDescriptionLevelVerbose); - - s->Printf("Watchpoint %u: addr = 0x%8.8" PRIx64 " size = %u state = %s type = %s%s", - GetID(), - GetLoadAddress(), - m_byte_size, - IsEnabled() ? "enabled" : "disabled", - m_watch_read ? "r" : "", - m_watch_write ? "w" : ""); - - if (description_level >= lldb::eDescriptionLevelFull) { - if (!m_decl_str.empty()) - s->Printf("\n declare @ '%s'", m_decl_str.c_str()); - if (!m_watch_spec_str.empty()) - s->Printf("\n watchpoint spec = '%s'", m_watch_spec_str.c_str()); - - // Dump the snapshots we have taken. - DumpSnapshots(s, " "); - - if (GetConditionText()) - s->Printf("\n condition = '%s'", GetConditionText()); - m_options.GetCallbackDescription(s, description_level); - } +void Watchpoint::DumpWithLevel(Stream *s, + lldb::DescriptionLevel description_level) const { + if (s == nullptr) + return; - if (description_level >= lldb::eDescriptionLevelVerbose) - { - s->Printf("\n hw_index = %i hit_count = %-4u ignore_count = %-4u", - GetHardwareIndex(), - GetHitCount(), - GetIgnoreCount()); - } -} + assert(description_level >= lldb::eDescriptionLevelBrief && + description_level <= lldb::eDescriptionLevelVerbose); -bool -Watchpoint::IsEnabled() const -{ - return m_enabled; -} + s->Printf("Watchpoint %u: addr = 0x%8.8" PRIx64 + " size = %u state = %s type = %s%s", + GetID(), GetLoadAddress(), m_byte_size, + IsEnabled() ? "enabled" : "disabled", m_watch_read ? "r" : "", + m_watch_write ? "w" : ""); -// Within StopInfo.cpp, we purposely turn on the ephemeral mode right before temporarily disable the watchpoint -// in order to perform possible watchpoint actions without triggering further watchpoint events. -// After the temporary disabled watchpoint is enabled, we then turn off the ephemeral mode. + if (description_level >= lldb::eDescriptionLevelFull) { + if (!m_decl_str.empty()) + s->Printf("\n declare @ '%s'", m_decl_str.c_str()); + if (!m_watch_spec_str.empty()) + s->Printf("\n watchpoint spec = '%s'", m_watch_spec_str.c_str()); -void -Watchpoint::TurnOnEphemeralMode() -{ - m_is_ephemeral = true; -} + // Dump the snapshots we have taken. + DumpSnapshots(s, " "); -void -Watchpoint::TurnOffEphemeralMode() -{ - m_is_ephemeral = false; - // Leaving ephemeral mode, reset the m_disabled_count! - m_disabled_count = 0; -} + if (GetConditionText()) + s->Printf("\n condition = '%s'", GetConditionText()); + m_options.GetCallbackDescription(s, description_level); + } -bool -Watchpoint::IsDisabledDuringEphemeralMode() -{ - return m_disabled_count > 1; + if (description_level >= lldb::eDescriptionLevelVerbose) { + s->Printf("\n hw_index = %i hit_count = %-4u ignore_count = %-4u", + GetHardwareIndex(), GetHitCount(), GetIgnoreCount()); + } } -void -Watchpoint::SetEnabled(bool enabled, bool notify) -{ - if (!enabled) - { - if (!m_is_ephemeral) - SetHardwareIndex(LLDB_INVALID_INDEX32); - else - ++m_disabled_count; - - // Don't clear the snapshots for now. - // Within StopInfo.cpp, we purposely do disable/enable watchpoint while performing watchpoint actions. - } - bool changed = enabled != m_enabled; - m_enabled = enabled; - if (notify && !m_is_ephemeral && changed) - SendWatchpointChangedEvent (enabled ? eWatchpointEventTypeEnabled : eWatchpointEventTypeDisabled); -} +bool Watchpoint::IsEnabled() const { return m_enabled; } -void -Watchpoint::SetWatchpointType (uint32_t type, bool notify) -{ - int old_watch_read = m_watch_read; - int old_watch_write = m_watch_write; - m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0; - m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0; - if (notify && (old_watch_read != m_watch_read || old_watch_write != m_watch_write)) - SendWatchpointChangedEvent (eWatchpointEventTypeTypeChanged); -} +// Within StopInfo.cpp, we purposely turn on the ephemeral mode right before +// temporarily disable the watchpoint +// in order to perform possible watchpoint actions without triggering further +// watchpoint events. +// After the temporary disabled watchpoint is enabled, we then turn off the +// ephemeral mode. + +void Watchpoint::TurnOnEphemeralMode() { m_is_ephemeral = true; } -bool -Watchpoint::WatchpointRead () const -{ - return m_watch_read != 0; +void Watchpoint::TurnOffEphemeralMode() { + m_is_ephemeral = false; + // Leaving ephemeral mode, reset the m_disabled_count! + m_disabled_count = 0; } -bool -Watchpoint::WatchpointWrite () const -{ - return m_watch_write != 0; +bool Watchpoint::IsDisabledDuringEphemeralMode() { + return m_disabled_count > 1; } -uint32_t -Watchpoint::GetIgnoreCount () const -{ - return m_ignore_count; +void Watchpoint::SetEnabled(bool enabled, bool notify) { + if (!enabled) { + if (!m_is_ephemeral) + SetHardwareIndex(LLDB_INVALID_INDEX32); + else + ++m_disabled_count; + + // Don't clear the snapshots for now. + // Within StopInfo.cpp, we purposely do disable/enable watchpoint while + // performing watchpoint actions. + } + bool changed = enabled != m_enabled; + m_enabled = enabled; + if (notify && !m_is_ephemeral && changed) + SendWatchpointChangedEvent(enabled ? eWatchpointEventTypeEnabled + : eWatchpointEventTypeDisabled); } -void -Watchpoint::SetIgnoreCount (uint32_t n) -{ - bool changed = m_ignore_count != n; - m_ignore_count = n; - if (changed) - SendWatchpointChangedEvent (eWatchpointEventTypeIgnoreChanged); +void Watchpoint::SetWatchpointType(uint32_t type, bool notify) { + int old_watch_read = m_watch_read; + int old_watch_write = m_watch_write; + m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0; + m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0; + if (notify && + (old_watch_read != m_watch_read || old_watch_write != m_watch_write)) + SendWatchpointChangedEvent(eWatchpointEventTypeTypeChanged); } -bool -Watchpoint::InvokeCallback (StoppointCallbackContext *context) -{ - return m_options.InvokeCallback (context, GetID()); +bool Watchpoint::WatchpointRead() const { return m_watch_read != 0; } + +bool Watchpoint::WatchpointWrite() const { return m_watch_write != 0; } + +uint32_t Watchpoint::GetIgnoreCount() const { return m_ignore_count; } + +void Watchpoint::SetIgnoreCount(uint32_t n) { + bool changed = m_ignore_count != n; + m_ignore_count = n; + if (changed) + SendWatchpointChangedEvent(eWatchpointEventTypeIgnoreChanged); } -void -Watchpoint::SetCondition (const char *condition) -{ - if (condition == nullptr || condition[0] == '\0') - { - if (m_condition_ap.get()) - m_condition_ap.reset(); - } - else - { - // Pass nullptr for expr_prefix (no translation-unit level definitions). - Error error; - m_condition_ap.reset(m_target.GetUserExpressionForLanguage(condition, - nullptr, - lldb::eLanguageTypeUnknown, - UserExpression::eResultTypeAny, - EvaluateExpressionOptions(), - error)); - if (error.Fail()) - { - // FIXME: Log something... - m_condition_ap.reset(); - } - } - SendWatchpointChangedEvent (eWatchpointEventTypeConditionChanged); +bool Watchpoint::InvokeCallback(StoppointCallbackContext *context) { + return m_options.InvokeCallback(context, GetID()); } -const char * -Watchpoint::GetConditionText () const -{ +void Watchpoint::SetCondition(const char *condition) { + if (condition == nullptr || condition[0] == '\0') { if (m_condition_ap.get()) - return m_condition_ap->GetUserText(); - else - return nullptr; + m_condition_ap.reset(); + } else { + // Pass nullptr for expr_prefix (no translation-unit level definitions). + Error error; + m_condition_ap.reset(m_target.GetUserExpressionForLanguage( + condition, nullptr, lldb::eLanguageTypeUnknown, + UserExpression::eResultTypeAny, EvaluateExpressionOptions(), error)); + if (error.Fail()) { + // FIXME: Log something... + m_condition_ap.reset(); + } + } + SendWatchpointChangedEvent(eWatchpointEventTypeConditionChanged); } -void -Watchpoint::SendWatchpointChangedEvent (lldb::WatchpointEventType eventKind) -{ - if (!m_being_created - && GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged)) - { - WatchpointEventData *data = new Watchpoint::WatchpointEventData (eventKind, shared_from_this()); - GetTarget().BroadcastEvent (Target::eBroadcastBitWatchpointChanged, data); - } +const char *Watchpoint::GetConditionText() const { + if (m_condition_ap.get()) + return m_condition_ap->GetUserText(); + else + return nullptr; } -void -Watchpoint::SendWatchpointChangedEvent (WatchpointEventData *data) -{ - if (data == nullptr) - return; - - if (!m_being_created - && GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged)) - GetTarget().BroadcastEvent (Target::eBroadcastBitWatchpointChanged, data); - else - delete data; +void Watchpoint::SendWatchpointChangedEvent( + lldb::WatchpointEventType eventKind) { + if (!m_being_created && + GetTarget().EventTypeHasListeners( + Target::eBroadcastBitWatchpointChanged)) { + WatchpointEventData *data = + new Watchpoint::WatchpointEventData(eventKind, shared_from_this()); + GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data); + } } -Watchpoint::WatchpointEventData::WatchpointEventData (WatchpointEventType sub_type, - const WatchpointSP &new_watchpoint_sp) : - EventData (), - m_watchpoint_event (sub_type), - m_new_watchpoint_sp (new_watchpoint_sp) -{ +void Watchpoint::SendWatchpointChangedEvent(WatchpointEventData *data) { + if (data == nullptr) + return; + + if (!m_being_created && + GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged)) + GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, data); + else + delete data; } +Watchpoint::WatchpointEventData::WatchpointEventData( + WatchpointEventType sub_type, const WatchpointSP &new_watchpoint_sp) + : EventData(), m_watchpoint_event(sub_type), + m_new_watchpoint_sp(new_watchpoint_sp) {} + Watchpoint::WatchpointEventData::~WatchpointEventData() = default; -const ConstString & -Watchpoint::WatchpointEventData::GetFlavorString () -{ - static ConstString g_flavor ("Watchpoint::WatchpointEventData"); - return g_flavor; +const ConstString &Watchpoint::WatchpointEventData::GetFlavorString() { + static ConstString g_flavor("Watchpoint::WatchpointEventData"); + return g_flavor; } -const ConstString & -Watchpoint::WatchpointEventData::GetFlavor () const -{ - return WatchpointEventData::GetFlavorString (); +const ConstString &Watchpoint::WatchpointEventData::GetFlavor() const { + return WatchpointEventData::GetFlavorString(); } -WatchpointSP & -Watchpoint::WatchpointEventData::GetWatchpoint () -{ - return m_new_watchpoint_sp; +WatchpointSP &Watchpoint::WatchpointEventData::GetWatchpoint() { + return m_new_watchpoint_sp; } WatchpointEventType -Watchpoint::WatchpointEventData::GetWatchpointEventType () const -{ - return m_watchpoint_event; +Watchpoint::WatchpointEventData::GetWatchpointEventType() const { + return m_watchpoint_event; } -void -Watchpoint::WatchpointEventData::Dump (Stream *s) const -{ -} +void Watchpoint::WatchpointEventData::Dump(Stream *s) const {} const Watchpoint::WatchpointEventData * -Watchpoint::WatchpointEventData::GetEventDataFromEvent (const Event *event) -{ - if (event) - { - const EventData *event_data = event->GetData(); - if (event_data && event_data->GetFlavor() == WatchpointEventData::GetFlavorString()) - return static_cast (event->GetData()); - } - return nullptr; +Watchpoint::WatchpointEventData::GetEventDataFromEvent(const Event *event) { + if (event) { + const EventData *event_data = event->GetData(); + if (event_data && + event_data->GetFlavor() == WatchpointEventData::GetFlavorString()) + return static_cast(event->GetData()); + } + return nullptr; } WatchpointEventType -Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent (const EventSP &event_sp) -{ - const WatchpointEventData *data = GetEventDataFromEvent (event_sp.get()); +Watchpoint::WatchpointEventData::GetWatchpointEventTypeFromEvent( + const EventSP &event_sp) { + const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get()); - if (data == nullptr) - return eWatchpointEventTypeInvalidType; - else - return data->GetWatchpointEventType(); + if (data == nullptr) + return eWatchpointEventTypeInvalidType; + else + return data->GetWatchpointEventType(); } -WatchpointSP -Watchpoint::WatchpointEventData::GetWatchpointFromEvent (const EventSP &event_sp) -{ - WatchpointSP wp_sp; +WatchpointSP Watchpoint::WatchpointEventData::GetWatchpointFromEvent( + const EventSP &event_sp) { + WatchpointSP wp_sp; - const WatchpointEventData *data = GetEventDataFromEvent (event_sp.get()); - if (data) - wp_sp = data->m_new_watchpoint_sp; + const WatchpointEventData *data = GetEventDataFromEvent(event_sp.get()); + if (data) + wp_sp = data->m_new_watchpoint_sp; - return wp_sp; + return wp_sp; } diff --git a/lldb/source/Breakpoint/WatchpointList.cpp b/lldb/source/Breakpoint/WatchpointList.cpp index f662c24cece..6ec3bd09c14 100644 --- a/lldb/source/Breakpoint/WatchpointList.cpp +++ b/lldb/source/Breakpoint/WatchpointList.cpp @@ -7,7 +7,6 @@ // //===----------------------------------------------------------------------===// - // C Includes // C++ Includes // Other libraries and framework includes @@ -18,291 +17,241 @@ using namespace lldb; using namespace lldb_private; -WatchpointList::WatchpointList() : m_watchpoints(), m_mutex(), m_next_wp_id(0) -{ -} +WatchpointList::WatchpointList() + : m_watchpoints(), m_mutex(), m_next_wp_id(0) {} -WatchpointList::~WatchpointList() -{ -} +WatchpointList::~WatchpointList() {} // Add a watchpoint to the list. -lldb::watch_id_t -WatchpointList::Add (const WatchpointSP &wp_sp, bool notify) -{ - std::lock_guard guard(m_mutex); - wp_sp->SetID(++m_next_wp_id); - m_watchpoints.push_back(wp_sp); - if (notify) - { - if (wp_sp->GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged)) - wp_sp->GetTarget().BroadcastEvent (Target::eBroadcastBitWatchpointChanged, - new Watchpoint::WatchpointEventData (eWatchpointEventTypeAdded, wp_sp)); - } - return wp_sp->GetID(); +lldb::watch_id_t WatchpointList::Add(const WatchpointSP &wp_sp, bool notify) { + std::lock_guard guard(m_mutex); + wp_sp->SetID(++m_next_wp_id); + m_watchpoints.push_back(wp_sp); + if (notify) { + if (wp_sp->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitWatchpointChanged)) + wp_sp->GetTarget().BroadcastEvent(Target::eBroadcastBitWatchpointChanged, + new Watchpoint::WatchpointEventData( + eWatchpointEventTypeAdded, wp_sp)); + } + return wp_sp->GetID(); } -void -WatchpointList::Dump (Stream *s) const -{ - DumpWithLevel(s, lldb::eDescriptionLevelBrief); +void WatchpointList::Dump(Stream *s) const { + DumpWithLevel(s, lldb::eDescriptionLevelBrief); } -void -WatchpointList::DumpWithLevel (Stream *s, lldb::DescriptionLevel description_level) const -{ - std::lock_guard guard(m_mutex); - s->Printf("%p: ", static_cast(this)); - //s->Indent(); - s->Printf("WatchpointList with %" PRIu64 " Watchpoints:\n", - (uint64_t)m_watchpoints.size()); - s->IndentMore(); - wp_collection::const_iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - (*pos)->DumpWithLevel(s, description_level); - s->IndentLess(); +void WatchpointList::DumpWithLevel( + Stream *s, lldb::DescriptionLevel description_level) const { + std::lock_guard guard(m_mutex); + s->Printf("%p: ", static_cast(this)); + // s->Indent(); + s->Printf("WatchpointList with %" PRIu64 " Watchpoints:\n", + (uint64_t)m_watchpoints.size()); + s->IndentMore(); + wp_collection::const_iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) + (*pos)->DumpWithLevel(s, description_level); + s->IndentLess(); } -const WatchpointSP -WatchpointList::FindByAddress (lldb::addr_t addr) const -{ - WatchpointSP wp_sp; - std::lock_guard guard(m_mutex); - if (!m_watchpoints.empty()) - { - wp_collection::const_iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - { - lldb::addr_t wp_addr = (*pos)->GetLoadAddress(); - uint32_t wp_bytesize = (*pos)->GetByteSize(); - if ((wp_addr <= addr) && ((wp_addr + wp_bytesize) > addr)) - { - wp_sp = *pos; - break; - } - } +const WatchpointSP WatchpointList::FindByAddress(lldb::addr_t addr) const { + WatchpointSP wp_sp; + std::lock_guard guard(m_mutex); + if (!m_watchpoints.empty()) { + wp_collection::const_iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) { + lldb::addr_t wp_addr = (*pos)->GetLoadAddress(); + uint32_t wp_bytesize = (*pos)->GetByteSize(); + if ((wp_addr <= addr) && ((wp_addr + wp_bytesize) > addr)) { + wp_sp = *pos; + break; + } } + } - return wp_sp; + return wp_sp; } -const WatchpointSP -WatchpointList::FindBySpec (std::string spec) const -{ - WatchpointSP wp_sp; - std::lock_guard guard(m_mutex); - if (!m_watchpoints.empty()) - { - wp_collection::const_iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - if ((*pos)->GetWatchSpec() == spec) { - wp_sp = *pos; - break; - } - } +const WatchpointSP WatchpointList::FindBySpec(std::string spec) const { + WatchpointSP wp_sp; + std::lock_guard guard(m_mutex); + if (!m_watchpoints.empty()) { + wp_collection::const_iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) + if ((*pos)->GetWatchSpec() == spec) { + wp_sp = *pos; + break; + } + } - return wp_sp; + return wp_sp; } -class WatchpointIDMatches -{ +class WatchpointIDMatches { public: - WatchpointIDMatches (lldb::watch_id_t watch_id) : - m_watch_id(watch_id) - { - } + WatchpointIDMatches(lldb::watch_id_t watch_id) : m_watch_id(watch_id) {} - bool operator() (const WatchpointSP &wp) const - { - return m_watch_id == wp->GetID(); - } + bool operator()(const WatchpointSP &wp) const { + return m_watch_id == wp->GetID(); + } private: - const lldb::watch_id_t m_watch_id; + const lldb::watch_id_t m_watch_id; }; WatchpointList::wp_collection::iterator -WatchpointList::GetIDIterator (lldb::watch_id_t watch_id) -{ - return std::find_if(m_watchpoints.begin(), m_watchpoints.end(), // Search full range - WatchpointIDMatches(watch_id)); // Predicate +WatchpointList::GetIDIterator(lldb::watch_id_t watch_id) { + return std::find_if(m_watchpoints.begin(), + m_watchpoints.end(), // Search full range + WatchpointIDMatches(watch_id)); // Predicate } WatchpointList::wp_collection::const_iterator -WatchpointList::GetIDConstIterator (lldb::watch_id_t watch_id) const -{ - return std::find_if(m_watchpoints.begin(), m_watchpoints.end(), // Search full range - WatchpointIDMatches(watch_id)); // Predicate +WatchpointList::GetIDConstIterator(lldb::watch_id_t watch_id) const { + return std::find_if(m_watchpoints.begin(), + m_watchpoints.end(), // Search full range + WatchpointIDMatches(watch_id)); // Predicate } -WatchpointSP -WatchpointList::FindByID (lldb::watch_id_t watch_id) const -{ - WatchpointSP wp_sp; - std::lock_guard guard(m_mutex); - wp_collection::const_iterator pos = GetIDConstIterator(watch_id); - if (pos != m_watchpoints.end()) - wp_sp = *pos; +WatchpointSP WatchpointList::FindByID(lldb::watch_id_t watch_id) const { + WatchpointSP wp_sp; + std::lock_guard guard(m_mutex); + wp_collection::const_iterator pos = GetIDConstIterator(watch_id); + if (pos != m_watchpoints.end()) + wp_sp = *pos; - return wp_sp; + return wp_sp; } -lldb::watch_id_t -WatchpointList::FindIDByAddress (lldb::addr_t addr) -{ - WatchpointSP wp_sp = FindByAddress (addr); - if (wp_sp) - { - return wp_sp->GetID(); - } - return LLDB_INVALID_WATCH_ID; +lldb::watch_id_t WatchpointList::FindIDByAddress(lldb::addr_t addr) { + WatchpointSP wp_sp = FindByAddress(addr); + if (wp_sp) { + return wp_sp->GetID(); + } + return LLDB_INVALID_WATCH_ID; } -lldb::watch_id_t -WatchpointList::FindIDBySpec (std::string spec) -{ - WatchpointSP wp_sp = FindBySpec (spec); - if (wp_sp) - { - return wp_sp->GetID(); - } - return LLDB_INVALID_WATCH_ID; +lldb::watch_id_t WatchpointList::FindIDBySpec(std::string spec) { + WatchpointSP wp_sp = FindBySpec(spec); + if (wp_sp) { + return wp_sp->GetID(); + } + return LLDB_INVALID_WATCH_ID; } -WatchpointSP -WatchpointList::GetByIndex (uint32_t i) -{ - std::lock_guard guard(m_mutex); - WatchpointSP wp_sp; - if (i < m_watchpoints.size()) - { - wp_collection::const_iterator pos = m_watchpoints.begin(); - std::advance(pos, i); - wp_sp = *pos; - } - return wp_sp; +WatchpointSP WatchpointList::GetByIndex(uint32_t i) { + std::lock_guard guard(m_mutex); + WatchpointSP wp_sp; + if (i < m_watchpoints.size()) { + wp_collection::const_iterator pos = m_watchpoints.begin(); + std::advance(pos, i); + wp_sp = *pos; + } + return wp_sp; } -const WatchpointSP -WatchpointList::GetByIndex (uint32_t i) const -{ - std::lock_guard guard(m_mutex); - WatchpointSP wp_sp; - if (i < m_watchpoints.size()) - { - wp_collection::const_iterator pos = m_watchpoints.begin(); - std::advance(pos, i); - wp_sp = *pos; - } - return wp_sp; +const WatchpointSP WatchpointList::GetByIndex(uint32_t i) const { + std::lock_guard guard(m_mutex); + WatchpointSP wp_sp; + if (i < m_watchpoints.size()) { + wp_collection::const_iterator pos = m_watchpoints.begin(); + std::advance(pos, i); + wp_sp = *pos; + } + return wp_sp; } -std::vector -WatchpointList::GetWatchpointIDs() const -{ - std::vector IDs; - wp_collection::const_iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - IDs.push_back((*pos)->GetID()); - return IDs; +std::vector WatchpointList::GetWatchpointIDs() const { + std::vector IDs; + wp_collection::const_iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) + IDs.push_back((*pos)->GetID()); + return IDs; } -bool -WatchpointList::Remove (lldb::watch_id_t watch_id, bool notify) -{ - std::lock_guard guard(m_mutex); - wp_collection::iterator pos = GetIDIterator(watch_id); - if (pos != m_watchpoints.end()) - { - WatchpointSP wp_sp = *pos; - if (notify) - { - if (wp_sp->GetTarget().EventTypeHasListeners(Target::eBroadcastBitWatchpointChanged)) - wp_sp->GetTarget().BroadcastEvent (Target::eBroadcastBitWatchpointChanged, - new Watchpoint::WatchpointEventData (eWatchpointEventTypeRemoved, wp_sp)); - } - m_watchpoints.erase(pos); - return true; +bool WatchpointList::Remove(lldb::watch_id_t watch_id, bool notify) { + std::lock_guard guard(m_mutex); + wp_collection::iterator pos = GetIDIterator(watch_id); + if (pos != m_watchpoints.end()) { + WatchpointSP wp_sp = *pos; + if (notify) { + if (wp_sp->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitWatchpointChanged)) + wp_sp->GetTarget().BroadcastEvent( + Target::eBroadcastBitWatchpointChanged, + new Watchpoint::WatchpointEventData(eWatchpointEventTypeRemoved, + wp_sp)); } - return false; + m_watchpoints.erase(pos); + return true; + } + return false; } -uint32_t -WatchpointList::GetHitCount () const -{ - uint32_t hit_count = 0; - std::lock_guard guard(m_mutex); - wp_collection::const_iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - hit_count += (*pos)->GetHitCount(); - return hit_count; +uint32_t WatchpointList::GetHitCount() const { + uint32_t hit_count = 0; + std::lock_guard guard(m_mutex); + wp_collection::const_iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) + hit_count += (*pos)->GetHitCount(); + return hit_count; } -bool -WatchpointList::ShouldStop (StoppointCallbackContext *context, lldb::watch_id_t watch_id) -{ - - WatchpointSP wp_sp = FindByID (watch_id); - if (wp_sp) - { - // Let the Watchpoint decide if it should stop here (could not have - // reached it's target hit count yet, or it could have a callback - // that decided it shouldn't stop. - return wp_sp->ShouldStop (context); - } - // We should stop here since this Watchpoint isn't valid anymore or it - // doesn't exist. - return true; +bool WatchpointList::ShouldStop(StoppointCallbackContext *context, + lldb::watch_id_t watch_id) { + + WatchpointSP wp_sp = FindByID(watch_id); + if (wp_sp) { + // Let the Watchpoint decide if it should stop here (could not have + // reached it's target hit count yet, or it could have a callback + // that decided it shouldn't stop. + return wp_sp->ShouldStop(context); + } + // We should stop here since this Watchpoint isn't valid anymore or it + // doesn't exist. + return true; } -void -WatchpointList::GetDescription (Stream *s, lldb::DescriptionLevel level) -{ - std::lock_guard guard(m_mutex); - wp_collection::iterator pos, end = m_watchpoints.end(); +void WatchpointList::GetDescription(Stream *s, lldb::DescriptionLevel level) { + std::lock_guard guard(m_mutex); + wp_collection::iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - { - s->Printf(" "); - (*pos)->Dump(s); - } + for (pos = m_watchpoints.begin(); pos != end; ++pos) { + s->Printf(" "); + (*pos)->Dump(s); + } } -void -WatchpointList::SetEnabledAll (bool enabled) -{ - std::lock_guard guard(m_mutex); +void WatchpointList::SetEnabledAll(bool enabled) { + std::lock_guard guard(m_mutex); - wp_collection::iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - (*pos)->SetEnabled (enabled); + wp_collection::iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) + (*pos)->SetEnabled(enabled); } -void -WatchpointList::RemoveAll (bool notify) -{ - std::lock_guard guard(m_mutex); - if (notify) +void WatchpointList::RemoveAll(bool notify) { + std::lock_guard guard(m_mutex); + if (notify) { + { - - { - wp_collection::iterator pos, end = m_watchpoints.end(); - for (pos = m_watchpoints.begin(); pos != end; ++pos) - { - if ((*pos)->GetTarget().EventTypeHasListeners(Target::eBroadcastBitBreakpointChanged)) - { - (*pos)->GetTarget().BroadcastEvent (Target::eBroadcastBitWatchpointChanged, - new Watchpoint::WatchpointEventData (eWatchpointEventTypeRemoved, - *pos)); - } - } + wp_collection::iterator pos, end = m_watchpoints.end(); + for (pos = m_watchpoints.begin(); pos != end; ++pos) { + if ((*pos)->GetTarget().EventTypeHasListeners( + Target::eBroadcastBitBreakpointChanged)) { + (*pos)->GetTarget().BroadcastEvent( + Target::eBroadcastBitWatchpointChanged, + new Watchpoint::WatchpointEventData(eWatchpointEventTypeRemoved, + *pos)); } + } } - m_watchpoints.clear(); + } + m_watchpoints.clear(); } -void -WatchpointList::GetListMutex(std::unique_lock &lock) -{ - lock = std::unique_lock(m_mutex); +void WatchpointList::GetListMutex( + std::unique_lock &lock) { + lock = std::unique_lock(m_mutex); } diff --git a/lldb/source/Breakpoint/WatchpointOptions.cpp b/lldb/source/Breakpoint/WatchpointOptions.cpp index 365d884691e..1108f44561c 100644 --- a/lldb/source/Breakpoint/WatchpointOptions.cpp +++ b/lldb/source/Breakpoint/WatchpointOptions.cpp @@ -13,10 +13,10 @@ // Project includes #include "lldb/Breakpoint/WatchpointOptions.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StringList.h" #include "lldb/Core/Value.h" -#include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadSpec.h" @@ -24,63 +24,55 @@ using namespace lldb; using namespace lldb_private; -bool -WatchpointOptions::NullCallback (void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id) -{ - return true; +bool WatchpointOptions::NullCallback(void *baton, + StoppointCallbackContext *context, + lldb::user_id_t watch_id) { + return true; } //---------------------------------------------------------------------- // WatchpointOptions constructor //---------------------------------------------------------------------- -WatchpointOptions::WatchpointOptions() : - m_callback (WatchpointOptions::NullCallback), - m_callback_baton_sp (), - m_callback_is_synchronous (false), - m_thread_spec_ap () -{ -} +WatchpointOptions::WatchpointOptions() + : m_callback(WatchpointOptions::NullCallback), m_callback_baton_sp(), + m_callback_is_synchronous(false), m_thread_spec_ap() {} //---------------------------------------------------------------------- // WatchpointOptions copy constructor //---------------------------------------------------------------------- -WatchpointOptions::WatchpointOptions(const WatchpointOptions& rhs) : - m_callback (rhs.m_callback), - m_callback_baton_sp (rhs.m_callback_baton_sp), - m_callback_is_synchronous (rhs.m_callback_is_synchronous), - m_thread_spec_ap () -{ - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get())); +WatchpointOptions::WatchpointOptions(const WatchpointOptions &rhs) + : m_callback(rhs.m_callback), m_callback_baton_sp(rhs.m_callback_baton_sp), + m_callback_is_synchronous(rhs.m_callback_is_synchronous), + m_thread_spec_ap() { + if (rhs.m_thread_spec_ap.get() != nullptr) + m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); } //---------------------------------------------------------------------- // WatchpointOptions assignment operator //---------------------------------------------------------------------- -const WatchpointOptions& -WatchpointOptions::operator=(const WatchpointOptions& rhs) -{ - m_callback = rhs.m_callback; - m_callback_baton_sp = rhs.m_callback_baton_sp; - m_callback_is_synchronous = rhs.m_callback_is_synchronous; - if (rhs.m_thread_spec_ap.get() != nullptr) - m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); - return *this; +const WatchpointOptions &WatchpointOptions:: +operator=(const WatchpointOptions &rhs) { + m_callback = rhs.m_callback; + m_callback_baton_sp = rhs.m_callback_baton_sp; + m_callback_is_synchronous = rhs.m_callback_is_synchronous; + if (rhs.m_thread_spec_ap.get() != nullptr) + m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get())); + return *this; } WatchpointOptions * -WatchpointOptions::CopyOptionsNoCallback (WatchpointOptions &orig) -{ - WatchpointHitCallback orig_callback = orig.m_callback; - lldb::BatonSP orig_callback_baton_sp = orig.m_callback_baton_sp; - bool orig_is_sync = orig.m_callback_is_synchronous; - - orig.ClearCallback(); - WatchpointOptions *ret_val = new WatchpointOptions(orig); - - orig.SetCallback (orig_callback, orig_callback_baton_sp, orig_is_sync); - - return ret_val; +WatchpointOptions::CopyOptionsNoCallback(WatchpointOptions &orig) { + WatchpointHitCallback orig_callback = orig.m_callback; + lldb::BatonSP orig_callback_baton_sp = orig.m_callback_baton_sp; + bool orig_is_sync = orig.m_callback_is_synchronous; + + orig.ClearCallback(); + WatchpointOptions *ret_val = new WatchpointOptions(orig); + + orig.SetCallback(orig_callback, orig_callback_baton_sp, orig_is_sync); + + return ret_val; } //---------------------------------------------------------------------- @@ -91,147 +83,117 @@ WatchpointOptions::~WatchpointOptions() = default; //------------------------------------------------------------------ // Callbacks //------------------------------------------------------------------ -void -WatchpointOptions::SetCallback (WatchpointHitCallback callback, const BatonSP &callback_baton_sp, bool callback_is_synchronous) -{ - m_callback_is_synchronous = callback_is_synchronous; - m_callback = callback; - m_callback_baton_sp = callback_baton_sp; +void WatchpointOptions::SetCallback(WatchpointHitCallback callback, + const BatonSP &callback_baton_sp, + bool callback_is_synchronous) { + m_callback_is_synchronous = callback_is_synchronous; + m_callback = callback; + m_callback_baton_sp = callback_baton_sp; } -void -WatchpointOptions::ClearCallback () -{ - m_callback = WatchpointOptions::NullCallback; - m_callback_is_synchronous = false; - m_callback_baton_sp.reset(); +void WatchpointOptions::ClearCallback() { + m_callback = WatchpointOptions::NullCallback; + m_callback_is_synchronous = false; + m_callback_baton_sp.reset(); } -Baton * -WatchpointOptions::GetBaton () -{ - return m_callback_baton_sp.get(); -} +Baton *WatchpointOptions::GetBaton() { return m_callback_baton_sp.get(); } -const Baton * -WatchpointOptions::GetBaton () const -{ - return m_callback_baton_sp.get(); +const Baton *WatchpointOptions::GetBaton() const { + return m_callback_baton_sp.get(); } -bool -WatchpointOptions::InvokeCallback (StoppointCallbackContext *context, - lldb::user_id_t watch_id) -{ - if (m_callback && context->is_synchronous == IsCallbackSynchronous()) - { - return m_callback(m_callback_baton_sp ? m_callback_baton_sp->m_data : nullptr, - context, - watch_id); - } - else - return true; +bool WatchpointOptions::InvokeCallback(StoppointCallbackContext *context, + lldb::user_id_t watch_id) { + if (m_callback && context->is_synchronous == IsCallbackSynchronous()) { + return m_callback(m_callback_baton_sp ? m_callback_baton_sp->m_data + : nullptr, + context, watch_id); + } else + return true; } -bool -WatchpointOptions::HasCallback () -{ - return m_callback != WatchpointOptions::NullCallback; +bool WatchpointOptions::HasCallback() { + return m_callback != WatchpointOptions::NullCallback; } -const ThreadSpec * -WatchpointOptions::GetThreadSpecNoCreate () const -{ - return m_thread_spec_ap.get(); +const ThreadSpec *WatchpointOptions::GetThreadSpecNoCreate() const { + return m_thread_spec_ap.get(); } -ThreadSpec * -WatchpointOptions::GetThreadSpec () -{ - if (m_thread_spec_ap.get() == nullptr) - m_thread_spec_ap.reset (new ThreadSpec()); - - return m_thread_spec_ap.get(); +ThreadSpec *WatchpointOptions::GetThreadSpec() { + if (m_thread_spec_ap.get() == nullptr) + m_thread_spec_ap.reset(new ThreadSpec()); + + return m_thread_spec_ap.get(); } -void -WatchpointOptions::SetThreadID (lldb::tid_t thread_id) -{ - GetThreadSpec()->SetTID(thread_id); +void WatchpointOptions::SetThreadID(lldb::tid_t thread_id) { + GetThreadSpec()->SetTID(thread_id); } -void -WatchpointOptions::GetCallbackDescription (Stream *s, lldb::DescriptionLevel level) const -{ - if (m_callback_baton_sp.get()) - { - s->EOL(); - m_callback_baton_sp->GetDescription (s, level); - } +void WatchpointOptions::GetCallbackDescription( + Stream *s, lldb::DescriptionLevel level) const { + if (m_callback_baton_sp.get()) { + s->EOL(); + m_callback_baton_sp->GetDescription(s, level); + } } -void -WatchpointOptions::GetDescription (Stream *s, lldb::DescriptionLevel level) const -{ - // Figure out if there are any options not at their default value, and only print - // anything if there are: - - if ((GetThreadSpecNoCreate() != nullptr && GetThreadSpecNoCreate()->HasSpecification ())) - { - if (level == lldb::eDescriptionLevelVerbose) - { - s->EOL (); - s->IndentMore(); - s->Indent(); - s->PutCString("Watchpoint Options:\n"); - s->IndentMore(); - s->Indent(); - } - else - s->PutCString(" Options: "); - - if (m_thread_spec_ap.get()) - m_thread_spec_ap->GetDescription (s, level); - else if (level == eDescriptionLevelBrief) - s->PutCString ("thread spec: no "); - if (level == lldb::eDescriptionLevelFull) - { - s->IndentLess(); - s->IndentMore(); - } +void WatchpointOptions::GetDescription(Stream *s, + lldb::DescriptionLevel level) const { + // Figure out if there are any options not at their default value, and only + // print + // anything if there are: + + if ((GetThreadSpecNoCreate() != nullptr && + GetThreadSpecNoCreate()->HasSpecification())) { + if (level == lldb::eDescriptionLevelVerbose) { + s->EOL(); + s->IndentMore(); + s->Indent(); + s->PutCString("Watchpoint Options:\n"); + s->IndentMore(); + s->Indent(); + } else + s->PutCString(" Options: "); + + if (m_thread_spec_ap.get()) + m_thread_spec_ap->GetDescription(s, level); + else if (level == eDescriptionLevelBrief) + s->PutCString("thread spec: no "); + if (level == lldb::eDescriptionLevelFull) { + s->IndentLess(); + s->IndentMore(); } - - GetCallbackDescription(s, level); + } + + GetCallbackDescription(s, level); } -void -WatchpointOptions::CommandBaton::GetDescription (Stream *s, lldb::DescriptionLevel level) const -{ - CommandData *data = (CommandData *)m_data; +void WatchpointOptions::CommandBaton::GetDescription( + Stream *s, lldb::DescriptionLevel level) const { + CommandData *data = (CommandData *)m_data; - if (level == eDescriptionLevelBrief) - { - s->Printf (", commands = %s", (data && data->user_source.GetSize() > 0) ? "yes" : "no"); - return; - } - - s->IndentMore (); - s->Indent("watchpoint commands:\n"); - - s->IndentMore (); - if (data && data->user_source.GetSize() > 0) - { - const size_t num_strings = data->user_source.GetSize(); - for (size_t i = 0; i < num_strings; ++i) - { - s->Indent(data->user_source.GetStringAtIndex(i)); - s->EOL(); - } - } - else - { - s->PutCString ("No commands.\n"); + if (level == eDescriptionLevelBrief) { + s->Printf(", commands = %s", + (data && data->user_source.GetSize() > 0) ? "yes" : "no"); + return; + } + + s->IndentMore(); + s->Indent("watchpoint commands:\n"); + + s->IndentMore(); + if (data && data->user_source.GetSize() > 0) { + const size_t num_strings = data->user_source.GetSize(); + for (size_t i = 0; i < num_strings; ++i) { + s->Indent(data->user_source.GetStringAtIndex(i)); + s->EOL(); } - s->IndentLess (); - s->IndentLess (); + } else { + s->PutCString("No commands.\n"); + } + s->IndentLess(); + s->IndentLess(); } diff --git a/lldb/source/Commands/CommandCompletions.cpp b/lldb/source/Commands/CommandCompletions.cpp index dd0ecb4b82e..9d70f406e93 100644 --- a/lldb/source/Commands/CommandCompletions.cpp +++ b/lldb/source/Commands/CommandCompletions.cpp @@ -37,447 +37,368 @@ using namespace lldb_private; CommandCompletions::CommonCompletionElement -CommandCompletions::g_common_completions[] = -{ - {eCustomCompletion, nullptr}, - {eSourceFileCompletion, CommandCompletions::SourceFiles}, - {eDiskFileCompletion, CommandCompletions::DiskFiles}, - {eDiskDirectoryCompletion, CommandCompletions::DiskDirectories}, - {eSymbolCompletion, CommandCompletions::Symbols}, - {eModuleCompletion, CommandCompletions::Modules}, - {eSettingsNameCompletion, CommandCompletions::SettingsNames}, - {ePlatformPluginCompletion, CommandCompletions::PlatformPluginNames}, - {eArchitectureCompletion, CommandCompletions::ArchitectureNames}, - {eVariablePathCompletion, CommandCompletions::VariablePath}, - {eNoCompletion, nullptr} // This one has to be last in the list. + CommandCompletions::g_common_completions[] = { + {eCustomCompletion, nullptr}, + {eSourceFileCompletion, CommandCompletions::SourceFiles}, + {eDiskFileCompletion, CommandCompletions::DiskFiles}, + {eDiskDirectoryCompletion, CommandCompletions::DiskDirectories}, + {eSymbolCompletion, CommandCompletions::Symbols}, + {eModuleCompletion, CommandCompletions::Modules}, + {eSettingsNameCompletion, CommandCompletions::SettingsNames}, + {ePlatformPluginCompletion, CommandCompletions::PlatformPluginNames}, + {eArchitectureCompletion, CommandCompletions::ArchitectureNames}, + {eVariablePathCompletion, CommandCompletions::VariablePath}, + {eNoCompletion, nullptr} // This one has to be last in the list. }; -bool -CommandCompletions::InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, - uint32_t completion_mask, - const char *completion_str, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - bool handled = false; - - if (completion_mask & eCustomCompletion) - return false; - - for (int i = 0; ; i++) - { - if (g_common_completions[i].type == eNoCompletion) - break; - else if ((g_common_completions[i].type & completion_mask) == g_common_completions[i].type - && g_common_completions[i].callback != nullptr) - { - handled = true; - g_common_completions[i].callback (interpreter, - completion_str, - match_start_point, - max_return_elements, - searcher, - word_complete, - matches); - } +bool CommandCompletions::InvokeCommonCompletionCallbacks( + CommandInterpreter &interpreter, uint32_t completion_mask, + const char *completion_str, int match_start_point, int max_return_elements, + SearchFilter *searcher, bool &word_complete, StringList &matches) { + bool handled = false; + + if (completion_mask & eCustomCompletion) + return false; + + for (int i = 0;; i++) { + if (g_common_completions[i].type == eNoCompletion) + break; + else if ((g_common_completions[i].type & completion_mask) == + g_common_completions[i].type && + g_common_completions[i].callback != nullptr) { + handled = true; + g_common_completions[i].callback(interpreter, completion_str, + match_start_point, max_return_elements, + searcher, word_complete, matches); } - return handled; + } + return handled; } -int -CommandCompletions::SourceFiles(CommandInterpreter &interpreter, - const char *partial_file_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - word_complete = true; - // Find some way to switch "include support files..." - SourceFileCompleter completer (interpreter, - false, - partial_file_name, - match_start_point, - max_return_elements, - matches); - - if (searcher == nullptr) - { - lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); - SearchFilterForUnconstrainedSearches null_searcher (target_sp); - completer.DoCompletion (&null_searcher); - } - else - { - completer.DoCompletion (searcher); - } - return matches.GetSize(); +int CommandCompletions::SourceFiles(CommandInterpreter &interpreter, + const char *partial_file_name, + int match_start_point, + int max_return_elements, + SearchFilter *searcher, bool &word_complete, + StringList &matches) { + word_complete = true; + // Find some way to switch "include support files..." + SourceFileCompleter completer(interpreter, false, partial_file_name, + match_start_point, max_return_elements, + matches); + + if (searcher == nullptr) { + lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); + SearchFilterForUnconstrainedSearches null_searcher(target_sp); + completer.DoCompletion(&null_searcher); + } else { + completer.DoCompletion(searcher); + } + return matches.GetSize(); } -typedef struct DiskFilesOrDirectoriesBaton -{ - const char *remainder; - char *partial_name_copy; - bool only_directories; - bool *saw_directory; - StringList *matches; - char *end_ptr; - size_t baselen; +typedef struct DiskFilesOrDirectoriesBaton { + const char *remainder; + char *partial_name_copy; + bool only_directories; + bool *saw_directory; + StringList *matches; + char *end_ptr; + size_t baselen; } DiskFilesOrDirectoriesBaton; -FileSpec::EnumerateDirectoryResult DiskFilesOrDirectoriesCallback(void *baton, FileSpec::FileType file_type, const FileSpec &spec) -{ - const char *name = spec.GetFilename().AsCString(); - - const DiskFilesOrDirectoriesBaton *parameters = (DiskFilesOrDirectoriesBaton*)baton; - char *end_ptr = parameters->end_ptr; - char *partial_name_copy = parameters->partial_name_copy; - const char *remainder = parameters->remainder; - - // Omit ".", ".." and any . files if the match string doesn't start with . - if (name[0] == '.') - { - if (name[1] == '\0') - return FileSpec::eEnumerateDirectoryResultNext; - else if (name[1] == '.' && name[2] == '\0') - return FileSpec::eEnumerateDirectoryResultNext; - else if (remainder[0] != '.') - return FileSpec::eEnumerateDirectoryResultNext; +FileSpec::EnumerateDirectoryResult +DiskFilesOrDirectoriesCallback(void *baton, FileSpec::FileType file_type, + const FileSpec &spec) { + const char *name = spec.GetFilename().AsCString(); + + const DiskFilesOrDirectoriesBaton *parameters = + (DiskFilesOrDirectoriesBaton *)baton; + char *end_ptr = parameters->end_ptr; + char *partial_name_copy = parameters->partial_name_copy; + const char *remainder = parameters->remainder; + + // Omit ".", ".." and any . files if the match string doesn't start with . + if (name[0] == '.') { + if (name[1] == '\0') + return FileSpec::eEnumerateDirectoryResultNext; + else if (name[1] == '.' && name[2] == '\0') + return FileSpec::eEnumerateDirectoryResultNext; + else if (remainder[0] != '.') + return FileSpec::eEnumerateDirectoryResultNext; + } + + // If we found a directory, we put a "/" at the end of the name. + + if (remainder[0] == '\0' || strstr(name, remainder) == name) { + if (strlen(name) + parameters->baselen >= PATH_MAX) + return FileSpec::eEnumerateDirectoryResultNext; + + strcpy(end_ptr, name); + + bool isa_directory = false; + if (file_type == FileSpec::eFileTypeDirectory) + isa_directory = true; + else if (file_type == FileSpec::eFileTypeSymbolicLink) { + if (FileSpec(partial_name_copy, false).IsDirectory()) + isa_directory = true; } - // If we found a directory, we put a "/" at the end of the name. - - if (remainder[0] == '\0' || strstr(name, remainder) == name) - { - if (strlen(name) + parameters->baselen >= PATH_MAX) - return FileSpec::eEnumerateDirectoryResultNext; + if (isa_directory) { + *parameters->saw_directory = true; + size_t len = strlen(parameters->partial_name_copy); + partial_name_copy[len] = '/'; + partial_name_copy[len + 1] = '\0'; + } + if (parameters->only_directories && !isa_directory) + return FileSpec::eEnumerateDirectoryResultNext; + parameters->matches->AppendString(partial_name_copy); + } - strcpy(end_ptr, name); + return FileSpec::eEnumerateDirectoryResultNext; +} - bool isa_directory = false; - if (file_type == FileSpec::eFileTypeDirectory) - isa_directory = true; - else if (file_type == FileSpec::eFileTypeSymbolicLink) - { - if (FileSpec(partial_name_copy, false).IsDirectory()) - isa_directory = true; - } +static int DiskFilesOrDirectories(const char *partial_file_name, + bool only_directories, bool &saw_directory, + StringList &matches) { + // I'm going to use the "glob" function with GLOB_TILDE for user directory + // expansion. + // If it is not defined on your host system, you'll need to implement it + // yourself... - if (isa_directory) - { - *parameters->saw_directory = true; - size_t len = strlen(parameters->partial_name_copy); - partial_name_copy[len] = '/'; - partial_name_copy[len + 1] = '\0'; - } - if (parameters->only_directories && !isa_directory) - return FileSpec::eEnumerateDirectoryResultNext; - parameters->matches->AppendString(partial_name_copy); - } + size_t partial_name_len = strlen(partial_file_name); - return FileSpec::eEnumerateDirectoryResultNext; -} + if (partial_name_len >= PATH_MAX) + return matches.GetSize(); -static int -DiskFilesOrDirectories(const char *partial_file_name, - bool only_directories, - bool &saw_directory, - StringList &matches) -{ - // I'm going to use the "glob" function with GLOB_TILDE for user directory expansion. - // If it is not defined on your host system, you'll need to implement it yourself... - - size_t partial_name_len = strlen(partial_file_name); - - if (partial_name_len >= PATH_MAX) + // This copy of the string will be cut up into the directory part, and the + // remainder. end_ptr + // below will point to the place of the remainder in this string. Then when + // we've resolved the + // containing directory, and opened it, we'll read the directory contents and + // overwrite the + // partial_name_copy starting from end_ptr with each of the matches. Thus we + // will preserve + // the form the user originally typed. + + char partial_name_copy[PATH_MAX]; + memcpy(partial_name_copy, partial_file_name, partial_name_len); + partial_name_copy[partial_name_len] = '\0'; + + // We'll need to save a copy of the remainder for comparison, which we do + // here. + char remainder[PATH_MAX]; + + // end_ptr will point past the last / in partial_name_copy, or if there is no + // slash to the beginning of the string. + char *end_ptr; + + end_ptr = strrchr(partial_name_copy, '/'); + + // This will store the resolved form of the containing directory + llvm::SmallString<64> containing_part; + + if (end_ptr == nullptr) { + // There's no directory. If the thing begins with a "~" then this is a bare + // user name. + if (*partial_name_copy == '~') { + // Nothing here but the user name. We could just put a slash on the end, + // but for completeness sake we'll resolve the user name and only put a + // slash + // on the end if it exists. + llvm::SmallString<64> resolved_username(partial_name_copy); + FileSpec::ResolveUsername(resolved_username); + + // Not sure how this would happen, a username longer than PATH_MAX? + // Still... + if (resolved_username.size() == 0) { + // The user name didn't resolve, let's look in the password database for + // matches. + // The user name database contains duplicates, and is not in + // alphabetical order, so + // we'll use a set to manage that for us. + FileSpec::ResolvePartialUsername(partial_name_copy, matches); + if (matches.GetSize() > 0) + saw_directory = true; return matches.GetSize(); - - // This copy of the string will be cut up into the directory part, and the remainder. end_ptr - // below will point to the place of the remainder in this string. Then when we've resolved the - // containing directory, and opened it, we'll read the directory contents and overwrite the - // partial_name_copy starting from end_ptr with each of the matches. Thus we will preserve - // the form the user originally typed. - - char partial_name_copy[PATH_MAX]; - memcpy(partial_name_copy, partial_file_name, partial_name_len); - partial_name_copy[partial_name_len] = '\0'; - - // We'll need to save a copy of the remainder for comparison, which we do here. - char remainder[PATH_MAX]; - - // end_ptr will point past the last / in partial_name_copy, or if there is no slash to the beginning of the string. - char *end_ptr; - - end_ptr = strrchr(partial_name_copy, '/'); - - // This will store the resolved form of the containing directory - llvm::SmallString<64> containing_part; - - if (end_ptr == nullptr) - { - // There's no directory. If the thing begins with a "~" then this is a bare - // user name. - if (*partial_name_copy == '~') - { - // Nothing here but the user name. We could just put a slash on the end, - // but for completeness sake we'll resolve the user name and only put a slash - // on the end if it exists. - llvm::SmallString<64> resolved_username(partial_name_copy); - FileSpec::ResolveUsername (resolved_username); - - // Not sure how this would happen, a username longer than PATH_MAX? Still... - if (resolved_username.size() == 0) - { - // The user name didn't resolve, let's look in the password database for matches. - // The user name database contains duplicates, and is not in alphabetical order, so - // we'll use a set to manage that for us. - FileSpec::ResolvePartialUsername (partial_name_copy, matches); - if (matches.GetSize() > 0) - saw_directory = true; - return matches.GetSize(); - } - else - { - //The thing exists, put a '/' on the end, and return it... - // FIXME: complete user names here: - partial_name_copy[partial_name_len] = '/'; - partial_name_copy[partial_name_len+1] = '\0'; - matches.AppendString(partial_name_copy); - saw_directory = true; - return matches.GetSize(); - } - } - else - { - // The containing part is the CWD, and the whole string is the remainder. - containing_part = "."; - strcpy(remainder, partial_name_copy); - end_ptr = partial_name_copy; - } - } - else - { - if (end_ptr == partial_name_copy) - { - // We're completing a file or directory in the root volume. - containing_part = "/"; - } - else - { - containing_part.append(partial_name_copy, end_ptr); - } - // Push end_ptr past the final "/" and set remainder. - end_ptr++; - strcpy(remainder, end_ptr); + } else { + // The thing exists, put a '/' on the end, and return it... + // FIXME: complete user names here: + partial_name_copy[partial_name_len] = '/'; + partial_name_copy[partial_name_len + 1] = '\0'; + matches.AppendString(partial_name_copy); + saw_directory = true; + return matches.GetSize(); + } + } else { + // The containing part is the CWD, and the whole string is the remainder. + containing_part = "."; + strcpy(remainder, partial_name_copy); + end_ptr = partial_name_copy; } - - // Look for a user name in the containing part, and if it's there, resolve it and stick the - // result back into the containing_part: - - if (*partial_name_copy == '~') - { - FileSpec::ResolveUsername(containing_part); - // User name doesn't exist, we're not getting any further... - if (containing_part.empty()) - return matches.GetSize(); + } else { + if (end_ptr == partial_name_copy) { + // We're completing a file or directory in the root volume. + containing_part = "/"; + } else { + containing_part.append(partial_name_copy, end_ptr); } - - // Okay, containing_part is now the directory we want to open and look for files: - - size_t baselen = end_ptr - partial_name_copy; - - DiskFilesOrDirectoriesBaton parameters; - parameters.remainder = remainder; - parameters.partial_name_copy = partial_name_copy; - parameters.only_directories = only_directories; - parameters.saw_directory = &saw_directory; - parameters.matches = &matches; - parameters.end_ptr = end_ptr; - parameters.baselen = baselen; - - FileSpec::EnumerateDirectory(containing_part.c_str(), true, true, true, DiskFilesOrDirectoriesCallback, ¶meters); - - return matches.GetSize(); + // Push end_ptr past the final "/" and set remainder. + end_ptr++; + strcpy(remainder, end_ptr); + } + + // Look for a user name in the containing part, and if it's there, resolve it + // and stick the + // result back into the containing_part: + + if (*partial_name_copy == '~') { + FileSpec::ResolveUsername(containing_part); + // User name doesn't exist, we're not getting any further... + if (containing_part.empty()) + return matches.GetSize(); + } + + // Okay, containing_part is now the directory we want to open and look for + // files: + + size_t baselen = end_ptr - partial_name_copy; + + DiskFilesOrDirectoriesBaton parameters; + parameters.remainder = remainder; + parameters.partial_name_copy = partial_name_copy; + parameters.only_directories = only_directories; + parameters.saw_directory = &saw_directory; + parameters.matches = &matches; + parameters.end_ptr = end_ptr; + parameters.baselen = baselen; + + FileSpec::EnumerateDirectory(containing_part.c_str(), true, true, true, + DiskFilesOrDirectoriesCallback, ¶meters); + + return matches.GetSize(); } -int -CommandCompletions::DiskFiles(CommandInterpreter &interpreter, - const char *partial_file_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - int ret_val = DiskFilesOrDirectories (partial_file_name, - false, - word_complete, - matches); - word_complete = !word_complete; - return ret_val; +int CommandCompletions::DiskFiles(CommandInterpreter &interpreter, + const char *partial_file_name, + int match_start_point, + int max_return_elements, + SearchFilter *searcher, bool &word_complete, + StringList &matches) { + int ret_val = + DiskFilesOrDirectories(partial_file_name, false, word_complete, matches); + word_complete = !word_complete; + return ret_val; } -int -CommandCompletions::DiskDirectories(CommandInterpreter &interpreter, - const char *partial_file_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - int ret_val = DiskFilesOrDirectories (partial_file_name, - true, - word_complete, - matches); - word_complete = false; - return ret_val; +int CommandCompletions::DiskDirectories( + CommandInterpreter &interpreter, const char *partial_file_name, + int match_start_point, int max_return_elements, SearchFilter *searcher, + bool &word_complete, StringList &matches) { + int ret_val = + DiskFilesOrDirectories(partial_file_name, true, word_complete, matches); + word_complete = false; + return ret_val; } -int -CommandCompletions::Modules(CommandInterpreter &interpreter, - const char *partial_file_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - word_complete = true; - ModuleCompleter completer (interpreter, - partial_file_name, - match_start_point, - max_return_elements, - matches); - - if (searcher == nullptr) - { - lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); - SearchFilterForUnconstrainedSearches null_searcher (target_sp); - completer.DoCompletion (&null_searcher); - } - else - { - completer.DoCompletion (searcher); - } - return matches.GetSize(); +int CommandCompletions::Modules(CommandInterpreter &interpreter, + const char *partial_file_name, + int match_start_point, int max_return_elements, + SearchFilter *searcher, bool &word_complete, + StringList &matches) { + word_complete = true; + ModuleCompleter completer(interpreter, partial_file_name, match_start_point, + max_return_elements, matches); + + if (searcher == nullptr) { + lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); + SearchFilterForUnconstrainedSearches null_searcher(target_sp); + completer.DoCompletion(&null_searcher); + } else { + completer.DoCompletion(searcher); + } + return matches.GetSize(); } -int -CommandCompletions::Symbols(CommandInterpreter &interpreter, - const char *partial_file_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - word_complete = true; - SymbolCompleter completer (interpreter, - partial_file_name, - match_start_point, - max_return_elements, - matches); - - if (searcher == nullptr) - { - lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); - SearchFilterForUnconstrainedSearches null_searcher (target_sp); - completer.DoCompletion (&null_searcher); - } - else - { - completer.DoCompletion (searcher); - } - return matches.GetSize(); +int CommandCompletions::Symbols(CommandInterpreter &interpreter, + const char *partial_file_name, + int match_start_point, int max_return_elements, + SearchFilter *searcher, bool &word_complete, + StringList &matches) { + word_complete = true; + SymbolCompleter completer(interpreter, partial_file_name, match_start_point, + max_return_elements, matches); + + if (searcher == nullptr) { + lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); + SearchFilterForUnconstrainedSearches null_searcher(target_sp); + completer.DoCompletion(&null_searcher); + } else { + completer.DoCompletion(searcher); + } + return matches.GetSize(); } -int -CommandCompletions::SettingsNames (CommandInterpreter &interpreter, - const char *partial_setting_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - StringList &matches) -{ - // Cache the full setting name list - static StringList g_property_names; - if (g_property_names.GetSize() == 0) - { - // Generate the full setting name list on demand - lldb::OptionValuePropertiesSP properties_sp (interpreter.GetDebugger().GetValueProperties()); - if (properties_sp) - { - StreamString strm; - properties_sp->DumpValue(nullptr, strm, OptionValue::eDumpOptionName); - const std::string &str = strm.GetString(); - g_property_names.SplitIntoLines(str.c_str(), str.size()); - } +int CommandCompletions::SettingsNames( + CommandInterpreter &interpreter, const char *partial_setting_name, + int match_start_point, int max_return_elements, SearchFilter *searcher, + bool &word_complete, StringList &matches) { + // Cache the full setting name list + static StringList g_property_names; + if (g_property_names.GetSize() == 0) { + // Generate the full setting name list on demand + lldb::OptionValuePropertiesSP properties_sp( + interpreter.GetDebugger().GetValueProperties()); + if (properties_sp) { + StreamString strm; + properties_sp->DumpValue(nullptr, strm, OptionValue::eDumpOptionName); + const std::string &str = strm.GetString(); + g_property_names.SplitIntoLines(str.c_str(), str.size()); } - - size_t exact_matches_idx = SIZE_MAX; - const size_t num_matches = g_property_names.AutoComplete (partial_setting_name, matches, exact_matches_idx); - word_complete = exact_matches_idx != SIZE_MAX; - return num_matches; + } + + size_t exact_matches_idx = SIZE_MAX; + const size_t num_matches = g_property_names.AutoComplete( + partial_setting_name, matches, exact_matches_idx); + word_complete = exact_matches_idx != SIZE_MAX; + return num_matches; } -int -CommandCompletions::PlatformPluginNames (CommandInterpreter &interpreter, - const char *partial_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - lldb_private::StringList &matches) -{ - const uint32_t num_matches = PluginManager::AutoCompletePlatformName(partial_name, matches); - word_complete = num_matches == 1; - return num_matches; +int CommandCompletions::PlatformPluginNames( + CommandInterpreter &interpreter, const char *partial_name, + int match_start_point, int max_return_elements, SearchFilter *searcher, + bool &word_complete, lldb_private::StringList &matches) { + const uint32_t num_matches = + PluginManager::AutoCompletePlatformName(partial_name, matches); + word_complete = num_matches == 1; + return num_matches; } -int -CommandCompletions::ArchitectureNames (CommandInterpreter &interpreter, - const char *partial_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - lldb_private::StringList &matches) -{ - const uint32_t num_matches = ArchSpec::AutoComplete (partial_name, matches); - word_complete = num_matches == 1; - return num_matches; +int CommandCompletions::ArchitectureNames( + CommandInterpreter &interpreter, const char *partial_name, + int match_start_point, int max_return_elements, SearchFilter *searcher, + bool &word_complete, lldb_private::StringList &matches) { + const uint32_t num_matches = ArchSpec::AutoComplete(partial_name, matches); + word_complete = num_matches == 1; + return num_matches; } -int -CommandCompletions::VariablePath (CommandInterpreter &interpreter, - const char *partial_name, - int match_start_point, - int max_return_elements, - SearchFilter *searcher, - bool &word_complete, - lldb_private::StringList &matches) -{ - return Variable::AutoComplete (interpreter.GetExecutionContext(), partial_name, matches, word_complete); +int CommandCompletions::VariablePath( + CommandInterpreter &interpreter, const char *partial_name, + int match_start_point, int max_return_elements, SearchFilter *searcher, + bool &word_complete, lldb_private::StringList &matches) { + return Variable::AutoComplete(interpreter.GetExecutionContext(), partial_name, + matches, word_complete); } CommandCompletions::Completer::Completer(CommandInterpreter &interpreter, const char *completion_str, int match_start_point, int max_return_elements, - StringList &matches) : - m_interpreter (interpreter), - m_completion_str (completion_str), - m_match_start_point (match_start_point), - m_max_return_elements (max_return_elements), - m_matches (matches) -{ -} + StringList &matches) + : m_interpreter(interpreter), m_completion_str(completion_str), + m_match_start_point(match_start_point), + m_max_return_elements(max_return_elements), m_matches(matches) {} CommandCompletions::Completer::~Completer() = default; @@ -485,237 +406,195 @@ CommandCompletions::Completer::~Completer() = default; // SourceFileCompleter //---------------------------------------------------------------------- -CommandCompletions::SourceFileCompleter::SourceFileCompleter(CommandInterpreter &interpreter, - bool include_support_files, - const char *completion_str, - int match_start_point, - int max_return_elements, - StringList &matches) : - CommandCompletions::Completer (interpreter, completion_str, match_start_point, max_return_elements, matches), - m_include_support_files (include_support_files), - m_matching_files() -{ - FileSpec partial_spec (m_completion_str.c_str(), false); - m_file_name = partial_spec.GetFilename().GetCString(); - m_dir_name = partial_spec.GetDirectory().GetCString(); +CommandCompletions::SourceFileCompleter::SourceFileCompleter( + CommandInterpreter &interpreter, bool include_support_files, + const char *completion_str, int match_start_point, int max_return_elements, + StringList &matches) + : CommandCompletions::Completer(interpreter, completion_str, + match_start_point, max_return_elements, + matches), + m_include_support_files(include_support_files), m_matching_files() { + FileSpec partial_spec(m_completion_str.c_str(), false); + m_file_name = partial_spec.GetFilename().GetCString(); + m_dir_name = partial_spec.GetDirectory().GetCString(); } -Searcher::Depth -CommandCompletions::SourceFileCompleter::GetDepth() -{ - return eDepthCompUnit; +Searcher::Depth CommandCompletions::SourceFileCompleter::GetDepth() { + return eDepthCompUnit; } Searcher::CallbackReturn CommandCompletions::SourceFileCompleter::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr, - bool complete) -{ - if (context.comp_unit != nullptr) - { - if (m_include_support_files) - { - FileSpecList supporting_files = context.comp_unit->GetSupportFiles(); - for (size_t sfiles = 0; sfiles < supporting_files.GetSize(); sfiles++) - { - const FileSpec &sfile_spec = supporting_files.GetFileSpecAtIndex(sfiles); - const char *sfile_file_name = sfile_spec.GetFilename().GetCString(); - const char *sfile_dir_name = sfile_spec.GetFilename().GetCString(); - bool match = false; - if (m_file_name && sfile_file_name - && strstr (sfile_file_name, m_file_name) == sfile_file_name) - match = true; - if (match && m_dir_name && sfile_dir_name - && strstr (sfile_dir_name, m_dir_name) != sfile_dir_name) - match = false; - - if (match) - { - m_matching_files.AppendIfUnique(sfile_spec); - } - } - } - else - { - const char *cur_file_name = context.comp_unit->GetFilename().GetCString(); - const char *cur_dir_name = context.comp_unit->GetDirectory().GetCString(); - - bool match = false; - if (m_file_name && cur_file_name - && strstr (cur_file_name, m_file_name) == cur_file_name) - match = true; - - if (match && m_dir_name && cur_dir_name - && strstr (cur_dir_name, m_dir_name) != cur_dir_name) - match = false; - - if (match) - { - m_matching_files.AppendIfUnique(context.comp_unit); - } + bool complete) { + if (context.comp_unit != nullptr) { + if (m_include_support_files) { + FileSpecList supporting_files = context.comp_unit->GetSupportFiles(); + for (size_t sfiles = 0; sfiles < supporting_files.GetSize(); sfiles++) { + const FileSpec &sfile_spec = + supporting_files.GetFileSpecAtIndex(sfiles); + const char *sfile_file_name = sfile_spec.GetFilename().GetCString(); + const char *sfile_dir_name = sfile_spec.GetFilename().GetCString(); + bool match = false; + if (m_file_name && sfile_file_name && + strstr(sfile_file_name, m_file_name) == sfile_file_name) + match = true; + if (match && m_dir_name && sfile_dir_name && + strstr(sfile_dir_name, m_dir_name) != sfile_dir_name) + match = false; + + if (match) { + m_matching_files.AppendIfUnique(sfile_spec); } + } + } else { + const char *cur_file_name = context.comp_unit->GetFilename().GetCString(); + const char *cur_dir_name = context.comp_unit->GetDirectory().GetCString(); + + bool match = false; + if (m_file_name && cur_file_name && + strstr(cur_file_name, m_file_name) == cur_file_name) + match = true; + + if (match && m_dir_name && cur_dir_name && + strstr(cur_dir_name, m_dir_name) != cur_dir_name) + match = false; + + if (match) { + m_matching_files.AppendIfUnique(context.comp_unit); + } } - return Searcher::eCallbackReturnContinue; + } + return Searcher::eCallbackReturnContinue; } size_t -CommandCompletions::SourceFileCompleter::DoCompletion (SearchFilter *filter) -{ - filter->Search (*this); - // Now convert the filelist to completions: - for (size_t i = 0; i < m_matching_files.GetSize(); i++) - { - m_matches.AppendString (m_matching_files.GetFileSpecAtIndex(i).GetFilename().GetCString()); - } - return m_matches.GetSize(); +CommandCompletions::SourceFileCompleter::DoCompletion(SearchFilter *filter) { + filter->Search(*this); + // Now convert the filelist to completions: + for (size_t i = 0; i < m_matching_files.GetSize(); i++) { + m_matches.AppendString( + m_matching_files.GetFileSpecAtIndex(i).GetFilename().GetCString()); + } + return m_matches.GetSize(); } //---------------------------------------------------------------------- // SymbolCompleter //---------------------------------------------------------------------- -static bool -regex_chars (const char comp) -{ - return (comp == '[' || comp == ']' || - comp == '(' || comp == ')' || - comp == '{' || comp == '}' || - comp == '+' || - comp == '.' || - comp == '*' || - comp == '|' || - comp == '^' || - comp == '$' || - comp == '\\' || - comp == '?'); +static bool regex_chars(const char comp) { + return (comp == '[' || comp == ']' || comp == '(' || comp == ')' || + comp == '{' || comp == '}' || comp == '+' || comp == '.' || + comp == '*' || comp == '|' || comp == '^' || comp == '$' || + comp == '\\' || comp == '?'); } -CommandCompletions::SymbolCompleter::SymbolCompleter(CommandInterpreter &interpreter, - const char *completion_str, - int match_start_point, - int max_return_elements, - StringList &matches) : - CommandCompletions::Completer (interpreter, completion_str, match_start_point, max_return_elements, matches) -{ - std::string regex_str; - if (completion_str && completion_str[0]) - { - regex_str.append("^"); - regex_str.append(completion_str); - } - else - { - // Match anything since the completion string is empty - regex_str.append("."); - } - std::string::iterator pos = find_if(regex_str.begin() + 1, regex_str.end(), regex_chars); - while (pos < regex_str.end()) - { - pos = regex_str.insert(pos, '\\'); - pos = find_if(pos + 2, regex_str.end(), regex_chars); - } - m_regex.Compile(regex_str.c_str()); +CommandCompletions::SymbolCompleter::SymbolCompleter( + CommandInterpreter &interpreter, const char *completion_str, + int match_start_point, int max_return_elements, StringList &matches) + : CommandCompletions::Completer(interpreter, completion_str, + match_start_point, max_return_elements, + matches) { + std::string regex_str; + if (completion_str && completion_str[0]) { + regex_str.append("^"); + regex_str.append(completion_str); + } else { + // Match anything since the completion string is empty + regex_str.append("."); + } + std::string::iterator pos = + find_if(regex_str.begin() + 1, regex_str.end(), regex_chars); + while (pos < regex_str.end()) { + pos = regex_str.insert(pos, '\\'); + pos = find_if(pos + 2, regex_str.end(), regex_chars); + } + m_regex.Compile(regex_str.c_str()); } -Searcher::Depth -CommandCompletions::SymbolCompleter::GetDepth() -{ - return eDepthModule; +Searcher::Depth CommandCompletions::SymbolCompleter::GetDepth() { + return eDepthModule; } -Searcher::CallbackReturn -CommandCompletions::SymbolCompleter::SearchCallback(SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool complete) -{ - if (context.module_sp) - { - SymbolContextList sc_list; - const bool include_symbols = true; - const bool include_inlines = true; - const bool append = true; - context.module_sp->FindFunctions (m_regex, include_symbols, include_inlines, append, sc_list); - - SymbolContext sc; - // Now add the functions & symbols to the list - only add if unique: - for (uint32_t i = 0; i < sc_list.GetSize(); i++) - { - if (sc_list.GetContextAtIndex(i, sc)) - { - ConstString func_name = sc.GetFunctionName(Mangled::ePreferDemangled); - if (!func_name.IsEmpty()) - m_match_set.insert (func_name); - } - } +Searcher::CallbackReturn CommandCompletions::SymbolCompleter::SearchCallback( + SearchFilter &filter, SymbolContext &context, Address *addr, + bool complete) { + if (context.module_sp) { + SymbolContextList sc_list; + const bool include_symbols = true; + const bool include_inlines = true; + const bool append = true; + context.module_sp->FindFunctions(m_regex, include_symbols, include_inlines, + append, sc_list); + + SymbolContext sc; + // Now add the functions & symbols to the list - only add if unique: + for (uint32_t i = 0; i < sc_list.GetSize(); i++) { + if (sc_list.GetContextAtIndex(i, sc)) { + ConstString func_name = sc.GetFunctionName(Mangled::ePreferDemangled); + if (!func_name.IsEmpty()) + m_match_set.insert(func_name); + } } - return Searcher::eCallbackReturnContinue; + } + return Searcher::eCallbackReturnContinue; } -size_t -CommandCompletions::SymbolCompleter::DoCompletion (SearchFilter *filter) -{ - filter->Search (*this); - collection::iterator pos = m_match_set.begin(), end = m_match_set.end(); - for (pos = m_match_set.begin(); pos != end; pos++) - m_matches.AppendString((*pos).GetCString()); - - return m_matches.GetSize(); +size_t CommandCompletions::SymbolCompleter::DoCompletion(SearchFilter *filter) { + filter->Search(*this); + collection::iterator pos = m_match_set.begin(), end = m_match_set.end(); + for (pos = m_match_set.begin(); pos != end; pos++) + m_matches.AppendString((*pos).GetCString()); + + return m_matches.GetSize(); } //---------------------------------------------------------------------- // ModuleCompleter //---------------------------------------------------------------------- -CommandCompletions::ModuleCompleter::ModuleCompleter(CommandInterpreter &interpreter, - const char *completion_str, - int match_start_point, - int max_return_elements, - StringList &matches) : - CommandCompletions::Completer (interpreter, completion_str, match_start_point, max_return_elements, matches) -{ - FileSpec partial_spec (m_completion_str.c_str(), false); - m_file_name = partial_spec.GetFilename().GetCString(); - m_dir_name = partial_spec.GetDirectory().GetCString(); +CommandCompletions::ModuleCompleter::ModuleCompleter( + CommandInterpreter &interpreter, const char *completion_str, + int match_start_point, int max_return_elements, StringList &matches) + : CommandCompletions::Completer(interpreter, completion_str, + match_start_point, max_return_elements, + matches) { + FileSpec partial_spec(m_completion_str.c_str(), false); + m_file_name = partial_spec.GetFilename().GetCString(); + m_dir_name = partial_spec.GetDirectory().GetCString(); } -Searcher::Depth -CommandCompletions::ModuleCompleter::GetDepth() -{ - return eDepthModule; +Searcher::Depth CommandCompletions::ModuleCompleter::GetDepth() { + return eDepthModule; } -Searcher::CallbackReturn -CommandCompletions::ModuleCompleter::SearchCallback(SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool complete) -{ - if (context.module_sp) - { - const char *cur_file_name = context.module_sp->GetFileSpec().GetFilename().GetCString(); - const char *cur_dir_name = context.module_sp->GetFileSpec().GetDirectory().GetCString(); - - bool match = false; - if (m_file_name && cur_file_name - && strstr (cur_file_name, m_file_name) == cur_file_name) - match = true; - - if (match && m_dir_name && cur_dir_name - && strstr (cur_dir_name, m_dir_name) != cur_dir_name) - match = false; - - if (match) - { - m_matches.AppendString (cur_file_name); - } +Searcher::CallbackReturn CommandCompletions::ModuleCompleter::SearchCallback( + SearchFilter &filter, SymbolContext &context, Address *addr, + bool complete) { + if (context.module_sp) { + const char *cur_file_name = + context.module_sp->GetFileSpec().GetFilename().GetCString(); + const char *cur_dir_name = + context.module_sp->GetFileSpec().GetDirectory().GetCString(); + + bool match = false; + if (m_file_name && cur_file_name && + strstr(cur_file_name, m_file_name) == cur_file_name) + match = true; + + if (match && m_dir_name && cur_dir_name && + strstr(cur_dir_name, m_dir_name) != cur_dir_name) + match = false; + + if (match) { + m_matches.AppendString(cur_file_name); } - return Searcher::eCallbackReturnContinue; + } + return Searcher::eCallbackReturnContinue; } -size_t -CommandCompletions::ModuleCompleter::DoCompletion (SearchFilter *filter) -{ - filter->Search (*this); - return m_matches.GetSize(); +size_t CommandCompletions::ModuleCompleter::DoCompletion(SearchFilter *filter) { + filter->Search(*this); + return m_matches.GetSize(); } diff --git a/lldb/source/Commands/CommandObjectApropos.cpp b/lldb/source/Commands/CommandObjectApropos.cpp index 29e1f14e3b2..c70d0217fc7 100644 --- a/lldb/source/Commands/CommandObjectApropos.cpp +++ b/lldb/source/Commands/CommandObjectApropos.cpp @@ -1,4 +1,5 @@ -//===-- CommandObjectApropos.cpp ---------------------------------*- C++ -*-===// +//===-- CommandObjectApropos.cpp ---------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -13,10 +14,10 @@ // Project includes #include "CommandObjectApropos.h" #include "lldb/Interpreter/Args.h" -#include "lldb/Interpreter/Options.h" -#include "lldb/Interpreter/Property.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" +#include "lldb/Interpreter/Property.h" using namespace lldb; using namespace lldb_private; @@ -26,93 +27,87 @@ using namespace lldb_private; //------------------------------------------------------------------------- CommandObjectApropos::CommandObjectApropos(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "apropos", "List debugger commands related to a word or subject.", nullptr) -{ - CommandArgumentEntry arg; - CommandArgumentData search_word_arg; + : CommandObjectParsed( + interpreter, "apropos", + "List debugger commands related to a word or subject.", nullptr) { + CommandArgumentEntry arg; + CommandArgumentData search_word_arg; - // Define the first (and only) variant of this arg. - search_word_arg.arg_type = eArgTypeSearchWord; - search_word_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + search_word_arg.arg_type = eArgTypeSearchWord; + search_word_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (search_word_arg); + // There is only one variant this argument could be; put it into the argument + // entry. + arg.push_back(search_word_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); } CommandObjectApropos::~CommandObjectApropos() = default; -bool -CommandObjectApropos::DoExecute (Args& args, CommandReturnObject &result) -{ - const size_t argc = args.GetArgumentCount (); - - if (argc == 1) - { - const char *search_word = args.GetArgumentAtIndex(0); - if ((search_word != nullptr) - && (strlen (search_word) > 0)) - { - // The bulk of the work must be done inside the Command Interpreter, since the command dictionary - // is private. - StringList commands_found; - StringList commands_help; - - m_interpreter.FindCommandsForApropos (search_word, commands_found, commands_help, true, true, true); - - if (commands_found.GetSize() == 0) - { - result.AppendMessageWithFormat ("No commands found pertaining to '%s'. Try 'help' to see a complete list of debugger commands.\n", search_word); - } - else - { - if (commands_found.GetSize() > 0) - { - result.AppendMessageWithFormat ("The following commands may relate to '%s':\n", search_word); - size_t max_len = 0; - - for (size_t i = 0; i < commands_found.GetSize(); ++i) - { - size_t len = strlen (commands_found.GetStringAtIndex (i)); - if (len > max_len) - max_len = len; - } - - for (size_t i = 0; i < commands_found.GetSize(); ++i) - m_interpreter.OutputFormattedHelpText (result.GetOutputStream(), - commands_found.GetStringAtIndex(i), - "--", - commands_help.GetStringAtIndex(i), - max_len); - } - } - - std::vector properties; - const size_t num_properties = m_interpreter.GetDebugger().Apropos(search_word, properties); - if (num_properties) - { - const bool dump_qualified_name = true; - result.AppendMessageWithFormat ("\nThe following settings variables may relate to '%s': \n\n", search_word); - for (size_t i=0; iDumpDescription (m_interpreter, result.GetOutputStream(), 0, dump_qualified_name); - - } - - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("'' is not a valid search word.\n"); - result.SetStatus (eReturnStatusFailed); +bool CommandObjectApropos::DoExecute(Args &args, CommandReturnObject &result) { + const size_t argc = args.GetArgumentCount(); + + if (argc == 1) { + const char *search_word = args.GetArgumentAtIndex(0); + if ((search_word != nullptr) && (strlen(search_word) > 0)) { + // The bulk of the work must be done inside the Command Interpreter, since + // the command dictionary + // is private. + StringList commands_found; + StringList commands_help; + + m_interpreter.FindCommandsForApropos(search_word, commands_found, + commands_help, true, true, true); + + if (commands_found.GetSize() == 0) { + result.AppendMessageWithFormat("No commands found pertaining to '%s'. " + "Try 'help' to see a complete list of " + "debugger commands.\n", + search_word); + } else { + if (commands_found.GetSize() > 0) { + result.AppendMessageWithFormat( + "The following commands may relate to '%s':\n", search_word); + size_t max_len = 0; + + for (size_t i = 0; i < commands_found.GetSize(); ++i) { + size_t len = strlen(commands_found.GetStringAtIndex(i)); + if (len > max_len) + max_len = len; + } + + for (size_t i = 0; i < commands_found.GetSize(); ++i) + m_interpreter.OutputFormattedHelpText( + result.GetOutputStream(), commands_found.GetStringAtIndex(i), + "--", commands_help.GetStringAtIndex(i), max_len); } + } + + std::vector properties; + const size_t num_properties = + m_interpreter.GetDebugger().Apropos(search_word, properties); + if (num_properties) { + const bool dump_qualified_name = true; + result.AppendMessageWithFormat( + "\nThe following settings variables may relate to '%s': \n\n", + search_word); + for (size_t i = 0; i < num_properties; ++i) + properties[i]->DumpDescription( + m_interpreter, result.GetOutputStream(), 0, dump_qualified_name); + } + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("'' is not a valid search word.\n"); + result.SetStatus(eReturnStatusFailed); } - else - { - result.AppendError ("'apropos' must be called with exactly one argument.\n"); - result.SetStatus (eReturnStatusFailed); - } + } else { + result.AppendError("'apropos' must be called with exactly one argument.\n"); + result.SetStatus(eReturnStatusFailed); + } - return result.Succeeded(); + return result.Succeeded(); } diff --git a/lldb/source/Commands/CommandObjectApropos.h b/lldb/source/Commands/CommandObjectApropos.h index d04620bc5f2..5cad40d5c62 100644 --- a/lldb/source/Commands/CommandObjectApropos.h +++ b/lldb/source/Commands/CommandObjectApropos.h @@ -1,4 +1,5 @@ -//===-- CommandObjectApropos.h -----------------------------------*- C++ -*-===// +//===-- CommandObjectApropos.h -----------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -22,18 +23,14 @@ namespace lldb_private { // CommandObjectApropos //------------------------------------------------------------------------- -class CommandObjectApropos : public CommandObjectParsed -{ +class CommandObjectApropos : public CommandObjectParsed { public: + CommandObjectApropos(CommandInterpreter &interpreter); - CommandObjectApropos (CommandInterpreter &interpreter); - - ~CommandObjectApropos() override; + ~CommandObjectApropos() override; protected: - bool - DoExecute(Args& command, - CommandReturnObject &result) override; + bool DoExecute(Args &command, CommandReturnObject &result) override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectArgs.cpp b/lldb/source/Commands/CommandObjectArgs.cpp index ac1b5817955..eec83b7db43 100644 --- a/lldb/source/Commands/CommandObjectArgs.cpp +++ b/lldb/source/Commands/CommandObjectArgs.cpp @@ -12,12 +12,12 @@ // Other libraries and framework includes // Project includes #include "CommandObjectArgs.h" -#include "lldb/Interpreter/Args.h" +#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/Value.h" -#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" #include "lldb/Host/Host.h" +#include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Symbol/ClangASTContext.h" @@ -25,242 +25,213 @@ #include "lldb/Symbol/Variable.h" #include "lldb/Target/ABI.h" #include "lldb/Target/Process.h" +#include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" -#include "lldb/Target/StackFrame.h" using namespace lldb; using namespace lldb_private; -// This command is a toy. I'm just using it to have a way to construct the arguments to +// This command is a toy. I'm just using it to have a way to construct the +// arguments to // calling functions. // -CommandObjectArgs::CommandOptions::CommandOptions (CommandInterpreter &interpreter) : - Options() -{ - // Keep only one place to reset the values to their defaults - OptionParsingStarting(nullptr); +CommandObjectArgs::CommandOptions::CommandOptions( + CommandInterpreter &interpreter) + : Options() { + // Keep only one place to reset the values to their defaults + OptionParsingStarting(nullptr); } CommandObjectArgs::CommandOptions::~CommandOptions() = default; -Error -CommandObjectArgs::CommandOptions::SetOptionValue(uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) -{ - Error error; - - const int short_option = m_getopt_table[option_idx].val; - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - - return error; -} - -void -CommandObjectArgs::CommandOptions::OptionParsingStarting( - ExecutionContext *execution_context) -{ -} +Error CommandObjectArgs::CommandOptions::SetOptionValue( + uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) { + Error error; -const OptionDefinition* -CommandObjectArgs::CommandOptions::GetDefinitions () -{ - return g_option_table; -} + const int short_option = m_getopt_table[option_idx].val; + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); -CommandObjectArgs::CommandObjectArgs (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "args", - "When stopped at the start of a function, reads function arguments of type (u?)int(8|16|32|64)_t, (void|char)*", - "args"), - m_options (interpreter) -{ + return error; } -CommandObjectArgs::~CommandObjectArgs() = default; +void CommandObjectArgs::CommandOptions::OptionParsingStarting( + ExecutionContext *execution_context) {} -Options * -CommandObjectArgs::GetOptions () -{ - return &m_options; +const OptionDefinition *CommandObjectArgs::CommandOptions::GetDefinitions() { + return g_option_table; } -bool -CommandObjectArgs::DoExecute (Args& args, CommandReturnObject &result) -{ - ConstString target_triple; +CommandObjectArgs::CommandObjectArgs(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "args", + "When stopped at the start of a function, reads " + "function arguments of type (u?)int(8|16|32|64)_t, " + "(void|char)*", + "args"), + m_options(interpreter) {} - Process *process = m_exe_ctx.GetProcessPtr(); - if (!process) - { - result.AppendError ("Args found no process."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const ABI *abi = process->GetABI().get(); - if (!abi) - { - result.AppendError ("The current process has no ABI."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const size_t num_args = args.GetArgumentCount (); - size_t arg_index; - - if (!num_args) - { - result.AppendError ("args requires at least one argument"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - Thread *thread = m_exe_ctx.GetThreadPtr(); - - if (!thread) - { - result.AppendError ("args found no thread."); - result.SetStatus (eReturnStatusFailed); +CommandObjectArgs::~CommandObjectArgs() = default; + +Options *CommandObjectArgs::GetOptions() { return &m_options; } + +bool CommandObjectArgs::DoExecute(Args &args, CommandReturnObject &result) { + ConstString target_triple; + + Process *process = m_exe_ctx.GetProcessPtr(); + if (!process) { + result.AppendError("Args found no process."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const ABI *abi = process->GetABI().get(); + if (!abi) { + result.AppendError("The current process has no ABI."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const size_t num_args = args.GetArgumentCount(); + size_t arg_index; + + if (!num_args) { + result.AppendError("args requires at least one argument"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + Thread *thread = m_exe_ctx.GetThreadPtr(); + + if (!thread) { + result.AppendError("args found no thread."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + lldb::StackFrameSP thread_cur_frame = thread->GetSelectedFrame(); + if (!thread_cur_frame) { + result.AppendError("The current thread has no current frame."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + ModuleSP thread_module_sp( + thread_cur_frame->GetFrameCodeAddress().GetModule()); + if (!thread_module_sp) { + result.AppendError("The PC has no associated module."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + TypeSystem *type_system = + thread_module_sp->GetTypeSystemForLanguage(eLanguageTypeC); + if (type_system == nullptr) { + result.AppendError("Unable to create C type system."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + ValueList value_list; + + for (arg_index = 0; arg_index < num_args; ++arg_index) { + const char *arg_type_cstr = args.GetArgumentAtIndex(arg_index); + Value value; + value.SetValueType(Value::eValueTypeScalar); + CompilerType compiler_type; + + char *int_pos; + if ((int_pos = strstr(const_cast(arg_type_cstr), "int"))) { + Encoding encoding = eEncodingSint; + + int width = 0; + + if (int_pos > arg_type_cstr + 1) { + result.AppendErrorWithFormat("Invalid format: %s.\n", arg_type_cstr); + result.SetStatus(eReturnStatusFailed); return false; - } - - lldb::StackFrameSP thread_cur_frame = thread->GetSelectedFrame (); - if (!thread_cur_frame) - { - result.AppendError ("The current thread has no current frame."); - result.SetStatus (eReturnStatusFailed); + } + if (int_pos == arg_type_cstr + 1 && arg_type_cstr[0] != 'u') { + result.AppendErrorWithFormat("Invalid format: %s.\n", arg_type_cstr); + result.SetStatus(eReturnStatusFailed); return false; - } - - ModuleSP thread_module_sp (thread_cur_frame->GetFrameCodeAddress ().GetModule()); - if (!thread_module_sp) - { - result.AppendError ("The PC has no associated module."); - result.SetStatus (eReturnStatusFailed); + } + if (arg_type_cstr[0] == 'u') { + encoding = eEncodingUint; + } + + char *width_pos = int_pos + 3; + + if (!strcmp(width_pos, "8_t")) + width = 8; + else if (!strcmp(width_pos, "16_t")) + width = 16; + else if (!strcmp(width_pos, "32_t")) + width = 32; + else if (!strcmp(width_pos, "64_t")) + width = 64; + else { + result.AppendErrorWithFormat("Invalid format: %s.\n", arg_type_cstr); + result.SetStatus(eReturnStatusFailed); return false; - } + } + compiler_type = + type_system->GetBuiltinTypeForEncodingAndBitSize(encoding, width); - TypeSystem *type_system = thread_module_sp->GetTypeSystemForLanguage(eLanguageTypeC); - if (type_system == nullptr) - { - result.AppendError ("Unable to create C type system."); - result.SetStatus (eReturnStatusFailed); + if (!compiler_type.IsValid()) { + result.AppendErrorWithFormat( + "Couldn't get Clang type for format %s (%s integer, width %d).\n", + arg_type_cstr, (encoding == eEncodingSint ? "signed" : "unsigned"), + width); + + result.SetStatus(eReturnStatusFailed); return false; - } - - ValueList value_list; - - for (arg_index = 0; arg_index < num_args; ++arg_index) - { - const char *arg_type_cstr = args.GetArgumentAtIndex(arg_index); - Value value; - value.SetValueType(Value::eValueTypeScalar); - CompilerType compiler_type; - - char *int_pos; - if ((int_pos = strstr (const_cast(arg_type_cstr), "int"))) - { - Encoding encoding = eEncodingSint; - - int width = 0; - - if (int_pos > arg_type_cstr + 1) - { - result.AppendErrorWithFormat ("Invalid format: %s.\n", arg_type_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (int_pos == arg_type_cstr + 1 && arg_type_cstr[0] != 'u') - { - result.AppendErrorWithFormat ("Invalid format: %s.\n", arg_type_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (arg_type_cstr[0] == 'u') - { - encoding = eEncodingUint; - } - - char *width_pos = int_pos + 3; - - if (!strcmp (width_pos, "8_t")) - width = 8; - else if (!strcmp (width_pos, "16_t")) - width = 16; - else if (!strcmp (width_pos, "32_t")) - width = 32; - else if (!strcmp (width_pos, "64_t")) - width = 64; - else - { - result.AppendErrorWithFormat ("Invalid format: %s.\n", arg_type_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - compiler_type = type_system->GetBuiltinTypeForEncodingAndBitSize(encoding, width); - - if (!compiler_type.IsValid()) - { - result.AppendErrorWithFormat ("Couldn't get Clang type for format %s (%s integer, width %d).\n", - arg_type_cstr, - (encoding == eEncodingSint ? "signed" : "unsigned"), - width); - - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else if (strchr (arg_type_cstr, '*')) - { - if (!strcmp (arg_type_cstr, "void*")) - compiler_type = type_system->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType(); - else if (!strcmp (arg_type_cstr, "char*")) - compiler_type = type_system->GetBasicTypeFromAST(eBasicTypeChar).GetPointerType(); - else - { - result.AppendErrorWithFormat ("Invalid format: %s.\n", arg_type_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - result.AppendErrorWithFormat ("Invalid format: %s.\n", arg_type_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - - value.SetCompilerType (compiler_type); - value_list.PushValue(value); - } - - if (!abi->GetArgumentValues (*thread, value_list)) - { - result.AppendError ("Couldn't get argument values"); - result.SetStatus (eReturnStatusFailed); + } + } else if (strchr(arg_type_cstr, '*')) { + if (!strcmp(arg_type_cstr, "void*")) + compiler_type = + type_system->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType(); + else if (!strcmp(arg_type_cstr, "char*")) + compiler_type = + type_system->GetBasicTypeFromAST(eBasicTypeChar).GetPointerType(); + else { + result.AppendErrorWithFormat("Invalid format: %s.\n", arg_type_cstr); + result.SetStatus(eReturnStatusFailed); return false; + } + } else { + result.AppendErrorWithFormat("Invalid format: %s.\n", arg_type_cstr); + result.SetStatus(eReturnStatusFailed); + return false; } - - result.GetOutputStream ().Printf("Arguments : \n"); - - for (arg_index = 0; arg_index < num_args; ++arg_index) - { - result.GetOutputStream ().Printf ("%" PRIu64 " (%s): ", (uint64_t)arg_index, args.GetArgumentAtIndex (arg_index)); - value_list.GetValueAtIndex (arg_index)->Dump (&result.GetOutputStream ()); - result.GetOutputStream ().Printf("\n"); - } - - return result.Succeeded(); + + value.SetCompilerType(compiler_type); + value_list.PushValue(value); + } + + if (!abi->GetArgumentValues(*thread, value_list)) { + result.AppendError("Couldn't get argument values"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + result.GetOutputStream().Printf("Arguments : \n"); + + for (arg_index = 0; arg_index < num_args; ++arg_index) { + result.GetOutputStream().Printf("%" PRIu64 " (%s): ", (uint64_t)arg_index, + args.GetArgumentAtIndex(arg_index)); + value_list.GetValueAtIndex(arg_index)->Dump(&result.GetOutputStream()); + result.GetOutputStream().Printf("\n"); + } + + return result.Succeeded(); } -OptionDefinition -CommandObjectArgs::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectArgs::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "debug", 'g', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; diff --git a/lldb/source/Commands/CommandObjectArgs.h b/lldb/source/Commands/CommandObjectArgs.h index 90b2f504ca1..2a154a32843 100644 --- a/lldb/source/Commands/CommandObjectArgs.h +++ b/lldb/source/Commands/CommandObjectArgs.h @@ -18,50 +18,39 @@ #include "lldb/Interpreter/Options.h" namespace lldb_private { - - class CommandObjectArgs : public CommandObjectParsed - { - public: - - class CommandOptions : public Options - { - public: - - CommandOptions (CommandInterpreter &interpreter); - - ~CommandOptions() override; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override; - - void - OptionParsingStarting(ExecutionContext *execution_context) override; - - const OptionDefinition* - GetDefinitions() override; - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - }; - - CommandObjectArgs (CommandInterpreter &interpreter); - - ~CommandObjectArgs() override; - - Options * - GetOptions() override; - - protected: - - CommandOptions m_options; - - bool - DoExecute(Args& command, - CommandReturnObject &result) override; - }; - + +class CommandObjectArgs : public CommandObjectParsed { +public: + class CommandOptions : public Options { + public: + CommandOptions(CommandInterpreter &interpreter); + + ~CommandOptions() override; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override; + + void OptionParsingStarting(ExecutionContext *execution_context) override; + + const OptionDefinition *GetDefinitions() override; + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + }; + + CommandObjectArgs(CommandInterpreter &interpreter); + + ~CommandObjectArgs() override; + + Options *GetOptions() override; + +protected: + CommandOptions m_options; + + bool DoExecute(Args &command, CommandReturnObject &result) override; +}; + } // namespace lldb_private #endif // liblldb_CommandObjectArgs_h_ diff --git a/lldb/source/Commands/CommandObjectBreakpoint.cpp b/lldb/source/Commands/CommandObjectBreakpoint.cpp index 6f9250680ca..a5bfe1d1c90 100644 --- a/lldb/source/Commands/CommandObjectBreakpoint.cpp +++ b/lldb/source/Commands/CommandObjectBreakpoint.cpp @@ -18,749 +18,692 @@ #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointIDList.h" #include "lldb/Breakpoint/BreakpointLocation.h" -#include "lldb/Host/StringConvert.h" -#include "lldb/Interpreter/Options.h" -#include "lldb/Interpreter/OptionValueBoolean.h" -#include "lldb/Interpreter/OptionValueString.h" -#include "lldb/Interpreter/OptionValueUInt64.h" #include "lldb/Core/RegularExpression.h" #include "lldb/Core/StreamString.h" +#include "lldb/Host/StringConvert.h" +#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/OptionValueBoolean.h" +#include "lldb/Interpreter/OptionValueString.h" +#include "lldb/Interpreter/OptionValueUInt64.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Target/Language.h" -#include "lldb/Target/Target.h" -#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Target/StackFrame.h" +#include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadSpec.h" using namespace lldb; using namespace lldb_private; -static void -AddBreakpointDescription (Stream *s, Breakpoint *bp, lldb::DescriptionLevel level) -{ - s->IndentMore(); - bp->GetDescription (s, level, true); - s->IndentLess(); - s->EOL(); +static void AddBreakpointDescription(Stream *s, Breakpoint *bp, + lldb::DescriptionLevel level) { + s->IndentMore(); + bp->GetDescription(s, level, true); + s->IndentLess(); + s->EOL(); } //------------------------------------------------------------------------- // CommandObjectBreakpointSet //------------------------------------------------------------------------- -class CommandObjectBreakpointSet : public CommandObjectParsed -{ +class CommandObjectBreakpointSet : public CommandObjectParsed { public: - typedef enum BreakpointSetType - { - eSetTypeInvalid, - eSetTypeFileAndLine, - eSetTypeAddress, - eSetTypeFunctionName, - eSetTypeFunctionRegexp, - eSetTypeSourceRegexp, - eSetTypeException - } BreakpointSetType; - - CommandObjectBreakpointSet (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "breakpoint set", - "Sets a breakpoint or set of breakpoints in the executable.", - "breakpoint set "), - m_options () - { + typedef enum BreakpointSetType { + eSetTypeInvalid, + eSetTypeFileAndLine, + eSetTypeAddress, + eSetTypeFunctionName, + eSetTypeFunctionRegexp, + eSetTypeSourceRegexp, + eSetTypeException + } BreakpointSetType; + + CommandObjectBreakpointSet(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "breakpoint set", + "Sets a breakpoint or set of breakpoints in the executable.", + "breakpoint set "), + m_options() {} + + ~CommandObjectBreakpointSet() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_condition(), m_filenames(), m_line_num(0), m_column(0), + m_func_names(), m_func_name_type_mask(eFunctionNameTypeNone), + m_func_regexp(), m_source_text_regexp(), m_modules(), m_load_addr(), + m_ignore_count(0), m_thread_id(LLDB_INVALID_THREAD_ID), + m_thread_index(UINT32_MAX), m_thread_name(), m_queue_name(), + m_catch_bp(false), m_throw_bp(true), m_hardware(false), + m_exception_language(eLanguageTypeUnknown), + m_language(lldb::eLanguageTypeUnknown), + m_skip_prologue(eLazyBoolCalculate), m_one_shot(false), + m_all_files(false), m_move_to_nearest_code(eLazyBoolCalculate) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': { + m_load_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + } break; + + case 'A': + m_all_files = true; + break; + + case 'b': + m_func_names.push_back(option_arg); + m_func_name_type_mask |= eFunctionNameTypeBase; + break; + + case 'C': { + bool success; + m_column = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid column number: %s", + option_arg); + break; + } + + case 'c': + m_condition.assign(option_arg); + break; + + case 'D': + m_use_dummy = true; + break; + + case 'E': { + LanguageType language = Language::GetLanguageTypeFromString(option_arg); + + switch (language) { + case eLanguageTypeC89: + case eLanguageTypeC: + case eLanguageTypeC99: + case eLanguageTypeC11: + m_exception_language = eLanguageTypeC; + break; + case eLanguageTypeC_plus_plus: + case eLanguageTypeC_plus_plus_03: + case eLanguageTypeC_plus_plus_11: + case eLanguageTypeC_plus_plus_14: + m_exception_language = eLanguageTypeC_plus_plus; + break; + case eLanguageTypeObjC: + m_exception_language = eLanguageTypeObjC; + break; + case eLanguageTypeObjC_plus_plus: + error.SetErrorStringWithFormat( + "Set exception breakpoints separately for c++ and objective-c"); + break; + case eLanguageTypeUnknown: + error.SetErrorStringWithFormat( + "Unknown language type: '%s' for exception breakpoint", + option_arg); + break; + default: + error.SetErrorStringWithFormat( + "Unsupported language type: '%s' for exception breakpoint", + option_arg); + } + } break; + + case 'f': + m_filenames.AppendIfUnique(FileSpec(option_arg, false)); + break; + + case 'F': + m_func_names.push_back(option_arg); + m_func_name_type_mask |= eFunctionNameTypeFull; + break; + + case 'h': { + bool success; + m_catch_bp = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat( + "Invalid boolean value for on-catch option: '%s'", option_arg); + } break; + + case 'H': + m_hardware = true; + break; + + case 'i': + m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_ignore_count == UINT32_MAX) + error.SetErrorStringWithFormat("invalid ignore count '%s'", + option_arg); + break; + + case 'K': { + bool success; + bool value; + value = Args::StringToBoolean(option_arg, true, &success); + if (value) + m_skip_prologue = eLazyBoolYes; + else + m_skip_prologue = eLazyBoolNo; + + if (!success) + error.SetErrorStringWithFormat( + "Invalid boolean value for skip prologue option: '%s'", + option_arg); + } break; + + case 'l': { + bool success; + m_line_num = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid line number: %s.", + option_arg); + break; + } + + case 'L': + m_language = Language::GetLanguageTypeFromString(option_arg); + if (m_language == eLanguageTypeUnknown) + error.SetErrorStringWithFormat( + "Unknown language type: '%s' for breakpoint", option_arg); + break; + + case 'm': { + bool success; + bool value; + value = Args::StringToBoolean(option_arg, true, &success); + if (value) + m_move_to_nearest_code = eLazyBoolYes; + else + m_move_to_nearest_code = eLazyBoolNo; + + if (!success) + error.SetErrorStringWithFormat( + "Invalid boolean value for move-to-nearest-code option: '%s'", + option_arg); + break; + } + + case 'M': + m_func_names.push_back(option_arg); + m_func_name_type_mask |= eFunctionNameTypeMethod; + break; + + case 'n': + m_func_names.push_back(option_arg); + m_func_name_type_mask |= eFunctionNameTypeAuto; + break; + + case 'N': + if (BreakpointID::StringIsBreakpointName(option_arg, error)) + m_breakpoint_names.push_back(option_arg); + break; + + case 'R': { + lldb::addr_t tmp_offset_addr; + tmp_offset_addr = + Args::StringToAddress(execution_context, option_arg, 0, &error); + if (error.Success()) + m_offset_addr = tmp_offset_addr; + } break; + + case 'o': + m_one_shot = true; + break; + + case 'O': + m_exception_extra_args.AppendArgument("-O"); + m_exception_extra_args.AppendArgument(option_arg); + break; + + case 'p': + m_source_text_regexp.assign(option_arg); + break; + + case 'q': + m_queue_name.assign(option_arg); + break; + + case 'r': + m_func_regexp.assign(option_arg); + break; + + case 's': + m_modules.AppendIfUnique(FileSpec(option_arg, false)); + break; + + case 'S': + m_func_names.push_back(option_arg); + m_func_name_type_mask |= eFunctionNameTypeSelector; + break; + + case 't': + m_thread_id = + StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); + if (m_thread_id == LLDB_INVALID_THREAD_ID) + error.SetErrorStringWithFormat("invalid thread id string '%s'", + option_arg); + break; + + case 'T': + m_thread_name.assign(option_arg); + break; + + case 'w': { + bool success; + m_throw_bp = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat( + "Invalid boolean value for on-throw option: '%s'", option_arg); + } break; + + case 'x': + m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_thread_id == UINT32_MAX) + error.SetErrorStringWithFormat("invalid thread index string '%s'", + option_arg); + break; + + case 'X': + m_source_regex_func_names.insert(option_arg); + break; + + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectBreakpointSet() override = default; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_condition.clear(); + m_filenames.Clear(); + m_line_num = 0; + m_column = 0; + m_func_names.clear(); + m_func_name_type_mask = eFunctionNameTypeNone; + m_func_regexp.clear(); + m_source_text_regexp.clear(); + m_modules.Clear(); + m_load_addr = LLDB_INVALID_ADDRESS; + m_offset_addr = 0; + m_ignore_count = 0; + m_thread_id = LLDB_INVALID_THREAD_ID; + m_thread_index = UINT32_MAX; + m_thread_name.clear(); + m_queue_name.clear(); + m_catch_bp = false; + m_throw_bp = true; + m_hardware = false; + m_exception_language = eLanguageTypeUnknown; + m_language = lldb::eLanguageTypeUnknown; + m_skip_prologue = eLazyBoolCalculate; + m_one_shot = false; + m_use_dummy = false; + m_breakpoint_names.clear(); + m_all_files = false; + m_exception_extra_args.Clear(); + m_move_to_nearest_code = eLazyBoolCalculate; + m_source_regex_func_names.clear(); + } - Options * - GetOptions () override - { - return &m_options; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + std::string m_condition; + FileSpecList m_filenames; + uint32_t m_line_num; + uint32_t m_column; + std::vector m_func_names; + std::vector m_breakpoint_names; + uint32_t m_func_name_type_mask; + std::string m_func_regexp; + std::string m_source_text_regexp; + FileSpecList m_modules; + lldb::addr_t m_load_addr; + lldb::addr_t m_offset_addr; + uint32_t m_ignore_count; + lldb::tid_t m_thread_id; + uint32_t m_thread_index; + std::string m_thread_name; + std::string m_queue_name; + bool m_catch_bp; + bool m_throw_bp; + bool m_hardware; // Request to use hardware breakpoints + lldb::LanguageType m_exception_language; + lldb::LanguageType m_language; + LazyBool m_skip_prologue; + bool m_one_shot; + bool m_use_dummy; + bool m_all_files; + Args m_exception_extra_args; + LazyBool m_move_to_nearest_code; + std::unordered_set m_source_regex_func_names; + }; + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + + if (target == nullptr) { + result.AppendError("Invalid target. Must set target before setting " + "breakpoints (see 'target create' command)."); + result.SetStatus(eReturnStatusFailed); + return false; } - class CommandOptions : public Options + // The following are the various types of breakpoints that could be set: + // 1). -f -l -p [-s -g] (setting breakpoint by source location) + // 2). -a [-s -g] (setting breakpoint by address) + // 3). -n [-s -g] (setting breakpoint by function name) + // 4). -r [-s -g] (setting breakpoint by function name regular + // expression) + // 5). -p -f (setting a breakpoint by comparing a reg-exp + // to source text) + // 6). -E [-w -h] (setting a breakpoint for exceptions for a + // given language.) + + BreakpointSetType break_type = eSetTypeInvalid; + + if (m_options.m_line_num != 0) + break_type = eSetTypeFileAndLine; + else if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) + break_type = eSetTypeAddress; + else if (!m_options.m_func_names.empty()) + break_type = eSetTypeFunctionName; + else if (!m_options.m_func_regexp.empty()) + break_type = eSetTypeFunctionRegexp; + else if (!m_options.m_source_text_regexp.empty()) + break_type = eSetTypeSourceRegexp; + else if (m_options.m_exception_language != eLanguageTypeUnknown) + break_type = eSetTypeException; + + Breakpoint *bp = nullptr; + FileSpec module_spec; + const bool internal = false; + + // If the user didn't specify skip-prologue, having an offset should turn + // that off. + if (m_options.m_offset_addr != 0 && + m_options.m_skip_prologue == eLazyBoolCalculate) + m_options.m_skip_prologue = eLazyBoolNo; + + switch (break_type) { + case eSetTypeFileAndLine: // Breakpoint by source position { - public: - CommandOptions () : - Options (), - m_condition (), - m_filenames (), - m_line_num (0), - m_column (0), - m_func_names (), - m_func_name_type_mask (eFunctionNameTypeNone), - m_func_regexp (), - m_source_text_regexp(), - m_modules (), - m_load_addr(), - m_ignore_count (0), - m_thread_id(LLDB_INVALID_THREAD_ID), - m_thread_index (UINT32_MAX), - m_thread_name(), - m_queue_name(), - m_catch_bp (false), - m_throw_bp (true), - m_hardware (false), - m_exception_language (eLanguageTypeUnknown), - m_language (lldb::eLanguageTypeUnknown), - m_skip_prologue (eLazyBoolCalculate), - m_one_shot (false), - m_all_files (false), - m_move_to_nearest_code (eLazyBoolCalculate) - { - } + FileSpec file; + const size_t num_files = m_options.m_filenames.GetSize(); + if (num_files == 0) { + if (!GetDefaultFile(target, file, result)) { + result.AppendError("No file supplied and no default file available."); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else if (num_files > 1) { + result.AppendError("Only one file at a time is allowed for file and " + "line breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } else + file = m_options.m_filenames.GetFileSpecAtIndex(0); + + // Only check for inline functions if + LazyBool check_inlines = eLazyBoolCalculate; + + bp = target + ->CreateBreakpoint(&(m_options.m_modules), file, + m_options.m_line_num, m_options.m_offset_addr, + check_inlines, m_options.m_skip_prologue, + internal, m_options.m_hardware, + m_options.m_move_to_nearest_code) + .get(); + } break; + + case eSetTypeAddress: // Breakpoint by address + { + // If a shared library has been specified, make an lldb_private::Address + // with the library, and + // use that. That way the address breakpoint will track the load location + // of the library. + size_t num_modules_specified = m_options.m_modules.GetSize(); + if (num_modules_specified == 1) { + const FileSpec *file_spec = + m_options.m_modules.GetFileSpecPointerAtIndex(0); + bp = target + ->CreateAddressInModuleBreakpoint(m_options.m_load_addr, + internal, file_spec, + m_options.m_hardware) + .get(); + } else if (num_modules_specified == 0) { + bp = target + ->CreateBreakpoint(m_options.m_load_addr, internal, + m_options.m_hardware) + .get(); + } else { + result.AppendError("Only one shared library can be specified for " + "address breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } + break; + } + case eSetTypeFunctionName: // Breakpoint by function name + { + uint32_t name_type_mask = m_options.m_func_name_type_mask; + + if (name_type_mask == 0) + name_type_mask = eFunctionNameTypeAuto; + + bp = target + ->CreateBreakpoint( + &(m_options.m_modules), &(m_options.m_filenames), + m_options.m_func_names, name_type_mask, m_options.m_language, + m_options.m_offset_addr, m_options.m_skip_prologue, internal, + m_options.m_hardware) + .get(); + } break; + + case eSetTypeFunctionRegexp: // Breakpoint by regular expression function + // name + { + RegularExpression regexp(m_options.m_func_regexp.c_str()); + if (!regexp.IsValid()) { + char err_str[1024]; + regexp.GetErrorAsCString(err_str, sizeof(err_str)); + result.AppendErrorWithFormat( + "Function name regular expression could not be compiled: \"%s\"", + err_str); + result.SetStatus(eReturnStatusFailed); + return false; + } + + bp = target + ->CreateFuncRegexBreakpoint( + &(m_options.m_modules), &(m_options.m_filenames), regexp, + m_options.m_language, m_options.m_skip_prologue, internal, + m_options.m_hardware) + .get(); + } break; + case eSetTypeSourceRegexp: // Breakpoint by regexp on source text. + { + const size_t num_files = m_options.m_filenames.GetSize(); + + if (num_files == 0 && !m_options.m_all_files) { + FileSpec file; + if (!GetDefaultFile(target, file, result)) { + result.AppendError( + "No files provided and could not find default file."); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + m_options.m_filenames.Append(file); + } + } + + RegularExpression regexp(m_options.m_source_text_regexp.c_str()); + if (!regexp.IsValid()) { + char err_str[1024]; + regexp.GetErrorAsCString(err_str, sizeof(err_str)); + result.AppendErrorWithFormat( + "Source text regular expression could not be compiled: \"%s\"", + err_str); + result.SetStatus(eReturnStatusFailed); + return false; + } + bp = target + ->CreateSourceRegexBreakpoint( + &(m_options.m_modules), &(m_options.m_filenames), + m_options.m_source_regex_func_names, regexp, internal, + m_options.m_hardware, m_options.m_move_to_nearest_code) + .get(); + } break; + case eSetTypeException: { + Error precond_error; + bp = target + ->CreateExceptionBreakpoint( + m_options.m_exception_language, m_options.m_catch_bp, + m_options.m_throw_bp, internal, + &m_options.m_exception_extra_args, &precond_error) + .get(); + if (precond_error.Fail()) { + result.AppendErrorWithFormat( + "Error setting extra exception arguments: %s", + precond_error.AsCString()); + target->RemoveBreakpointByID(bp->GetID()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } break; + default: + break; + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - { - m_load_addr = - Args::StringToAddress(execution_context, option_arg, - LLDB_INVALID_ADDRESS, &error); - } - break; - - case 'A': - m_all_files = true; - break; - - case 'b': - m_func_names.push_back (option_arg); - m_func_name_type_mask |= eFunctionNameTypeBase; - break; - - case 'C': - { - bool success; - m_column = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid column number: %s", option_arg); - break; - } - - case 'c': - m_condition.assign(option_arg); - break; - - case 'D': - m_use_dummy = true; - break; - - case 'E': - { - LanguageType language = Language::GetLanguageTypeFromString (option_arg); - - switch (language) - { - case eLanguageTypeC89: - case eLanguageTypeC: - case eLanguageTypeC99: - case eLanguageTypeC11: - m_exception_language = eLanguageTypeC; - break; - case eLanguageTypeC_plus_plus: - case eLanguageTypeC_plus_plus_03: - case eLanguageTypeC_plus_plus_11: - case eLanguageTypeC_plus_plus_14: - m_exception_language = eLanguageTypeC_plus_plus; - break; - case eLanguageTypeObjC: - m_exception_language = eLanguageTypeObjC; - break; - case eLanguageTypeObjC_plus_plus: - error.SetErrorStringWithFormat ("Set exception breakpoints separately for c++ and objective-c"); - break; - case eLanguageTypeUnknown: - error.SetErrorStringWithFormat ("Unknown language type: '%s' for exception breakpoint", option_arg); - break; - default: - error.SetErrorStringWithFormat ("Unsupported language type: '%s' for exception breakpoint", option_arg); - } - } - break; - - case 'f': - m_filenames.AppendIfUnique (FileSpec(option_arg, false)); - break; - - case 'F': - m_func_names.push_back (option_arg); - m_func_name_type_mask |= eFunctionNameTypeFull; - break; - - case 'h': - { - bool success; - m_catch_bp = Args::StringToBoolean (option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat ("Invalid boolean value for on-catch option: '%s'", option_arg); - } - break; - - case 'H': - m_hardware = true; - break; - - case 'i': - m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_ignore_count == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid ignore count '%s'", option_arg); - break; - - case 'K': - { - bool success; - bool value; - value = Args::StringToBoolean (option_arg, true, &success); - if (value) - m_skip_prologue = eLazyBoolYes; - else - m_skip_prologue = eLazyBoolNo; - - if (!success) - error.SetErrorStringWithFormat ("Invalid boolean value for skip prologue option: '%s'", option_arg); - } - break; - - case 'l': - { - bool success; - m_line_num = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat ("invalid line number: %s.", option_arg); - break; - } - - case 'L': - m_language = Language::GetLanguageTypeFromString (option_arg); - if (m_language == eLanguageTypeUnknown) - error.SetErrorStringWithFormat ("Unknown language type: '%s' for breakpoint", option_arg); - break; - - case 'm': - { - bool success; - bool value; - value = Args::StringToBoolean (option_arg, true, &success); - if (value) - m_move_to_nearest_code = eLazyBoolYes; - else - m_move_to_nearest_code = eLazyBoolNo; - - if (!success) - error.SetErrorStringWithFormat ("Invalid boolean value for move-to-nearest-code option: '%s'", option_arg); - break; - } - - case 'M': - m_func_names.push_back (option_arg); - m_func_name_type_mask |= eFunctionNameTypeMethod; - break; - - case 'n': - m_func_names.push_back (option_arg); - m_func_name_type_mask |= eFunctionNameTypeAuto; - break; - - case 'N': - if (BreakpointID::StringIsBreakpointName(option_arg, error)) - m_breakpoint_names.push_back (option_arg); - break; - - case 'R': - { - lldb::addr_t tmp_offset_addr; - tmp_offset_addr = - Args::StringToAddress(execution_context, option_arg, - 0, &error); - if (error.Success()) - m_offset_addr = tmp_offset_addr; - } - break; - - case 'o': - m_one_shot = true; - break; - - case 'O': - m_exception_extra_args.AppendArgument ("-O"); - m_exception_extra_args.AppendArgument (option_arg); - break; - - case 'p': - m_source_text_regexp.assign (option_arg); - break; - - case 'q': - m_queue_name.assign (option_arg); - break; - - case 'r': - m_func_regexp.assign (option_arg); - break; - - case 's': - m_modules.AppendIfUnique (FileSpec (option_arg, false)); - break; - - case 'S': - m_func_names.push_back (option_arg); - m_func_name_type_mask |= eFunctionNameTypeSelector; - break; - - case 't' : - m_thread_id = StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); - if (m_thread_id == LLDB_INVALID_THREAD_ID) - error.SetErrorStringWithFormat ("invalid thread id string '%s'", option_arg); - break; - - case 'T': - m_thread_name.assign (option_arg); - break; - - case 'w': - { - bool success; - m_throw_bp = Args::StringToBoolean (option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat ("Invalid boolean value for on-throw option: '%s'", option_arg); - } - break; - - case 'x': - m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_thread_id == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid thread index string '%s'", option_arg); - break; - - case 'X': - m_source_regex_func_names.insert(option_arg); - break; - - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } + // Now set the various options that were passed in: + if (bp) { + if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) + bp->SetThreadID(m_options.m_thread_id); - return error; - } + if (m_options.m_thread_index != UINT32_MAX) + bp->GetOptions()->GetThreadSpec()->SetIndex(m_options.m_thread_index); - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_condition.clear(); - m_filenames.Clear(); - m_line_num = 0; - m_column = 0; - m_func_names.clear(); - m_func_name_type_mask = eFunctionNameTypeNone; - m_func_regexp.clear(); - m_source_text_regexp.clear(); - m_modules.Clear(); - m_load_addr = LLDB_INVALID_ADDRESS; - m_offset_addr = 0; - m_ignore_count = 0; - m_thread_id = LLDB_INVALID_THREAD_ID; - m_thread_index = UINT32_MAX; - m_thread_name.clear(); - m_queue_name.clear(); - m_catch_bp = false; - m_throw_bp = true; - m_hardware = false; - m_exception_language = eLanguageTypeUnknown; - m_language = lldb::eLanguageTypeUnknown; - m_skip_prologue = eLazyBoolCalculate; - m_one_shot = false; - m_use_dummy = false; - m_breakpoint_names.clear(); - m_all_files = false; - m_exception_extra_args.Clear(); - m_move_to_nearest_code = eLazyBoolCalculate; - m_source_regex_func_names.clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + if (!m_options.m_thread_name.empty()) + bp->GetOptions()->GetThreadSpec()->SetName( + m_options.m_thread_name.c_str()); - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - std::string m_condition; - FileSpecList m_filenames; - uint32_t m_line_num; - uint32_t m_column; - std::vector m_func_names; - std::vector m_breakpoint_names; - uint32_t m_func_name_type_mask; - std::string m_func_regexp; - std::string m_source_text_regexp; - FileSpecList m_modules; - lldb::addr_t m_load_addr; - lldb::addr_t m_offset_addr; - uint32_t m_ignore_count; - lldb::tid_t m_thread_id; - uint32_t m_thread_index; - std::string m_thread_name; - std::string m_queue_name; - bool m_catch_bp; - bool m_throw_bp; - bool m_hardware; // Request to use hardware breakpoints - lldb::LanguageType m_exception_language; - lldb::LanguageType m_language; - LazyBool m_skip_prologue; - bool m_one_shot; - bool m_use_dummy; - bool m_all_files; - Args m_exception_extra_args; - LazyBool m_move_to_nearest_code; - std::unordered_set m_source_regex_func_names; - }; + if (!m_options.m_queue_name.empty()) + bp->GetOptions()->GetThreadSpec()->SetQueueName( + m_options.m_queue_name.c_str()); -protected: - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + if (m_options.m_ignore_count != 0) + bp->GetOptions()->SetIgnoreCount(m_options.m_ignore_count); - if (target == nullptr) - { - result.AppendError ("Invalid target. Must set target before setting breakpoints (see 'target create' command)."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // The following are the various types of breakpoints that could be set: - // 1). -f -l -p [-s -g] (setting breakpoint by source location) - // 2). -a [-s -g] (setting breakpoint by address) - // 3). -n [-s -g] (setting breakpoint by function name) - // 4). -r [-s -g] (setting breakpoint by function name regular expression) - // 5). -p -f (setting a breakpoint by comparing a reg-exp to source text) - // 6). -E [-w -h] (setting a breakpoint for exceptions for a given language.) - - BreakpointSetType break_type = eSetTypeInvalid; - - if (m_options.m_line_num != 0) - break_type = eSetTypeFileAndLine; - else if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) - break_type = eSetTypeAddress; - else if (!m_options.m_func_names.empty()) - break_type = eSetTypeFunctionName; - else if (!m_options.m_func_regexp.empty()) - break_type = eSetTypeFunctionRegexp; - else if (!m_options.m_source_text_regexp.empty()) - break_type = eSetTypeSourceRegexp; - else if (m_options.m_exception_language != eLanguageTypeUnknown) - break_type = eSetTypeException; - - Breakpoint *bp = nullptr; - FileSpec module_spec; - const bool internal = false; - - // If the user didn't specify skip-prologue, having an offset should turn that off. - if (m_options.m_offset_addr != 0 && m_options.m_skip_prologue == eLazyBoolCalculate) - m_options.m_skip_prologue = eLazyBoolNo; - - switch (break_type) - { - case eSetTypeFileAndLine: // Breakpoint by source position - { - FileSpec file; - const size_t num_files = m_options.m_filenames.GetSize(); - if (num_files == 0) - { - if (!GetDefaultFile (target, file, result)) - { - result.AppendError("No file supplied and no default file available."); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else if (num_files > 1) - { - result.AppendError("Only one file at a time is allowed for file and line breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - file = m_options.m_filenames.GetFileSpecAtIndex(0); - - // Only check for inline functions if - LazyBool check_inlines = eLazyBoolCalculate; - - bp = target->CreateBreakpoint (&(m_options.m_modules), - file, - m_options.m_line_num, - m_options.m_offset_addr, - check_inlines, - m_options.m_skip_prologue, - internal, - m_options.m_hardware, - m_options.m_move_to_nearest_code).get(); - } - break; - - case eSetTypeAddress: // Breakpoint by address - { - // If a shared library has been specified, make an lldb_private::Address with the library, and - // use that. That way the address breakpoint will track the load location of the library. - size_t num_modules_specified = m_options.m_modules.GetSize(); - if (num_modules_specified == 1) - { - const FileSpec *file_spec = m_options.m_modules.GetFileSpecPointerAtIndex(0); - bp = target->CreateAddressInModuleBreakpoint (m_options.m_load_addr, - internal, - file_spec, - m_options.m_hardware).get(); - } - else if (num_modules_specified == 0) - { - bp = target->CreateBreakpoint (m_options.m_load_addr, - internal, - m_options.m_hardware).get(); - } - else - { - result.AppendError("Only one shared library can be specified for address breakpoints."); - result.SetStatus(eReturnStatusFailed); - return false; - } - break; - } - case eSetTypeFunctionName: // Breakpoint by function name - { - uint32_t name_type_mask = m_options.m_func_name_type_mask; - - if (name_type_mask == 0) - name_type_mask = eFunctionNameTypeAuto; - - bp = target->CreateBreakpoint (&(m_options.m_modules), - &(m_options.m_filenames), - m_options.m_func_names, - name_type_mask, - m_options.m_language, - m_options.m_offset_addr, - m_options.m_skip_prologue, - internal, - m_options.m_hardware).get(); - } - break; - - case eSetTypeFunctionRegexp: // Breakpoint by regular expression function name - { - RegularExpression regexp(m_options.m_func_regexp.c_str()); - if (!regexp.IsValid()) - { - char err_str[1024]; - regexp.GetErrorAsCString(err_str, sizeof(err_str)); - result.AppendErrorWithFormat("Function name regular expression could not be compiled: \"%s\"", - err_str); - result.SetStatus (eReturnStatusFailed); - return false; - } - - bp = target->CreateFuncRegexBreakpoint (&(m_options.m_modules), - &(m_options.m_filenames), - regexp, - m_options.m_language, - m_options.m_skip_prologue, - internal, - m_options.m_hardware).get(); - } - break; - case eSetTypeSourceRegexp: // Breakpoint by regexp on source text. - { - const size_t num_files = m_options.m_filenames.GetSize(); - - if (num_files == 0 && !m_options.m_all_files) - { - FileSpec file; - if (!GetDefaultFile (target, file, result)) - { - result.AppendError ("No files provided and could not find default file."); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - m_options.m_filenames.Append (file); - } - } - - RegularExpression regexp(m_options.m_source_text_regexp.c_str()); - if (!regexp.IsValid()) - { - char err_str[1024]; - regexp.GetErrorAsCString(err_str, sizeof(err_str)); - result.AppendErrorWithFormat("Source text regular expression could not be compiled: \"%s\"", - err_str); - result.SetStatus (eReturnStatusFailed); - return false; - } - bp = target->CreateSourceRegexBreakpoint (&(m_options.m_modules), - &(m_options.m_filenames), - m_options.m_source_regex_func_names, - regexp, - internal, - m_options.m_hardware, - m_options.m_move_to_nearest_code).get(); - } - break; - case eSetTypeException: - { - Error precond_error; - bp = target->CreateExceptionBreakpoint (m_options.m_exception_language, - m_options.m_catch_bp, - m_options.m_throw_bp, - internal, - &m_options.m_exception_extra_args, - &precond_error).get(); - if (precond_error.Fail()) - { - result.AppendErrorWithFormat("Error setting extra exception arguments: %s", - precond_error.AsCString()); - target->RemoveBreakpointByID(bp->GetID()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - break; - default: - break; - } - - // Now set the various options that were passed in: - if (bp) - { - if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) - bp->SetThreadID (m_options.m_thread_id); - - if (m_options.m_thread_index != UINT32_MAX) - bp->GetOptions()->GetThreadSpec()->SetIndex(m_options.m_thread_index); - - if (!m_options.m_thread_name.empty()) - bp->GetOptions()->GetThreadSpec()->SetName(m_options.m_thread_name.c_str()); - - if (!m_options.m_queue_name.empty()) - bp->GetOptions()->GetThreadSpec()->SetQueueName(m_options.m_queue_name.c_str()); - - if (m_options.m_ignore_count != 0) - bp->GetOptions()->SetIgnoreCount(m_options.m_ignore_count); + if (!m_options.m_condition.empty()) + bp->GetOptions()->SetCondition(m_options.m_condition.c_str()); - if (!m_options.m_condition.empty()) - bp->GetOptions()->SetCondition(m_options.m_condition.c_str()); + if (!m_options.m_breakpoint_names.empty()) { + Error error; // We don't need to check the error here, since the option + // parser checked it... + for (auto name : m_options.m_breakpoint_names) + bp->AddName(name.c_str(), error); + } - if (!m_options.m_breakpoint_names.empty()) - { - Error error; // We don't need to check the error here, since the option parser checked it... - for (auto name : m_options.m_breakpoint_names) - bp->AddName(name.c_str(), error); - } - - bp->SetOneShot (m_options.m_one_shot); - } - - if (bp) - { - Stream &output_stream = result.GetOutputStream(); - const bool show_locations = false; - bp->GetDescription(&output_stream, lldb::eDescriptionLevelInitial, show_locations); - if (target == m_interpreter.GetDebugger().GetDummyTarget()) - output_stream.Printf ("Breakpoint set in dummy target, will get copied into future targets.\n"); - else - { - // Don't print out this warning for exception breakpoints. They can get set before the target - // is set, but we won't know how to actually set the breakpoint till we run. - if (bp->GetNumLocations() == 0 && break_type != eSetTypeException) - { - output_stream.Printf ("WARNING: Unable to resolve breakpoint to any actual locations.\n"); - } - } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else if (!bp) - { - result.AppendError ("Breakpoint creation failed: No breakpoint created."); - result.SetStatus (eReturnStatusFailed); - } + bp->SetOneShot(m_options.m_one_shot); + } - return result.Succeeded(); + if (bp) { + Stream &output_stream = result.GetOutputStream(); + const bool show_locations = false; + bp->GetDescription(&output_stream, lldb::eDescriptionLevelInitial, + show_locations); + if (target == m_interpreter.GetDebugger().GetDummyTarget()) + output_stream.Printf("Breakpoint set in dummy target, will get copied " + "into future targets.\n"); + else { + // Don't print out this warning for exception breakpoints. They can get + // set before the target + // is set, but we won't know how to actually set the breakpoint till we + // run. + if (bp->GetNumLocations() == 0 && break_type != eSetTypeException) { + output_stream.Printf("WARNING: Unable to resolve breakpoint to any " + "actual locations.\n"); + } + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else if (!bp) { + result.AppendError("Breakpoint creation failed: No breakpoint created."); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + private: - bool - GetDefaultFile (Target *target, FileSpec &file, CommandReturnObject &result) - { - uint32_t default_line; - // First use the Source Manager's default file. - // Then use the current stack frame's file. - if (!target->GetSourceManager().GetDefaultFileAndLine(file, default_line)) - { - StackFrame *cur_frame = m_exe_ctx.GetFramePtr(); - if (cur_frame == nullptr) - { - result.AppendError ("No selected frame to use to find the default file."); - result.SetStatus (eReturnStatusFailed); - return false; - } - else if (!cur_frame->HasDebugInformation()) - { - result.AppendError ("Cannot use the selected frame to find the default file, it has no debug info."); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - const SymbolContext &sc = cur_frame->GetSymbolContext (eSymbolContextLineEntry); - if (sc.line_entry.file) - { - file = sc.line_entry.file; - } - else - { - result.AppendError ("Can't find the file for the selected frame to use as the default file."); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - return true; + bool GetDefaultFile(Target *target, FileSpec &file, + CommandReturnObject &result) { + uint32_t default_line; + // First use the Source Manager's default file. + // Then use the current stack frame's file. + if (!target->GetSourceManager().GetDefaultFileAndLine(file, default_line)) { + StackFrame *cur_frame = m_exe_ctx.GetFramePtr(); + if (cur_frame == nullptr) { + result.AppendError( + "No selected frame to use to find the default file."); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!cur_frame->HasDebugInformation()) { + result.AppendError("Cannot use the selected frame to find the default " + "file, it has no debug info."); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + const SymbolContext &sc = + cur_frame->GetSymbolContext(eSymbolContextLineEntry); + if (sc.line_entry.file) { + file = sc.line_entry.file; + } else { + result.AppendError("Can't find the file for the selected frame to " + "use as the default file."); + result.SetStatus(eReturnStatusFailed); + return false; + } + } } - - CommandOptions m_options; + return true; + } + + CommandOptions m_options; }; // If an additional option set beyond LLDB_OPTION_SET_10 is added, make sure to // update the numbers passed to LLDB_OPT_SET_FROM_TO(...) appropriately. -#define LLDB_OPT_FILE ( LLDB_OPT_SET_FROM_TO(1, 9) & ~LLDB_OPT_SET_2 ) -#define LLDB_OPT_NOT_10 ( LLDB_OPT_SET_FROM_TO(1, 10) & ~LLDB_OPT_SET_10 ) -#define LLDB_OPT_SKIP_PROLOGUE ( LLDB_OPT_SET_1 | LLDB_OPT_SET_FROM_TO(3,8) ) -#define LLDB_OPT_OFFSET_APPLIES (LLDB_OPT_SET_1 | LLDB_OPT_SET_FROM_TO(3,8) ) -#define LLDB_OPT_MOVE_TO_NEAREST_CODE ( LLDB_OPT_SET_1 | LLDB_OPT_SET_9 ) -#define LLDB_OPT_EXPR_LANGUAGE ( LLDB_OPT_SET_FROM_TO(3, 8) ) - -OptionDefinition -CommandObjectBreakpointSet::CommandOptions::g_option_table[] = -{ - // clang-format off +#define LLDB_OPT_FILE (LLDB_OPT_SET_FROM_TO(1, 9) & ~LLDB_OPT_SET_2) +#define LLDB_OPT_NOT_10 (LLDB_OPT_SET_FROM_TO(1, 10) & ~LLDB_OPT_SET_10) +#define LLDB_OPT_SKIP_PROLOGUE (LLDB_OPT_SET_1 | LLDB_OPT_SET_FROM_TO(3, 8)) +#define LLDB_OPT_OFFSET_APPLIES (LLDB_OPT_SET_1 | LLDB_OPT_SET_FROM_TO(3, 8)) +#define LLDB_OPT_MOVE_TO_NEAREST_CODE (LLDB_OPT_SET_1 | LLDB_OPT_SET_9) +#define LLDB_OPT_EXPR_LANGUAGE (LLDB_OPT_SET_FROM_TO(3, 8)) + +OptionDefinition CommandObjectBreakpointSet::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_NOT_10, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Set the breakpoint only in this shared library. Can repeat this option " "multiple times to specify multiple shared libraries."}, {LLDB_OPT_SET_ALL, false, "ignore-count", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Set the number of times this breakpoint is skipped before stopping." }, @@ -838,7 +781,7 @@ CommandObjectBreakpointSet::CommandOptions::g_option_table[] = {LLDB_OPT_MOVE_TO_NEAREST_CODE, false, "move-to-nearest-code", 'm', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Move breakpoints to nearest code. If not set the target.move-to-nearest-code " "setting is used."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -846,300 +789,264 @@ CommandObjectBreakpointSet::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Modify -class CommandObjectBreakpointModify : public CommandObjectParsed -{ +class CommandObjectBreakpointModify : public CommandObjectParsed { public: - CommandObjectBreakpointModify (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "breakpoint modify", - "Modify the options on a breakpoint or set of breakpoints in the executable. " - "If no breakpoint is specified, acts on the last created breakpoint. " - "With the exception of -e, -d and -i, passing an empty argument clears the modification.", + CommandObjectBreakpointModify(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "breakpoint modify", + "Modify the options on a breakpoint or set of " + "breakpoints in the executable. " + "If no breakpoint is specified, acts on the last " + "created breakpoint. " + "With the exception of -e, -d and -i, passing an " + "empty argument clears the modification.", nullptr), - m_options () - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, eArgTypeBreakpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back (arg); + m_options() { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, + eArgTypeBreakpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectBreakpointModify() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_ignore_count(0), m_thread_id(LLDB_INVALID_THREAD_ID), + m_thread_id_passed(false), m_thread_index(UINT32_MAX), + m_thread_index_passed(false), m_thread_name(), m_queue_name(), + m_condition(), m_one_shot(false), m_enable_passed(false), + m_enable_value(false), m_name_passed(false), m_queue_passed(false), + m_condition_passed(false), m_one_shot_passed(false), + m_use_dummy(false) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'c': + if (option_arg != nullptr) + m_condition.assign(option_arg); + else + m_condition.clear(); + m_condition_passed = true; + break; + case 'd': + m_enable_passed = true; + m_enable_value = false; + break; + case 'D': + m_use_dummy = true; + break; + case 'e': + m_enable_passed = true; + m_enable_value = true; + break; + case 'i': + m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_ignore_count == UINT32_MAX) + error.SetErrorStringWithFormat("invalid ignore count '%s'", + option_arg); + break; + case 'o': { + bool value, success; + value = Args::StringToBoolean(option_arg, false, &success); + if (success) { + m_one_shot_passed = true; + m_one_shot = value; + } else + error.SetErrorStringWithFormat( + "invalid boolean value '%s' passed for -o option", option_arg); + } break; + case 't': + if (option_arg[0] == '\0') { + m_thread_id = LLDB_INVALID_THREAD_ID; + m_thread_id_passed = true; + } else { + m_thread_id = + StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); + if (m_thread_id == LLDB_INVALID_THREAD_ID) + error.SetErrorStringWithFormat("invalid thread id string '%s'", + option_arg); + else + m_thread_id_passed = true; + } + break; + case 'T': + if (option_arg != nullptr) + m_thread_name.assign(option_arg); + else + m_thread_name.clear(); + m_name_passed = true; + break; + case 'q': + if (option_arg != nullptr) + m_queue_name.assign(option_arg); + else + m_queue_name.clear(); + m_queue_passed = true; + break; + case 'x': + if (option_arg[0] == '\n') { + m_thread_index = UINT32_MAX; + m_thread_index_passed = true; + } else { + m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_thread_id == UINT32_MAX) + error.SetErrorStringWithFormat("invalid thread index string '%s'", + option_arg); + else + m_thread_index_passed = true; + } + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectBreakpointModify() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_ignore_count = 0; + m_thread_id = LLDB_INVALID_THREAD_ID; + m_thread_id_passed = false; + m_thread_index = UINT32_MAX; + m_thread_index_passed = false; + m_thread_name.clear(); + m_queue_name.clear(); + m_condition.clear(); + m_one_shot = false; + m_enable_passed = false; + m_queue_passed = false; + m_name_passed = false; + m_condition_passed = false; + m_one_shot_passed = false; + m_use_dummy = false; } - class CommandOptions : public Options - { - public: - CommandOptions () : - Options (), - m_ignore_count (0), - m_thread_id(LLDB_INVALID_THREAD_ID), - m_thread_id_passed(false), - m_thread_index (UINT32_MAX), - m_thread_index_passed(false), - m_thread_name(), - m_queue_name(), - m_condition (), - m_one_shot (false), - m_enable_passed (false), - m_enable_value (false), - m_name_passed (false), - m_queue_passed (false), - m_condition_passed (false), - m_one_shot_passed (false), - m_use_dummy (false) - { - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'c': - if (option_arg != nullptr) - m_condition.assign (option_arg); - else - m_condition.clear(); - m_condition_passed = true; - break; - case 'd': - m_enable_passed = true; - m_enable_value = false; - break; - case 'D': - m_use_dummy = true; - break; - case 'e': - m_enable_passed = true; - m_enable_value = true; - break; - case 'i': - m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_ignore_count == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid ignore count '%s'", option_arg); - break; - case 'o': - { - bool value, success; - value = Args::StringToBoolean(option_arg, false, &success); - if (success) - { - m_one_shot_passed = true; - m_one_shot = value; - } - else - error.SetErrorStringWithFormat("invalid boolean value '%s' passed for -o option", option_arg); - } - break; - case 't' : - if (option_arg[0] == '\0') - { - m_thread_id = LLDB_INVALID_THREAD_ID; - m_thread_id_passed = true; - } - else - { - m_thread_id = StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); - if (m_thread_id == LLDB_INVALID_THREAD_ID) - error.SetErrorStringWithFormat ("invalid thread id string '%s'", option_arg); - else - m_thread_id_passed = true; - } - break; - case 'T': - if (option_arg != nullptr) - m_thread_name.assign (option_arg); - else - m_thread_name.clear(); - m_name_passed = true; - break; - case 'q': - if (option_arg != nullptr) - m_queue_name.assign (option_arg); - else - m_queue_name.clear(); - m_queue_passed = true; - break; - case 'x': - if (option_arg[0] == '\n') - { - m_thread_index = UINT32_MAX; - m_thread_index_passed = true; - } - else - { - m_thread_index = StringConvert::ToUInt32 (option_arg, UINT32_MAX, 0); - if (m_thread_id == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid thread index string '%s'", option_arg); - else - m_thread_index_passed = true; - } - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } + // Options table: Required for subclasses of Options. - return error; - } + static OptionDefinition g_option_table[]; - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_ignore_count = 0; - m_thread_id = LLDB_INVALID_THREAD_ID; - m_thread_id_passed = false; - m_thread_index = UINT32_MAX; - m_thread_index_passed = false; - m_thread_name.clear(); - m_queue_name.clear(); - m_condition.clear(); - m_one_shot = false; - m_enable_passed = false; - m_queue_passed = false; - m_name_passed = false; - m_condition_passed = false; - m_one_shot_passed = false; - m_use_dummy = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - uint32_t m_ignore_count; - lldb::tid_t m_thread_id; - bool m_thread_id_passed; - uint32_t m_thread_index; - bool m_thread_index_passed; - std::string m_thread_name; - std::string m_queue_name; - std::string m_condition; - bool m_one_shot; - bool m_enable_passed; - bool m_enable_value; - bool m_name_passed; - bool m_queue_passed; - bool m_condition_passed; - bool m_one_shot_passed; - bool m_use_dummy; - }; + // Instance variables to hold the values for command options. + + uint32_t m_ignore_count; + lldb::tid_t m_thread_id; + bool m_thread_id_passed; + uint32_t m_thread_index; + bool m_thread_index_passed; + std::string m_thread_name; + std::string m_queue_name; + std::string m_condition; + bool m_one_shot; + bool m_enable_passed; + bool m_enable_value; + bool m_name_passed; + bool m_queue_passed; + bool m_condition_passed; + bool m_one_shot_passed; + bool m_use_dummy; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); + + BreakpointIDList valid_bp_ids; + + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *bp = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + BreakpointLocation *location = + bp->FindLocationByID(cur_bp_id.GetLocationID()).get(); + if (location) { + if (m_options.m_thread_id_passed) + location->SetThreadID(m_options.m_thread_id); + + if (m_options.m_thread_index_passed) + location->SetThreadIndex(m_options.m_thread_index); + + if (m_options.m_name_passed) + location->SetThreadName(m_options.m_thread_name.c_str()); - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); - - BreakpointIDList valid_bp_ids; - - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *bp = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - BreakpointLocation *location = bp->FindLocationByID (cur_bp_id.GetLocationID()).get(); - if (location) - { - if (m_options.m_thread_id_passed) - location->SetThreadID (m_options.m_thread_id); - - if (m_options.m_thread_index_passed) - location->SetThreadIndex(m_options.m_thread_index); - - if (m_options.m_name_passed) - location->SetThreadName(m_options.m_thread_name.c_str()); - - if (m_options.m_queue_passed) - location->SetQueueName(m_options.m_queue_name.c_str()); - - if (m_options.m_ignore_count != 0) - location->SetIgnoreCount(m_options.m_ignore_count); - - if (m_options.m_enable_passed) - location->SetEnabled (m_options.m_enable_value); - - if (m_options.m_condition_passed) - location->SetCondition (m_options.m_condition.c_str()); - } - } - else - { - if (m_options.m_thread_id_passed) - bp->SetThreadID (m_options.m_thread_id); - - if (m_options.m_thread_index_passed) - bp->SetThreadIndex(m_options.m_thread_index); - - if (m_options.m_name_passed) - bp->SetThreadName(m_options.m_thread_name.c_str()); - - if (m_options.m_queue_passed) - bp->SetQueueName(m_options.m_queue_name.c_str()); - - if (m_options.m_ignore_count != 0) - bp->SetIgnoreCount(m_options.m_ignore_count); - - if (m_options.m_enable_passed) - bp->SetEnabled (m_options.m_enable_value); - - if (m_options.m_condition_passed) - bp->SetCondition (m_options.m_condition.c_str()); - } - } + if (m_options.m_queue_passed) + location->SetQueueName(m_options.m_queue_name.c_str()); + + if (m_options.m_ignore_count != 0) + location->SetIgnoreCount(m_options.m_ignore_count); + + if (m_options.m_enable_passed) + location->SetEnabled(m_options.m_enable_value); + + if (m_options.m_condition_passed) + location->SetCondition(m_options.m_condition.c_str()); } + } else { + if (m_options.m_thread_id_passed) + bp->SetThreadID(m_options.m_thread_id); + + if (m_options.m_thread_index_passed) + bp->SetThreadIndex(m_options.m_thread_index); + + if (m_options.m_name_passed) + bp->SetThreadName(m_options.m_thread_name.c_str()); + + if (m_options.m_queue_passed) + bp->SetQueueName(m_options.m_queue_name.c_str()); + + if (m_options.m_ignore_count != 0) + bp->SetIgnoreCount(m_options.m_ignore_count); + + if (m_options.m_enable_passed) + bp->SetEnabled(m_options.m_enable_value); + + if (m_options.m_condition_passed) + bp->SetCondition(m_options.m_condition.c_str()); + } } - - return result.Succeeded(); + } } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; #pragma mark Modify::CommandOptions OptionDefinition -CommandObjectBreakpointModify::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectBreakpointModify::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "ignore-count", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Set the number of times this breakpoint is skipped before stopping."}, {LLDB_OPT_SET_ALL, false, "one-shot", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "The breakpoint is deleted the first time it stop causes a stop."}, {LLDB_OPT_SET_ALL, false, "thread-index", 'x', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadIndex, "The breakpoint stops only for the thread whose index matches this argument."}, @@ -1151,7 +1058,7 @@ CommandObjectBreakpointModify::CommandOptions::g_option_table[] = {LLDB_OPT_SET_2, false, "disable", 'd', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Disable the breakpoint."}, {LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Sets Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1159,97 +1066,89 @@ CommandObjectBreakpointModify::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Enable -class CommandObjectBreakpointEnable : public CommandObjectParsed -{ +class CommandObjectBreakpointEnable : public CommandObjectParsed { public: - CommandObjectBreakpointEnable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "enable", - "Enable the specified disabled breakpoint(s). If no breakpoints are specified, enable all of them.", - nullptr) - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, eArgTypeBreakpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectBreakpointEnable() override = default; + CommandObjectBreakpointEnable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "enable", + "Enable the specified disabled breakpoint(s). If " + "no breakpoints are specified, enable all of them.", + nullptr) { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, + eArgTypeBreakpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectBreakpointEnable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - const BreakpointList &breakpoints = target->GetBreakpointList(); + const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist to be enabled."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist to be enabled."); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - // No breakpoint selected; enable all currently set breakpoints. - target->EnableAllBreakpoints (); - result.AppendMessageWithFormat ("All breakpoints enabled. (%" PRIu64 " breakpoints)\n", (uint64_t)num_breakpoints); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular breakpoint selected; enable that breakpoint. - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - int enable_count = 0; - int loc_count = 0; - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *breakpoint = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - BreakpointLocation *location = breakpoint->FindLocationByID (cur_bp_id.GetLocationID()).get(); - if (location) - { - location->SetEnabled (true); - ++loc_count; - } - } - else - { - breakpoint->SetEnabled (true); - ++enable_count; - } - } - } - result.AppendMessageWithFormat ("%d breakpoints enabled.\n", enable_count + loc_count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); + if (command.GetArgumentCount() == 0) { + // No breakpoint selected; enable all currently set breakpoints. + target->EnableAllBreakpoints(); + result.AppendMessageWithFormat("All breakpoints enabled. (%" PRIu64 + " breakpoints)\n", + (uint64_t)num_breakpoints); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular breakpoint selected; enable that breakpoint. + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + int enable_count = 0; + int loc_count = 0; + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *breakpoint = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + BreakpointLocation *location = + breakpoint->FindLocationByID(cur_bp_id.GetLocationID()).get(); + if (location) { + location->SetEnabled(true); + ++loc_count; + } + } else { + breakpoint->SetEnabled(true); + ++enable_count; } + } } - - return result.Succeeded(); + result.AppendMessageWithFormat("%d breakpoints enabled.\n", + enable_count + loc_count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1257,23 +1156,24 @@ protected: //------------------------------------------------------------------------- #pragma mark Disable -class CommandObjectBreakpointDisable : public CommandObjectParsed -{ +class CommandObjectBreakpointDisable : public CommandObjectParsed { public: - CommandObjectBreakpointDisable(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "breakpoint disable", "Disable the specified breakpoint(s) without deleting " - "them. If none are specified, disable all " - "breakpoints.", - nullptr) - { - SetHelpLong("Disable the specified breakpoint(s) without deleting them. \ + CommandObjectBreakpointDisable(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "breakpoint disable", + "Disable the specified breakpoint(s) without deleting " + "them. If none are specified, disable all " + "breakpoints.", + nullptr) { + SetHelpLong( + "Disable the specified breakpoint(s) without deleting them. \ If none are specified, disable all breakpoints." - R"( + R"( )" - "Note: disabling a breakpoint will cause none of its locations to be hit \ + "Note: disabling a breakpoint will cause none of its locations to be hit \ regardless of whether individual locations are enabled or disabled. After the sequence:" - R"( + R"( (lldb) break disable 1 (lldb) break enable 1.1 @@ -1284,91 +1184,85 @@ execution will NOT stop at location 1.1. To achieve that, type: (lldb) break enable 1.1 )" - "The first command disables all locations for breakpoint 1, \ + "The first command disables all locations for breakpoint 1, \ the second re-enables the first location."); - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, eArgTypeBreakpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back (arg); - } + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, + eArgTypeBreakpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectBreakpointDisable() override = default; + ~CommandObjectBreakpointDisable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + const BreakpointList &breakpoints = target->GetBreakpointList(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist to be disabled."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist to be disabled."); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - // No breakpoint selected; disable all currently set breakpoints. - target->DisableAllBreakpoints (); - result.AppendMessageWithFormat ("All breakpoints disabled. (%" PRIu64 " breakpoints)\n", (uint64_t)num_breakpoints); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular breakpoint selected; disable that breakpoint. - BreakpointIDList valid_bp_ids; - - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - int disable_count = 0; - int loc_count = 0; - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *breakpoint = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - BreakpointLocation *location = breakpoint->FindLocationByID (cur_bp_id.GetLocationID()).get(); - if (location) - { - location->SetEnabled (false); - ++loc_count; - } - } - else - { - breakpoint->SetEnabled (false); - ++disable_count; - } - } - } - result.AppendMessageWithFormat ("%d breakpoints disabled.\n", disable_count + loc_count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); + if (command.GetArgumentCount() == 0) { + // No breakpoint selected; disable all currently set breakpoints. + target->DisableAllBreakpoints(); + result.AppendMessageWithFormat("All breakpoints disabled. (%" PRIu64 + " breakpoints)\n", + (uint64_t)num_breakpoints); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular breakpoint selected; disable that breakpoint. + BreakpointIDList valid_bp_ids; + + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + int disable_count = 0; + int loc_count = 0; + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *breakpoint = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + BreakpointLocation *location = + breakpoint->FindLocationByID(cur_bp_id.GetLocationID()).get(); + if (location) { + location->SetEnabled(false); + ++loc_count; + } + } else { + breakpoint->SetEnabled(false); + ++disable_count; } + } } - - return result.Succeeded(); + result.AppendMessageWithFormat("%d breakpoints disabled.\n", + disable_count + loc_count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1376,182 +1270,156 @@ protected: //------------------------------------------------------------------------- #pragma mark List -class CommandObjectBreakpointList : public CommandObjectParsed -{ +class CommandObjectBreakpointList : public CommandObjectParsed { public: - CommandObjectBreakpointList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "breakpoint list", - "List some or all breakpoints at configurable levels of detail.", - nullptr), - m_options () - { - CommandArgumentEntry arg; - CommandArgumentData bp_id_arg; - - // Define the first (and only) variant of this arg. - bp_id_arg.arg_type = eArgTypeBreakpointID; - bp_id_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (bp_id_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + CommandObjectBreakpointList(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "breakpoint list", + "List some or all breakpoints at configurable levels of detail.", + nullptr), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData bp_id_arg; + + // Define the first (and only) variant of this arg. + bp_id_arg.arg_type = eArgTypeBreakpointID; + bp_id_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(bp_id_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectBreakpointList() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_level(lldb::eDescriptionLevelBrief), m_use_dummy(false) { } - ~CommandObjectBreakpointList() override = default; - - Options * - GetOptions () override - { - return &m_options; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'b': + m_level = lldb::eDescriptionLevelBrief; + break; + case 'D': + m_use_dummy = true; + break; + case 'f': + m_level = lldb::eDescriptionLevelFull; + break; + case 'v': + m_level = lldb::eDescriptionLevelVerbose; + break; + case 'i': + m_internal = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - - class CommandOptions : public Options - { - public: - CommandOptions () : - Options (), - m_level (lldb::eDescriptionLevelBrief), - m_use_dummy(false) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'b': - m_level = lldb::eDescriptionLevelBrief; - break; - case 'D': - m_use_dummy = true; - break; - case 'f': - m_level = lldb::eDescriptionLevelFull; - break; - case 'v': - m_level = lldb::eDescriptionLevelVerbose; - break; - case 'i': - m_internal = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_level = lldb::eDescriptionLevelFull; - m_internal = false; - m_use_dummy = false; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_level = lldb::eDescriptionLevelFull; + m_internal = false; + m_use_dummy = false; + } - const OptionDefinition * - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - lldb::DescriptionLevel m_level; + lldb::DescriptionLevel m_level; - bool m_internal; - bool m_use_dummy; - }; + bool m_internal; + bool m_use_dummy; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - - if (target == nullptr) - { - result.AppendError ("Invalid target. No current target or breakpoints."); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - return true; - } - - const BreakpointList &breakpoints = target->GetBreakpointList(m_options.m_internal); - std::unique_lock lock; - target->GetBreakpointList(m_options.m_internal).GetListMutex(lock); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - size_t num_breakpoints = breakpoints.GetSize(); + if (target == nullptr) { + result.AppendError("Invalid target. No current target or breakpoints."); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } - if (num_breakpoints == 0) - { - result.AppendMessage ("No breakpoints currently set."); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - return true; - } + const BreakpointList &breakpoints = + target->GetBreakpointList(m_options.m_internal); + std::unique_lock lock; + target->GetBreakpointList(m_options.m_internal).GetListMutex(lock); - Stream &output_stream = result.GetOutputStream(); + size_t num_breakpoints = breakpoints.GetSize(); - if (command.GetArgumentCount() == 0) - { - // No breakpoint selected; show info about all currently set breakpoints. - result.AppendMessage ("Current breakpoints:"); - for (size_t i = 0; i < num_breakpoints; ++i) - { - Breakpoint *breakpoint = breakpoints.GetBreakpointAtIndex (i).get(); - AddBreakpointDescription (&output_stream, breakpoint, m_options.m_level); - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular breakpoints selected; show info about that breakpoint. - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - for (size_t i = 0; i < valid_bp_ids.GetSize(); ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - Breakpoint *breakpoint = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - AddBreakpointDescription (&output_stream, breakpoint, m_options.m_level); - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError("Invalid breakpoint ID."); - result.SetStatus (eReturnStatusFailed); - } - } + if (num_breakpoints == 0) { + result.AppendMessage("No breakpoints currently set."); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } - return result.Succeeded(); + Stream &output_stream = result.GetOutputStream(); + + if (command.GetArgumentCount() == 0) { + // No breakpoint selected; show info about all currently set breakpoints. + result.AppendMessage("Current breakpoints:"); + for (size_t i = 0; i < num_breakpoints; ++i) { + Breakpoint *breakpoint = breakpoints.GetBreakpointAtIndex(i).get(); + AddBreakpointDescription(&output_stream, breakpoint, m_options.m_level); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular breakpoints selected; show info about that breakpoint. + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + for (size_t i = 0; i < valid_bp_ids.GetSize(); ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + Breakpoint *breakpoint = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + AddBreakpointDescription(&output_stream, breakpoint, + m_options.m_level); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("Invalid breakpoint ID."); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; #pragma mark List::CommandOptions -OptionDefinition -CommandObjectBreakpointList::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectBreakpointList::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "internal", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show debugger internal breakpoints" }, {LLDB_OPT_SET_1, false, "brief", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Give a brief description of the breakpoint (no location info)."}, // FIXME: We need to add an "internal" command, and then add this sort of thing to it. @@ -1560,7 +1428,7 @@ CommandObjectBreakpointList::CommandOptions::g_option_table[] = {LLDB_OPT_SET_3, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Explain everything we know about the breakpoint (for debugging debugger bugs)."}, {LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "List Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1568,196 +1436,162 @@ CommandObjectBreakpointList::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Clear -class CommandObjectBreakpointClear : public CommandObjectParsed -{ +class CommandObjectBreakpointClear : public CommandObjectParsed { public: - typedef enum BreakpointClearType - { - eClearTypeInvalid, - eClearTypeFileAndLine - } BreakpointClearType; - - CommandObjectBreakpointClear(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "breakpoint clear", - "Delete or disable breakpoints matching the specified source file and line.", - "breakpoint clear "), - m_options() - { - } + typedef enum BreakpointClearType { + eClearTypeInvalid, + eClearTypeFileAndLine + } BreakpointClearType; - ~CommandObjectBreakpointClear() override = default; + CommandObjectBreakpointClear(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "breakpoint clear", + "Delete or disable breakpoints matching the " + "specified source file and line.", + "breakpoint clear "), + m_options() {} - Options * - GetOptions () override - { - return &m_options; - } + ~CommandObjectBreakpointClear() override = default; - class CommandOptions : public Options - { - public: - CommandOptions () : - Options (), - m_filename (), - m_line_num (0) - { - } + Options *GetOptions() override { return &m_options; } - ~CommandOptions() override = default; + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_filename(), m_line_num(0) {} - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; + ~CommandOptions() override = default; - switch (short_option) - { - case 'f': - m_filename.assign (option_arg); - break; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - case 'l': - m_line_num = StringConvert::ToUInt32 (option_arg, 0); - break; + switch (short_option) { + case 'f': + m_filename.assign(option_arg); + break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } + case 'l': + m_line_num = StringConvert::ToUInt32(option_arg, 0); + break; - return error; - } + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_filename.clear(); - m_line_num = 0; - } + return error; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_filename.clear(); + m_line_num = 0; + } - // Options table: Required for subclasses of Options. + const OptionDefinition *GetDefinitions() override { return g_option_table; } - static OptionDefinition g_option_table[]; + // Options table: Required for subclasses of Options. - // Instance variables to hold the values for command options. + static OptionDefinition g_option_table[]; - std::string m_filename; - uint32_t m_line_num; + // Instance variables to hold the values for command options. - }; + std::string m_filename; + uint32_t m_line_num; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - // The following are the various types of breakpoints that could be cleared: - // 1). -f -l (clearing breakpoint by source location) + // The following are the various types of breakpoints that could be cleared: + // 1). -f -l (clearing breakpoint by source location) - BreakpointClearType break_type = eClearTypeInvalid; + BreakpointClearType break_type = eClearTypeInvalid; - if (m_options.m_line_num != 0) - break_type = eClearTypeFileAndLine; + if (m_options.m_line_num != 0) + break_type = eClearTypeFileAndLine; - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + BreakpointList &breakpoints = target->GetBreakpointList(); + size_t num_breakpoints = breakpoints.GetSize(); - // Early return if there's no breakpoint at all. - if (num_breakpoints == 0) - { - result.AppendError ("Breakpoint clear: No breakpoint cleared."); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } + // Early return if there's no breakpoint at all. + if (num_breakpoints == 0) { + result.AppendError("Breakpoint clear: No breakpoint cleared."); + result.SetStatus(eReturnStatusFailed); + return result.Succeeded(); + } - // Find matching breakpoints and delete them. - - // First create a copy of all the IDs. - std::vector BreakIDs; - for (size_t i = 0; i < num_breakpoints; ++i) - BreakIDs.push_back(breakpoints.GetBreakpointAtIndex(i)->GetID()); - - int num_cleared = 0; - StreamString ss; - switch (break_type) - { - case eClearTypeFileAndLine: // Breakpoint by source position - { - const ConstString filename(m_options.m_filename.c_str()); - BreakpointLocationCollection loc_coll; - - for (size_t i = 0; i < num_breakpoints; ++i) - { - Breakpoint *bp = breakpoints.FindBreakpointByID(BreakIDs[i]).get(); - - if (bp->GetMatchingFileLine(filename, m_options.m_line_num, loc_coll)) - { - // If the collection size is 0, it's a full match and we can just remove the breakpoint. - if (loc_coll.GetSize() == 0) - { - bp->GetDescription(&ss, lldb::eDescriptionLevelBrief); - ss.EOL(); - target->RemoveBreakpointByID (bp->GetID()); - ++num_cleared; - } - } - } - } - break; - - default: - break; - } + // Find matching breakpoints and delete them. - if (num_cleared > 0) - { - Stream &output_stream = result.GetOutputStream(); - output_stream.Printf ("%d breakpoints cleared:\n", num_cleared); - output_stream << ss.GetData(); - output_stream.EOL(); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("Breakpoint clear: No breakpoint cleared."); - result.SetStatus (eReturnStatusFailed); - } + // First create a copy of all the IDs. + std::vector BreakIDs; + for (size_t i = 0; i < num_breakpoints; ++i) + BreakIDs.push_back(breakpoints.GetBreakpointAtIndex(i)->GetID()); + + int num_cleared = 0; + StreamString ss; + switch (break_type) { + case eClearTypeFileAndLine: // Breakpoint by source position + { + const ConstString filename(m_options.m_filename.c_str()); + BreakpointLocationCollection loc_coll; + + for (size_t i = 0; i < num_breakpoints; ++i) { + Breakpoint *bp = breakpoints.FindBreakpointByID(BreakIDs[i]).get(); + + if (bp->GetMatchingFileLine(filename, m_options.m_line_num, loc_coll)) { + // If the collection size is 0, it's a full match and we can just + // remove the breakpoint. + if (loc_coll.GetSize() == 0) { + bp->GetDescription(&ss, lldb::eDescriptionLevelBrief); + ss.EOL(); + target->RemoveBreakpointByID(bp->GetID()); + ++num_cleared; + } + } + } + } break; + + default: + break; + } - return result.Succeeded(); + if (num_cleared > 0) { + Stream &output_stream = result.GetOutputStream(); + output_stream.Printf("%d breakpoints cleared:\n", num_cleared); + output_stream << ss.GetData(); + output_stream.EOL(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("Breakpoint clear: No breakpoint cleared."); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; #pragma mark Clear::CommandOptions OptionDefinition -CommandObjectBreakpointClear::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectBreakpointClear::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "Specify the breakpoint by source location in this particular file."}, {LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Specify the breakpoint by source location at this particular line."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1765,184 +1599,158 @@ CommandObjectBreakpointClear::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Delete -class CommandObjectBreakpointDelete : public CommandObjectParsed -{ +class CommandObjectBreakpointDelete : public CommandObjectParsed { public: - CommandObjectBreakpointDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "breakpoint delete", - "Delete the specified breakpoint(s). If no breakpoints are specified, delete them all.", + CommandObjectBreakpointDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "breakpoint delete", + "Delete the specified breakpoint(s). If no " + "breakpoints are specified, delete them all.", nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, eArgTypeBreakpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back (arg); + m_options() { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeBreakpointID, + eArgTypeBreakpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectBreakpointDelete() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_use_dummy(false), m_force(false) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'f': + m_force = true; + break; + + case 'D': + m_use_dummy = true; + break; + + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectBreakpointDelete() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_use_dummy = false; + m_force = false; } - class CommandOptions : public Options - { - public: - CommandOptions () : - Options (), - m_use_dummy (false), - m_force (false) - { - } - - ~CommandOptions() override = default; + const OptionDefinition *GetDefinitions() override { return g_option_table; } - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; + // Options table: Required for subclasses of Options. - switch (short_option) - { - case 'f': - m_force = true; - break; + static OptionDefinition g_option_table[]; - case 'D': - m_use_dummy = true; - break; - - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_use_dummy = false; - m_force = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - bool m_use_dummy; - bool m_force; - }; + // Instance variables to hold the values for command options. + bool m_use_dummy; + bool m_force; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - const BreakpointList &breakpoints = target->GetBreakpointList(); + const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist to be deleted."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist to be deleted."); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - if (!m_options.m_force && !m_interpreter.Confirm ("About to delete all breakpoints, do you want to do that?", true)) - { - result.AppendMessage("Operation cancelled..."); + if (command.GetArgumentCount() == 0) { + if (!m_options.m_force && + !m_interpreter.Confirm( + "About to delete all breakpoints, do you want to do that?", + true)) { + result.AppendMessage("Operation cancelled..."); + } else { + target->RemoveAllBreakpoints(); + result.AppendMessageWithFormat( + "All breakpoints removed. (%" PRIu64 " breakpoint%s)\n", + (uint64_t)num_breakpoints, num_breakpoints > 1 ? "s" : ""); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular breakpoint selected; disable that breakpoint. + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + int delete_count = 0; + int disable_count = 0; + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *breakpoint = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + BreakpointLocation *location = + breakpoint->FindLocationByID(cur_bp_id.GetLocationID()).get(); + // It makes no sense to try to delete individual locations, so we + // disable them instead. + if (location) { + location->SetEnabled(false); + ++disable_count; + } + } else { + target->RemoveBreakpointByID(cur_bp_id.GetBreakpointID()); + ++delete_count; } - else - { - target->RemoveAllBreakpoints (); - result.AppendMessageWithFormat ("All breakpoints removed. (%" PRIu64 " breakpoint%s)\n", (uint64_t)num_breakpoints, num_breakpoints > 1 ? "s" : ""); - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); + } } - else - { - // Particular breakpoint selected; disable that breakpoint. - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - int delete_count = 0; - int disable_count = 0; - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *breakpoint = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - BreakpointLocation *location = breakpoint->FindLocationByID (cur_bp_id.GetLocationID()).get(); - // It makes no sense to try to delete individual locations, so we disable them instead. - if (location) - { - location->SetEnabled (false); - ++disable_count; - } - } - else - { - target->RemoveBreakpointByID (cur_bp_id.GetBreakpointID()); - ++delete_count; - } - } - } - result.AppendMessageWithFormat ("%d breakpoints deleted; %d breakpoint locations disabled.\n", - delete_count, disable_count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - } - return result.Succeeded(); + result.AppendMessageWithFormat( + "%d breakpoints deleted; %d breakpoint locations disabled.\n", + delete_count, disable_count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } } + return result.Succeeded(); + } private: - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectBreakpointDelete::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectBreakpointDelete::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "force", 'f', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Delete all breakpoints without querying for confirmation."}, {LLDB_OPT_SET_1, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Delete Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1950,374 +1758,327 @@ CommandObjectBreakpointDelete::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- static OptionDefinition g_breakpoint_name_options[] = { - // clang-format off + // clang-format off {LLDB_OPT_SET_1, false, "name", 'N', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBreakpointName, "Specifies a breakpoint name to use."}, {LLDB_OPT_SET_2, false, "breakpoint-id", 'B', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBreakpointID, "Specify a breakpoint ID to use."}, {LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Operate on Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, - // clang-format on + // clang-format on }; -class BreakpointNameOptionGroup : public OptionGroup -{ +class BreakpointNameOptionGroup : public OptionGroup { public: - BreakpointNameOptionGroup() : - OptionGroup(), - m_breakpoint(LLDB_INVALID_BREAK_ID), - m_use_dummy (false) - { + BreakpointNameOptionGroup() + : OptionGroup(), m_breakpoint(LLDB_INVALID_BREAK_ID), m_use_dummy(false) { + } + + ~BreakpointNameOptionGroup() override = default; + + uint32_t GetNumDefinitions() override { + return sizeof(g_breakpoint_name_options) / sizeof(OptionDefinition); + } + + const OptionDefinition *GetDefinitions() override { + return g_breakpoint_name_options; + } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_breakpoint_name_options[option_idx].short_option; + + switch (short_option) { + case 'N': + if (BreakpointID::StringIsBreakpointName(option_value, error) && + error.Success()) + m_name.SetValueFromString(option_value); + break; + + case 'B': + if (m_breakpoint.SetValueFromString(option_value).Fail()) + error.SetErrorStringWithFormat( + "unrecognized value \"%s\" for breakpoint", option_value); + break; + case 'D': + if (m_use_dummy.SetValueFromString(option_value).Fail()) + error.SetErrorStringWithFormat( + "unrecognized value \"%s\" for use-dummy", option_value); + break; + + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; } - - ~BreakpointNameOptionGroup() override = default; - - uint32_t - GetNumDefinitions () override - { - return sizeof (g_breakpoint_name_options) / sizeof (OptionDefinition); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_breakpoint_name_options; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_breakpoint_name_options[option_idx].short_option; - - switch (short_option) - { - case 'N': - if (BreakpointID::StringIsBreakpointName(option_value, error) && error.Success()) - m_name.SetValueFromString(option_value); - break; - - case 'B': - if (m_breakpoint.SetValueFromString(option_value).Fail()) - error.SetErrorStringWithFormat ("unrecognized value \"%s\" for breakpoint", option_value); - break; - case 'D': - if (m_use_dummy.SetValueFromString(option_value).Fail()) - error.SetErrorStringWithFormat ("unrecognized value \"%s\" for use-dummy", option_value); - break; - - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_name.Clear(); - m_breakpoint.Clear(); - m_use_dummy.Clear(); - m_use_dummy.SetDefaultValue(false); - } - - OptionValueString m_name; - OptionValueUInt64 m_breakpoint; - OptionValueBoolean m_use_dummy; + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_name.Clear(); + m_breakpoint.Clear(); + m_use_dummy.Clear(); + m_use_dummy.SetDefaultValue(false); + } + + OptionValueString m_name; + OptionValueUInt64 m_breakpoint; + OptionValueBoolean m_use_dummy; }; -class CommandObjectBreakpointNameAdd : public CommandObjectParsed -{ +class CommandObjectBreakpointNameAdd : public CommandObjectParsed { public: - CommandObjectBreakpointNameAdd (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "add", - "Add a name to the breakpoints provided.", - "breakpoint name add "), - m_name_options(), - m_option_group() - { - // Create the first variant for the first (and only) argument for this command. - CommandArgumentEntry arg1; - CommandArgumentData id_arg; - id_arg.arg_type = eArgTypeBreakpointID; - id_arg.arg_repetition = eArgRepeatOptional; - arg1.push_back(id_arg); - m_arguments.push_back (arg1); - - m_option_group.Append (&m_name_options, LLDB_OPT_SET_1, LLDB_OPT_SET_ALL); - m_option_group.Finalize(); - } - - ~CommandObjectBreakpointNameAdd() override = default; - - Options * - GetOptions() override - { - return &m_option_group; - } + CommandObjectBreakpointNameAdd(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "add", "Add a name to the breakpoints provided.", + "breakpoint name add "), + m_name_options(), m_option_group() { + // Create the first variant for the first (and only) argument for this + // command. + CommandArgumentEntry arg1; + CommandArgumentData id_arg; + id_arg.arg_type = eArgTypeBreakpointID; + id_arg.arg_repetition = eArgRepeatOptional; + arg1.push_back(id_arg); + m_arguments.push_back(arg1); + + m_option_group.Append(&m_name_options, LLDB_OPT_SET_1, LLDB_OPT_SET_ALL); + m_option_group.Finalize(); + } + + ~CommandObjectBreakpointNameAdd() override = default; + + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (!m_name_options.m_name.OptionWasSet()) - { - result.SetError("No name option provided."); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (!m_name_options.m_name.OptionWasSet()) { + result.SetError("No name option provided."); + return false; + } - Target *target = GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); + Target *target = + GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - const BreakpointList &breakpoints = target->GetBreakpointList(); + const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.SetError("No breakpoints, cannot add names."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Particular breakpoint selected; disable that breakpoint. - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - if (valid_bp_ids.GetSize() == 0) - { - result.SetError("No breakpoints specified, cannot add names."); - result.SetStatus (eReturnStatusFailed); - return false; - } - size_t num_valid_ids = valid_bp_ids.GetSize(); - for (size_t index = 0; index < num_valid_ids; index++) - { - lldb::break_id_t bp_id = valid_bp_ids.GetBreakpointIDAtIndex(index).GetBreakpointID(); - BreakpointSP bp_sp = breakpoints.FindBreakpointByID(bp_id); - Error error; // We don't need to check the error here, since the option parser checked it... - bp_sp->AddName(m_name_options.m_name.GetCurrentValue(), error); - } - } + size_t num_breakpoints = breakpoints.GetSize(); + if (num_breakpoints == 0) { + result.SetError("No breakpoints, cannot add names."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return true; + // Particular breakpoint selected; disable that breakpoint. + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + if (valid_bp_ids.GetSize() == 0) { + result.SetError("No breakpoints specified, cannot add names."); + result.SetStatus(eReturnStatusFailed); + return false; + } + size_t num_valid_ids = valid_bp_ids.GetSize(); + for (size_t index = 0; index < num_valid_ids; index++) { + lldb::break_id_t bp_id = + valid_bp_ids.GetBreakpointIDAtIndex(index).GetBreakpointID(); + BreakpointSP bp_sp = breakpoints.FindBreakpointByID(bp_id); + Error error; // We don't need to check the error here, since the option + // parser checked it... + bp_sp->AddName(m_name_options.m_name.GetCurrentValue(), error); + } } + return true; + } + private: - BreakpointNameOptionGroup m_name_options; - OptionGroupOptions m_option_group; + BreakpointNameOptionGroup m_name_options; + OptionGroupOptions m_option_group; }; -class CommandObjectBreakpointNameDelete : public CommandObjectParsed -{ +class CommandObjectBreakpointNameDelete : public CommandObjectParsed { public: - CommandObjectBreakpointNameDelete (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "delete", - "Delete a name from the breakpoints provided.", - "breakpoint name delete "), - m_name_options(), - m_option_group() - { - // Create the first variant for the first (and only) argument for this command. - CommandArgumentEntry arg1; - CommandArgumentData id_arg; - id_arg.arg_type = eArgTypeBreakpointID; - id_arg.arg_repetition = eArgRepeatOptional; - arg1.push_back(id_arg); - m_arguments.push_back (arg1); - - m_option_group.Append (&m_name_options, LLDB_OPT_SET_1, LLDB_OPT_SET_ALL); - m_option_group.Finalize(); - } - - ~CommandObjectBreakpointNameDelete() override = default; - - Options * - GetOptions() override - { - return &m_option_group; - } + CommandObjectBreakpointNameDelete(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "delete", + "Delete a name from the breakpoints provided.", + "breakpoint name delete "), + m_name_options(), m_option_group() { + // Create the first variant for the first (and only) argument for this + // command. + CommandArgumentEntry arg1; + CommandArgumentData id_arg; + id_arg.arg_type = eArgTypeBreakpointID; + id_arg.arg_repetition = eArgRepeatOptional; + arg1.push_back(id_arg); + m_arguments.push_back(arg1); + + m_option_group.Append(&m_name_options, LLDB_OPT_SET_1, LLDB_OPT_SET_ALL); + m_option_group.Finalize(); + } + + ~CommandObjectBreakpointNameDelete() override = default; + + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (!m_name_options.m_name.OptionWasSet()) - { - result.SetError("No name option provided."); - return false; - } - - Target *target = GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (!m_name_options.m_name.OptionWasSet()) { + result.SetError("No name option provided."); + return false; + } - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } + Target *target = + GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - const BreakpointList &breakpoints = target->GetBreakpointList(); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); - size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.SetError("No breakpoints, cannot delete names."); - result.SetStatus (eReturnStatusFailed); - return false; - } + const BreakpointList &breakpoints = target->GetBreakpointList(); - // Particular breakpoint selected; disable that breakpoint. - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - if (valid_bp_ids.GetSize() == 0) - { - result.SetError("No breakpoints specified, cannot delete names."); - result.SetStatus (eReturnStatusFailed); - return false; - } - size_t num_valid_ids = valid_bp_ids.GetSize(); - for (size_t index = 0; index < num_valid_ids; index++) - { - lldb::break_id_t bp_id = valid_bp_ids.GetBreakpointIDAtIndex(index).GetBreakpointID(); - BreakpointSP bp_sp = breakpoints.FindBreakpointByID(bp_id); - bp_sp->RemoveName(m_name_options.m_name.GetCurrentValue()); - } - } + size_t num_breakpoints = breakpoints.GetSize(); + if (num_breakpoints == 0) { + result.SetError("No breakpoints, cannot delete names."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return true; + // Particular breakpoint selected; disable that breakpoint. + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + if (valid_bp_ids.GetSize() == 0) { + result.SetError("No breakpoints specified, cannot delete names."); + result.SetStatus(eReturnStatusFailed); + return false; + } + size_t num_valid_ids = valid_bp_ids.GetSize(); + for (size_t index = 0; index < num_valid_ids; index++) { + lldb::break_id_t bp_id = + valid_bp_ids.GetBreakpointIDAtIndex(index).GetBreakpointID(); + BreakpointSP bp_sp = breakpoints.FindBreakpointByID(bp_id); + bp_sp->RemoveName(m_name_options.m_name.GetCurrentValue()); + } } + return true; + } + private: - BreakpointNameOptionGroup m_name_options; - OptionGroupOptions m_option_group; + BreakpointNameOptionGroup m_name_options; + OptionGroupOptions m_option_group; }; -class CommandObjectBreakpointNameList : public CommandObjectParsed -{ +class CommandObjectBreakpointNameList : public CommandObjectParsed { public: - CommandObjectBreakpointNameList (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "list", - "List either the names for a breakpoint or the breakpoints for a given name.", - "breakpoint name list "), - m_name_options(), - m_option_group() - { - m_option_group.Append (&m_name_options); - m_option_group.Finalize(); - } + CommandObjectBreakpointNameList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "list", + "List either the names for a breakpoint or the " + "breakpoints for a given name.", + "breakpoint name list "), + m_name_options(), m_option_group() { + m_option_group.Append(&m_name_options); + m_option_group.Finalize(); + } - ~CommandObjectBreakpointNameList() override = default; + ~CommandObjectBreakpointNameList() override = default; - Options * - GetOptions() override - { - return &m_option_group; - } + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); - - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or breakpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - if (m_name_options.m_name.OptionWasSet()) - { - const char *name = m_name_options.m_name.GetCurrentValue(); - std::unique_lock lock; - target->GetBreakpointList().GetListMutex(lock); - - BreakpointList &breakpoints = target->GetBreakpointList(); - for (BreakpointSP bp_sp : breakpoints.Breakpoints()) - { - if (bp_sp->MatchesName(name)) - { - StreamString s; - bp_sp->GetDescription(&s, eDescriptionLevelBrief); - s.EOL(); - result.AppendMessage(s.GetData()); - } - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = + GetSelectedOrDummyTarget(m_name_options.m_use_dummy.GetCurrentValue()); + + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or breakpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } - } - else if (m_name_options.m_breakpoint.OptionWasSet()) - { - BreakpointSP bp_sp = target->GetBreakpointList().FindBreakpointByID(m_name_options.m_breakpoint.GetCurrentValue()); - if (bp_sp) - { - std::vector names; - bp_sp->GetNames (names); - result.AppendMessage ("Names:"); - for (auto name : names) - result.AppendMessageWithFormat (" %s\n", name.c_str()); - } - else - { - result.AppendErrorWithFormat ("Could not find breakpoint %" PRId64 ".\n", - m_name_options.m_breakpoint.GetCurrentValue()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - result.SetError ("Must specify -N or -B option to list."); - result.SetStatus (eReturnStatusFailed); - return false; - } - return true; + if (m_name_options.m_name.OptionWasSet()) { + const char *name = m_name_options.m_name.GetCurrentValue(); + std::unique_lock lock; + target->GetBreakpointList().GetListMutex(lock); + + BreakpointList &breakpoints = target->GetBreakpointList(); + for (BreakpointSP bp_sp : breakpoints.Breakpoints()) { + if (bp_sp->MatchesName(name)) { + StreamString s; + bp_sp->GetDescription(&s, eDescriptionLevelBrief); + s.EOL(); + result.AppendMessage(s.GetData()); + } + } + + } else if (m_name_options.m_breakpoint.OptionWasSet()) { + BreakpointSP bp_sp = target->GetBreakpointList().FindBreakpointByID( + m_name_options.m_breakpoint.GetCurrentValue()); + if (bp_sp) { + std::vector names; + bp_sp->GetNames(names); + result.AppendMessage("Names:"); + for (auto name : names) + result.AppendMessageWithFormat(" %s\n", name.c_str()); + } else { + result.AppendErrorWithFormat( + "Could not find breakpoint %" PRId64 ".\n", + m_name_options.m_breakpoint.GetCurrentValue()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + result.SetError("Must specify -N or -B option to list."); + result.SetStatus(eReturnStatusFailed); + return false; } + return true; + } private: - BreakpointNameOptionGroup m_name_options; - OptionGroupOptions m_option_group; + BreakpointNameOptionGroup m_name_options; + OptionGroupOptions m_option_group; }; //------------------------------------------------------------------------- // CommandObjectMultiwordBreakpoint //------------------------------------------------------------------------- -class CommandObjectBreakpointName : public CommandObjectMultiword -{ +class CommandObjectBreakpointName : public CommandObjectMultiword { public: - CommandObjectBreakpointName(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "name", "Commands to manage name tags for breakpoints", - "breakpoint name []") - { - CommandObjectSP add_command_object (new CommandObjectBreakpointNameAdd (interpreter)); - CommandObjectSP delete_command_object (new CommandObjectBreakpointNameDelete (interpreter)); - CommandObjectSP list_command_object (new CommandObjectBreakpointNameList (interpreter)); - - LoadSubCommand ("add", add_command_object); - LoadSubCommand ("delete", delete_command_object); - LoadSubCommand ("list", list_command_object); - } - - ~CommandObjectBreakpointName() override = default; + CommandObjectBreakpointName(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "name", "Commands to manage name tags for breakpoints", + "breakpoint name []") { + CommandObjectSP add_command_object( + new CommandObjectBreakpointNameAdd(interpreter)); + CommandObjectSP delete_command_object( + new CommandObjectBreakpointNameDelete(interpreter)); + CommandObjectSP list_command_object( + new CommandObjectBreakpointNameList(interpreter)); + + LoadSubCommand("add", add_command_object); + LoadSubCommand("delete", delete_command_object); + LoadSubCommand("list", list_command_object); + } + + ~CommandObjectBreakpointName() override = default; }; //------------------------------------------------------------------------- @@ -2325,120 +2086,134 @@ public: //------------------------------------------------------------------------- #pragma mark MultiwordBreakpoint -CommandObjectMultiwordBreakpoint::CommandObjectMultiwordBreakpoint(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "breakpoint", - "Commands for operating on breakpoints (see 'help b' for shorthand.)", - "breakpoint []") -{ - CommandObjectSP list_command_object (new CommandObjectBreakpointList (interpreter)); - CommandObjectSP enable_command_object (new CommandObjectBreakpointEnable (interpreter)); - CommandObjectSP disable_command_object (new CommandObjectBreakpointDisable (interpreter)); - CommandObjectSP clear_command_object (new CommandObjectBreakpointClear (interpreter)); - CommandObjectSP delete_command_object (new CommandObjectBreakpointDelete (interpreter)); - CommandObjectSP set_command_object (new CommandObjectBreakpointSet (interpreter)); - CommandObjectSP command_command_object (new CommandObjectBreakpointCommand (interpreter)); - CommandObjectSP modify_command_object (new CommandObjectBreakpointModify(interpreter)); - CommandObjectSP name_command_object (new CommandObjectBreakpointName(interpreter)); - - list_command_object->SetCommandName ("breakpoint list"); - enable_command_object->SetCommandName("breakpoint enable"); - disable_command_object->SetCommandName("breakpoint disable"); - clear_command_object->SetCommandName("breakpoint clear"); - delete_command_object->SetCommandName("breakpoint delete"); - set_command_object->SetCommandName("breakpoint set"); - command_command_object->SetCommandName ("breakpoint command"); - modify_command_object->SetCommandName ("breakpoint modify"); - name_command_object->SetCommandName ("breakpoint name"); - - LoadSubCommand ("list", list_command_object); - LoadSubCommand ("enable", enable_command_object); - LoadSubCommand ("disable", disable_command_object); - LoadSubCommand ("clear", clear_command_object); - LoadSubCommand ("delete", delete_command_object); - LoadSubCommand ("set", set_command_object); - LoadSubCommand ("command", command_command_object); - LoadSubCommand ("modify", modify_command_object); - LoadSubCommand ("name", name_command_object); +CommandObjectMultiwordBreakpoint::CommandObjectMultiwordBreakpoint( + CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "breakpoint", + "Commands for operating on breakpoints (see 'help b' for shorthand.)", + "breakpoint []") { + CommandObjectSP list_command_object( + new CommandObjectBreakpointList(interpreter)); + CommandObjectSP enable_command_object( + new CommandObjectBreakpointEnable(interpreter)); + CommandObjectSP disable_command_object( + new CommandObjectBreakpointDisable(interpreter)); + CommandObjectSP clear_command_object( + new CommandObjectBreakpointClear(interpreter)); + CommandObjectSP delete_command_object( + new CommandObjectBreakpointDelete(interpreter)); + CommandObjectSP set_command_object( + new CommandObjectBreakpointSet(interpreter)); + CommandObjectSP command_command_object( + new CommandObjectBreakpointCommand(interpreter)); + CommandObjectSP modify_command_object( + new CommandObjectBreakpointModify(interpreter)); + CommandObjectSP name_command_object( + new CommandObjectBreakpointName(interpreter)); + + list_command_object->SetCommandName("breakpoint list"); + enable_command_object->SetCommandName("breakpoint enable"); + disable_command_object->SetCommandName("breakpoint disable"); + clear_command_object->SetCommandName("breakpoint clear"); + delete_command_object->SetCommandName("breakpoint delete"); + set_command_object->SetCommandName("breakpoint set"); + command_command_object->SetCommandName("breakpoint command"); + modify_command_object->SetCommandName("breakpoint modify"); + name_command_object->SetCommandName("breakpoint name"); + + LoadSubCommand("list", list_command_object); + LoadSubCommand("enable", enable_command_object); + LoadSubCommand("disable", disable_command_object); + LoadSubCommand("clear", clear_command_object); + LoadSubCommand("delete", delete_command_object); + LoadSubCommand("set", set_command_object); + LoadSubCommand("command", command_command_object); + LoadSubCommand("modify", modify_command_object); + LoadSubCommand("name", name_command_object); } CommandObjectMultiwordBreakpoint::~CommandObjectMultiwordBreakpoint() = default; -void -CommandObjectMultiwordBreakpoint::VerifyIDs (Args &args, - Target *target, - bool allow_locations, - CommandReturnObject &result, - BreakpointIDList *valid_ids) -{ - // args can be strings representing 1). integers (for breakpoint ids) - // 2). the full breakpoint & location canonical representation - // 3). the word "to" or a hyphen, representing a range (in which case there - // had *better* be an entry both before & after of one of the first two types. - // 4). A breakpoint name - // If args is empty, we will use the last created breakpoint (if there is one.) - - Args temp_args; - - if (args.GetArgumentCount() == 0) - { - if (target->GetLastCreatedBreakpoint()) - { - valid_ids->AddBreakpointID (BreakpointID(target->GetLastCreatedBreakpoint()->GetID(), LLDB_INVALID_BREAK_ID)); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError("No breakpoint specified and no last created breakpoint."); - result.SetStatus (eReturnStatusFailed); - } - return; +void CommandObjectMultiwordBreakpoint::VerifyIDs(Args &args, Target *target, + bool allow_locations, + CommandReturnObject &result, + BreakpointIDList *valid_ids) { + // args can be strings representing 1). integers (for breakpoint ids) + // 2). the full breakpoint & location + // canonical representation + // 3). the word "to" or a hyphen, + // representing a range (in which case there + // had *better* be an entry both before & + // after of one of the first two types. + // 4). A breakpoint name + // If args is empty, we will use the last created breakpoint (if there is + // one.) + + Args temp_args; + + if (args.GetArgumentCount() == 0) { + if (target->GetLastCreatedBreakpoint()) { + valid_ids->AddBreakpointID(BreakpointID( + target->GetLastCreatedBreakpoint()->GetID(), LLDB_INVALID_BREAK_ID)); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError( + "No breakpoint specified and no last created breakpoint."); + result.SetStatus(eReturnStatusFailed); } - - // Create a new Args variable to use; copy any non-breakpoint-id-ranges stuff directly from the old ARGS to - // the new TEMP_ARGS. Do not copy breakpoint id range strings over; instead generate a list of strings for - // all the breakpoint ids in the range, and shove all of those breakpoint id strings into TEMP_ARGS. - - BreakpointIDList::FindAndReplaceIDRanges (args, target, allow_locations, result, temp_args); - - // NOW, convert the list of breakpoint id strings in TEMP_ARGS into an actual BreakpointIDList: - - valid_ids->InsertStringArray (temp_args.GetConstArgumentVector(), temp_args.GetArgumentCount(), result); - - // At this point, all of the breakpoint ids that the user passed in have been converted to breakpoint IDs - // and put into valid_ids. - - if (result.Succeeded()) - { - // Now that we've converted everything from args into a list of breakpoint ids, go through our tentative list - // of breakpoint id's and verify that they correspond to valid/currently set breakpoints. - - const size_t count = valid_ids->GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_ids->GetBreakpointIDAtIndex (i); - Breakpoint *breakpoint = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - if (breakpoint != nullptr) - { - const size_t num_locations = breakpoint->GetNumLocations(); - if (static_cast(cur_bp_id.GetLocationID()) > num_locations) - { - StreamString id_str; - BreakpointID::GetCanonicalReference (&id_str, - cur_bp_id.GetBreakpointID(), - cur_bp_id.GetLocationID()); - i = valid_ids->GetSize() + 1; - result.AppendErrorWithFormat ("'%s' is not a currently valid breakpoint/location id.\n", - id_str.GetData()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - i = valid_ids->GetSize() + 1; - result.AppendErrorWithFormat("'%d' is not a currently valid breakpoint ID.\n", - cur_bp_id.GetBreakpointID()); - result.SetStatus (eReturnStatusFailed); - } - } + return; + } + + // Create a new Args variable to use; copy any non-breakpoint-id-ranges stuff + // directly from the old ARGS to + // the new TEMP_ARGS. Do not copy breakpoint id range strings over; instead + // generate a list of strings for + // all the breakpoint ids in the range, and shove all of those breakpoint id + // strings into TEMP_ARGS. + + BreakpointIDList::FindAndReplaceIDRanges(args, target, allow_locations, + result, temp_args); + + // NOW, convert the list of breakpoint id strings in TEMP_ARGS into an actual + // BreakpointIDList: + + valid_ids->InsertStringArray(temp_args.GetConstArgumentVector(), + temp_args.GetArgumentCount(), result); + + // At this point, all of the breakpoint ids that the user passed in have been + // converted to breakpoint IDs + // and put into valid_ids. + + if (result.Succeeded()) { + // Now that we've converted everything from args into a list of breakpoint + // ids, go through our tentative list + // of breakpoint id's and verify that they correspond to valid/currently set + // breakpoints. + + const size_t count = valid_ids->GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_ids->GetBreakpointIDAtIndex(i); + Breakpoint *breakpoint = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + if (breakpoint != nullptr) { + const size_t num_locations = breakpoint->GetNumLocations(); + if (static_cast(cur_bp_id.GetLocationID()) > num_locations) { + StreamString id_str; + BreakpointID::GetCanonicalReference( + &id_str, cur_bp_id.GetBreakpointID(), cur_bp_id.GetLocationID()); + i = valid_ids->GetSize() + 1; + result.AppendErrorWithFormat( + "'%s' is not a currently valid breakpoint/location id.\n", + id_str.GetData()); + result.SetStatus(eReturnStatusFailed); + } + } else { + i = valid_ids->GetSize() + 1; + result.AppendErrorWithFormat( + "'%d' is not a currently valid breakpoint ID.\n", + cur_bp_id.GetBreakpointID()); + result.SetStatus(eReturnStatusFailed); + } } + } } diff --git a/lldb/source/Commands/CommandObjectBreakpoint.h b/lldb/source/Commands/CommandObjectBreakpoint.h index 123e8232c98..6e14b8f876a 100644 --- a/lldb/source/Commands/CommandObjectBreakpoint.h +++ b/lldb/source/Commands/CommandObjectBreakpoint.h @@ -19,9 +19,9 @@ // Other libraries and framework includes // Project includes #include "lldb/Core/Address.h" +#include "lldb/Core/STLUtils.h" #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/Options.h" -#include "lldb/Core/STLUtils.h" namespace lldb_private { @@ -29,28 +29,28 @@ namespace lldb_private { // CommandObjectMultiwordBreakpoint //------------------------------------------------------------------------- -class CommandObjectMultiwordBreakpoint : public CommandObjectMultiword -{ +class CommandObjectMultiwordBreakpoint : public CommandObjectMultiword { public: - CommandObjectMultiwordBreakpoint (CommandInterpreter &interpreter); + CommandObjectMultiwordBreakpoint(CommandInterpreter &interpreter); - ~CommandObjectMultiwordBreakpoint() override; + ~CommandObjectMultiwordBreakpoint() override; - static void - VerifyBreakpointOrLocationIDs (Args &args, Target *target, CommandReturnObject &result, BreakpointIDList *valid_ids) - { - VerifyIDs (args, target, true, result, valid_ids); - } + static void VerifyBreakpointOrLocationIDs(Args &args, Target *target, + CommandReturnObject &result, + BreakpointIDList *valid_ids) { + VerifyIDs(args, target, true, result, valid_ids); + } - static void - VerifyBreakpointIDs (Args &args, Target *target, CommandReturnObject &result, BreakpointIDList *valid_ids) - { - VerifyIDs (args, target, false, result, valid_ids); - } + static void VerifyBreakpointIDs(Args &args, Target *target, + CommandReturnObject &result, + BreakpointIDList *valid_ids) { + VerifyIDs(args, target, false, result, valid_ids); + } private: - static void - VerifyIDs (Args &args, Target *target, bool allow_locations, CommandReturnObject &result, BreakpointIDList *valid_ids); + static void VerifyIDs(Args &args, Target *target, bool allow_locations, + CommandReturnObject &result, + BreakpointIDList *valid_ids); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectBreakpointCommand.cpp b/lldb/source/Commands/CommandObjectBreakpointCommand.cpp index ce6d0ef1155..557cb5f13a9 100644 --- a/lldb/source/Commands/CommandObjectBreakpointCommand.cpp +++ b/lldb/source/Commands/CommandObjectBreakpointCommand.cpp @@ -13,16 +13,16 @@ // Project includes #include "CommandObjectBreakpointCommand.h" #include "CommandObjectBreakpoint.h" +#include "lldb/Breakpoint/Breakpoint.h" +#include "lldb/Breakpoint/BreakpointIDList.h" +#include "lldb/Breakpoint/BreakpointLocation.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" #include "lldb/Core/IOHandler.h" +#include "lldb/Core/State.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" -#include "lldb/Breakpoint/BreakpointIDList.h" -#include "lldb/Breakpoint/Breakpoint.h" -#include "lldb/Breakpoint/BreakpointLocation.h" -#include "lldb/Breakpoint/StoppointCallbackContext.h" -#include "lldb/Core/State.h" using namespace lldb; using namespace lldb_private; @@ -31,44 +31,52 @@ using namespace lldb_private; // CommandObjectBreakpointCommandAdd //------------------------------------------------------------------------- -class CommandObjectBreakpointCommandAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectBreakpointCommandAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { public: - CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "add", - "Add LLDB commands to a breakpoint, to be executed whenever the breakpoint is hit." - " If no breakpoint is specified, adds the commands to the last created breakpoint.", - nullptr), - IOHandlerDelegateMultiline("DONE", IOHandlerDelegate::Completion::LLDBCommand), - m_options() - { - SetHelpLong ( -R"( + CommandObjectBreakpointCommandAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "add", + "Add LLDB commands to a breakpoint, to be executed " + "whenever the breakpoint is hit." + " If no breakpoint is specified, adds the " + "commands to the last created breakpoint.", + nullptr), + IOHandlerDelegateMultiline("DONE", + IOHandlerDelegate::Completion::LLDBCommand), + m_options() { + SetHelpLong( + R"( General information about entering breakpoint commands ------------------------------------------------------ -)" "This command will prompt for commands to be executed when the specified \ +)" + "This command will prompt for commands to be executed when the specified \ breakpoint is hit. Each command is typed on its own line following the '> ' \ -prompt until 'DONE' is entered." R"( +prompt until 'DONE' is entered." + R"( -)" "Syntactic errors may not be detected when initially entered, and many \ +)" + "Syntactic errors may not be detected when initially entered, and many \ malformed commands can silently fail when executed. If your breakpoint commands \ -do not appear to be executing, double-check the command syntax." R"( +do not appear to be executing, double-check the command syntax." + R"( -)" "Note: You may enter any debugger command exactly as you would at the debugger \ +)" + "Note: You may enter any debugger command exactly as you would at the debugger \ prompt. There is no limit to the number of commands supplied, but do NOT enter \ -more than one command per line." R"( +more than one command per line." + R"( Special information about PYTHON breakpoint commands ---------------------------------------------------- -)" "You may enter either one or more lines of Python, including function \ +)" + "You may enter either one or more lines of Python, including function \ definitions or calls to functions that will have been imported by the time \ the code executes. Single line breakpoint commands will be interpreted 'as is' \ when the breakpoint is hit. Multiple lines of Python will be wrapped in a \ -generated function, and a call to the function will be attached to the breakpoint." R"( +generated function, and a call to the function will be attached to the breakpoint." + R"( This auto-generated function is passed in three arguments: @@ -78,8 +86,10 @@ This auto-generated function is passed in three arguments: dict: the python session dictionary hit. -)" "When specifying a python function with the --python-function option, you need \ -to supply the function name prepended by the module name:" R"( +)" + "When specifying a python function with the --python-function option, you need \ +to supply the function name prepended by the module name:" + R"( --python-function myutils.breakpoint_callback @@ -88,16 +98,20 @@ The function itself must have the following prototype: def breakpoint_callback(frame, bp_loc, dict): # Your code goes here -)" "The arguments are the same as the arguments passed to generated functions as \ +)" + "The arguments are the same as the arguments passed to generated functions as \ described above. Note that the global variable 'lldb.frame' will NOT be updated when \ this function is called, so be sure to use the 'frame' argument. The 'frame' argument \ can get you to the thread via frame.GetThread(), the thread can get you to the \ process via thread.GetProcess(), and the process can get you back to the target \ -via process.GetTarget()." R"( +via process.GetTarget()." + R"( -)" "Important Note: As Python code gets collected into functions, access to global \ +)" + "Important Note: As Python code gets collected into functions, access to global \ variables requires explicit scoping using the 'global' keyword. Be sure to use correct \ -Python syntax, including indentation, when entering Python breakpoint commands." R"( +Python syntax, including indentation, when entering Python breakpoint commands." + R"( Example Python one-line breakpoint command: @@ -142,729 +156,658 @@ Enter your Python command(s). Type 'DONE' to end. > breakpoint_output (1) > DONE -)" "In this case, since there is a reference to a global variable, \ +)" + "In this case, since there is a reference to a global variable, \ 'bp_count', you will also need to make sure 'bp_count' exists and is \ -initialized:" R"( +initialized:" + R"( (lldb) script >>> bp_count = 0 >>> quit() -)" "Your Python code, however organized, can optionally return a value. \ +)" + "Your Python code, however organized, can optionally return a value. \ If the returned value is False, that tells LLDB not to stop at the breakpoint \ to which the code is associated. Returning anything other than False, or even \ returning None, or even omitting a return statement entirely, will cause \ -LLDB to stop." R"( +LLDB to stop." + R"( -)" "Final Note: A warning that no breakpoint command was generated when there \ -are no syntax errors may indicate that a function was declared but never called." - ); +)" + "Final Note: A warning that no breakpoint command was generated when there \ +are no syntax errors may indicate that a function was declared but never called."); - CommandArgumentEntry arg; - CommandArgumentData bp_id_arg; + CommandArgumentEntry arg; + CommandArgumentData bp_id_arg; - // Define the first (and only) variant of this arg. - bp_id_arg.arg_type = eArgTypeBreakpointID; - bp_id_arg.arg_repetition = eArgRepeatOptional; + // Define the first (and only) variant of this arg. + bp_id_arg.arg_type = eArgTypeBreakpointID; + bp_id_arg.arg_repetition = eArgRepeatOptional; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (bp_id_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(bp_id_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectBreakpointCommandAdd() override = default; + ~CommandObjectBreakpointCommandAdd() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } - void - IOHandlerActivated (IOHandler &io_handler) override - { - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString(g_reader_instructions); - output_sp->Flush(); - } + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString(g_reader_instructions); + output_sp->Flush(); } - - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &line) override - { - io_handler.SetIsDone(true); - - std::vector *bp_options_vec = (std::vector *)io_handler.GetUserData(); - for (BreakpointOptions *bp_options : *bp_options_vec) - { - if (!bp_options) - continue; - - std::unique_ptr data_ap(new BreakpointOptions::CommandData()); - if (data_ap) - { - data_ap->user_source.SplitIntoLines (line.c_str(), line.size()); - BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); - bp_options->SetCallback (BreakpointOptionsCallbackFunction, baton_sp); - } - } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &line) override { + io_handler.SetIsDone(true); + + std::vector *bp_options_vec = + (std::vector *)io_handler.GetUserData(); + for (BreakpointOptions *bp_options : *bp_options_vec) { + if (!bp_options) + continue; + + std::unique_ptr data_ap( + new BreakpointOptions::CommandData()); + if (data_ap) { + data_ap->user_source.SplitIntoLines(line.c_str(), line.size()); + BatonSP baton_sp( + new BreakpointOptions::CommandBaton(data_ap.release())); + bp_options->SetCallback(BreakpointOptionsCallbackFunction, baton_sp); + } } - - void - CollectDataForBreakpointCommandCallback (std::vector &bp_options_vec, - CommandReturnObject &result) - { - m_interpreter.GetLLDBCommandsFromIOHandler ("> ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - &bp_options_vec); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions + } + + void CollectDataForBreakpointCommandCallback( + std::vector &bp_options_vec, + CommandReturnObject &result) { + m_interpreter.GetLLDBCommandsFromIOHandler( + "> ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + &bp_options_vec); // Baton for the "io_handler" that will be passed back + // into our IOHandlerDelegate functions + } + + /// Set a one-liner as the callback for the breakpoint. + void + SetBreakpointCommandCallback(std::vector &bp_options_vec, + const char *oneliner) { + for (auto bp_options : bp_options_vec) { + std::unique_ptr data_ap( + new BreakpointOptions::CommandData()); + + // It's necessary to set both user_source and script_source to the + // oneliner. + // The former is used to generate callback description (as in breakpoint + // command list) + // while the latter is used for Python to interpret during the actual + // callback. + data_ap->user_source.AppendString(oneliner); + data_ap->script_source.assign(oneliner); + data_ap->stop_on_error = m_options.m_stop_on_error; + + BatonSP baton_sp(new BreakpointOptions::CommandBaton(data_ap.release())); + bp_options->SetCallback(BreakpointOptionsCallbackFunction, baton_sp); } - - /// Set a one-liner as the callback for the breakpoint. - void - SetBreakpointCommandCallback (std::vector &bp_options_vec, - const char *oneliner) - { - for (auto bp_options : bp_options_vec) - { - std::unique_ptr data_ap(new BreakpointOptions::CommandData()); - - // It's necessary to set both user_source and script_source to the oneliner. - // The former is used to generate callback description (as in breakpoint command list) - // while the latter is used for Python to interpret during the actual callback. - data_ap->user_source.AppendString (oneliner); - data_ap->script_source.assign (oneliner); - data_ap->stop_on_error = m_options.m_stop_on_error; - - BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); - bp_options->SetCallback (BreakpointOptionsCallbackFunction, baton_sp); - } + } + + static bool BreakpointOptionsCallbackFunction( + void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, + lldb::user_id_t break_loc_id) { + bool ret_value = true; + if (baton == nullptr) + return true; + + BreakpointOptions::CommandData *data = + (BreakpointOptions::CommandData *)baton; + StringList &commands = data->user_source; + + if (commands.GetSize() > 0) { + ExecutionContext exe_ctx(context->exe_ctx_ref); + Target *target = exe_ctx.GetTargetPtr(); + if (target) { + CommandReturnObject result; + Debugger &debugger = target->GetDebugger(); + // Rig up the results secondary output stream to the debugger's, so the + // output will come out synchronously + // if the debugger is set up that way. + + StreamSP output_stream(debugger.GetAsyncOutputStream()); + StreamSP error_stream(debugger.GetAsyncErrorStream()); + result.SetImmediateOutputStream(output_stream); + result.SetImmediateErrorStream(error_stream); + + CommandInterpreterRunOptions options; + options.SetStopOnContinue(true); + options.SetStopOnError(data->stop_on_error); + options.SetEchoCommands(true); + options.SetPrintResults(true); + options.SetAddToHistory(false); + + debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx, + options, result); + result.GetImmediateOutputStream()->Flush(); + result.GetImmediateErrorStream()->Flush(); + } } - - static bool - BreakpointOptionsCallbackFunction (void *baton, - StoppointCallbackContext *context, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id) - { - bool ret_value = true; - if (baton == nullptr) - return true; - - BreakpointOptions::CommandData *data = (BreakpointOptions::CommandData *) baton; - StringList &commands = data->user_source; - - if (commands.GetSize() > 0) - { - ExecutionContext exe_ctx (context->exe_ctx_ref); - Target *target = exe_ctx.GetTargetPtr(); - if (target) - { - CommandReturnObject result; - Debugger &debugger = target->GetDebugger(); - // Rig up the results secondary output stream to the debugger's, so the output will come out synchronously - // if the debugger is set up that way. - - StreamSP output_stream (debugger.GetAsyncOutputStream()); - StreamSP error_stream (debugger.GetAsyncErrorStream()); - result.SetImmediateOutputStream (output_stream); - result.SetImmediateErrorStream (error_stream); - - CommandInterpreterRunOptions options; - options.SetStopOnContinue(true); - options.SetStopOnError (data->stop_on_error); - options.SetEchoCommands (true); - options.SetPrintResults (true); - options.SetAddToHistory (false); - - debugger.GetCommandInterpreter().HandleCommands (commands, - &exe_ctx, - options, - result); - result.GetImmediateOutputStream()->Flush(); - result.GetImmediateErrorStream()->Flush(); - } - } - return ret_value; - } - - class CommandOptions : public Options - { - public: - CommandOptions () : - Options (), - m_use_commands (false), - m_use_script_language (false), - m_script_language (eScriptLanguageNone), - m_use_one_liner (false), - m_one_liner(), - m_function_name() - { + return ret_value; + } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_use_commands(false), m_use_script_language(false), + m_script_language(eScriptLanguageNone), m_use_one_liner(false), + m_one_liner(), m_function_name() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'o': + m_use_one_liner = true; + m_one_liner = option_arg; + break; + + case 's': + m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum( + option_arg, g_option_table[option_idx].enum_values, + eScriptLanguageNone, error); + + if (m_script_language == eScriptLanguagePython || + m_script_language == eScriptLanguageDefault) { + m_use_script_language = true; + } else { + m_use_script_language = false; } + break; + + case 'e': { + bool success = false; + m_stop_on_error = Args::StringToBoolean(option_arg, false, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid value for stop-on-error: \"%s\"", option_arg); + } break; + + case 'F': + m_use_one_liner = false; + m_use_script_language = true; + m_function_name.assign(option_arg); + break; + + case 'D': + m_use_dummy = true; + break; + + default: + break; + } + return error; + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'o': - m_use_one_liner = true; - m_one_liner = option_arg; - break; - - case 's': - m_script_language = (lldb::ScriptLanguage) Args::StringToOptionEnum (option_arg, - g_option_table[option_idx].enum_values, - eScriptLanguageNone, - error); - - if (m_script_language == eScriptLanguagePython || m_script_language == eScriptLanguageDefault) - { - m_use_script_language = true; - } - else - { - m_use_script_language = false; - } - break; - - case 'e': - { - bool success = false; - m_stop_on_error = Args::StringToBoolean(option_arg, false, &success); - if (!success) - error.SetErrorStringWithFormat("invalid value for stop-on-error: \"%s\"", option_arg); - } - break; - - case 'F': - m_use_one_liner = false; - m_use_script_language = true; - m_function_name.assign(option_arg); - break; - - case 'D': - m_use_dummy = true; - break; - - default: - break; - } - return error; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_use_commands = true; + m_use_script_language = false; + m_script_language = eScriptLanguageNone; - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_use_commands = true; - m_use_script_language = false; - m_script_language = eScriptLanguageNone; - - m_use_one_liner = false; - m_stop_on_error = true; - m_one_liner.clear(); - m_function_name.clear(); - m_use_dummy = false; - } + m_use_one_liner = false; + m_stop_on_error = true; + m_one_liner.clear(); + m_function_name.clear(); + m_use_dummy = false; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - bool m_use_commands; - bool m_use_script_language; - lldb::ScriptLanguage m_script_language; + bool m_use_commands; + bool m_use_script_language; + lldb::ScriptLanguage m_script_language; - // Instance variables to hold the values for one_liner options. - bool m_use_one_liner; - std::string m_one_liner; - bool m_stop_on_error; - std::string m_function_name; - bool m_use_dummy; - }; + // Instance variables to hold the values for one_liner options. + bool m_use_one_liner; + std::string m_one_liner; + bool m_stop_on_error; + std::string m_function_name; + bool m_use_dummy; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no breakpoints to which to add commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "breakpoints to which to add commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + const BreakpointList &breakpoints = target->GetBreakpointList(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist to have commands added"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist to have commands added"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (!m_options.m_use_script_language && !m_options.m_function_name.empty()) - { - result.AppendError ("need to enable scripting to have a function run as a breakpoint command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - m_bp_options_vec.clear(); - - if (result.Succeeded()) - { - const size_t count = valid_bp_ids.GetSize(); - - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *bp = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - BreakpointOptions *bp_options = nullptr; - if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) - { - // This breakpoint does not have an associated location. - bp_options = bp->GetOptions(); - } - else - { - BreakpointLocationSP bp_loc_sp(bp->FindLocationByID (cur_bp_id.GetLocationID())); - // This breakpoint does have an associated location. - // Get its breakpoint options. - if (bp_loc_sp) - bp_options = bp_loc_sp->GetLocationOptions(); - } - if (bp_options) - m_bp_options_vec.push_back (bp_options); - } - } + if (!m_options.m_use_script_language && + !m_options.m_function_name.empty()) { + result.AppendError("need to enable scripting to have a function run as a " + "breakpoint command"); + result.SetStatus(eReturnStatusFailed); + return false; + } - // If we are using script language, get the script interpreter - // in order to set or collect command callback. Otherwise, call - // the methods associated with this object. - if (m_options.m_use_script_language) - { - ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter(); - // Special handling for one-liner specified inline. - if (m_options.m_use_one_liner) - { - script_interp->SetBreakpointCommandCallback (m_bp_options_vec, - m_options.m_one_liner.c_str()); - } - else if (!m_options.m_function_name.empty()) - { - script_interp->SetBreakpointCommandCallbackFunction (m_bp_options_vec, - m_options.m_function_name.c_str()); - } - else - { - script_interp->CollectDataForBreakpointCommandCallback (m_bp_options_vec, - result); - } - } - else - { - // Special handling for one-liner specified inline. - if (m_options.m_use_one_liner) - SetBreakpointCommandCallback (m_bp_options_vec, - m_options.m_one_liner.c_str()); - else - CollectDataForBreakpointCommandCallback (m_bp_options_vec, - result); - } + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + m_bp_options_vec.clear(); + + if (result.Succeeded()) { + const size_t count = valid_bp_ids.GetSize(); + + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *bp = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + BreakpointOptions *bp_options = nullptr; + if (cur_bp_id.GetLocationID() == LLDB_INVALID_BREAK_ID) { + // This breakpoint does not have an associated location. + bp_options = bp->GetOptions(); + } else { + BreakpointLocationSP bp_loc_sp( + bp->FindLocationByID(cur_bp_id.GetLocationID())); + // This breakpoint does have an associated location. + // Get its breakpoint options. + if (bp_loc_sp) + bp_options = bp_loc_sp->GetLocationOptions(); + } + if (bp_options) + m_bp_options_vec.push_back(bp_options); } - - return result.Succeeded(); + } + + // If we are using script language, get the script interpreter + // in order to set or collect command callback. Otherwise, call + // the methods associated with this object. + if (m_options.m_use_script_language) { + ScriptInterpreter *script_interp = m_interpreter.GetScriptInterpreter(); + // Special handling for one-liner specified inline. + if (m_options.m_use_one_liner) { + script_interp->SetBreakpointCommandCallback( + m_bp_options_vec, m_options.m_one_liner.c_str()); + } else if (!m_options.m_function_name.empty()) { + script_interp->SetBreakpointCommandCallbackFunction( + m_bp_options_vec, m_options.m_function_name.c_str()); + } else { + script_interp->CollectDataForBreakpointCommandCallback( + m_bp_options_vec, result); + } + } else { + // Special handling for one-liner specified inline. + if (m_options.m_use_one_liner) + SetBreakpointCommandCallback(m_bp_options_vec, + m_options.m_one_liner.c_str()); + else + CollectDataForBreakpointCommandCallback(m_bp_options_vec, result); + } } + return result.Succeeded(); + } + private: - CommandOptions m_options; - std::vector m_bp_options_vec; // This stores the breakpoint options that we are currently - // collecting commands for. In the CollectData... calls we need - // to hand this off to the IOHandler, which may run asynchronously. - // So we have to have some way to keep it alive, and not leak it. - // Making it an ivar of the command object, which never goes away - // achieves this. Note that if we were able to run - // the same command concurrently in one interpreter we'd have to - // make this "per invocation". But there are many more reasons - // why it is not in general safe to do that in lldb at present, - // so it isn't worthwhile to come up with a more complex mechanism - // to address this particular weakness right now. - static const char *g_reader_instructions; + CommandOptions m_options; + std::vector m_bp_options_vec; // This stores the + // breakpoint options that + // we are currently + // collecting commands for. In the CollectData... calls we need + // to hand this off to the IOHandler, which may run asynchronously. + // So we have to have some way to keep it alive, and not leak it. + // Making it an ivar of the command object, which never goes away + // achieves this. Note that if we were able to run + // the same command concurrently in one interpreter we'd have to + // make this "per invocation". But there are many more reasons + // why it is not in general safe to do that in lldb at present, + // so it isn't worthwhile to come up with a more complex mechanism + // to address this particular weakness right now. + static const char *g_reader_instructions; }; -const char * -CommandObjectBreakpointCommandAdd::g_reader_instructions = "Enter your debugger command(s). Type 'DONE' to end.\n"; +const char *CommandObjectBreakpointCommandAdd::g_reader_instructions = + "Enter your debugger command(s). Type 'DONE' to end.\n"; -// FIXME: "script-type" needs to have its contents determined dynamically, so somebody can add a new scripting -// language to lldb and have it pickable here without having to change this enumeration by hand and rebuild lldb proper. +// FIXME: "script-type" needs to have its contents determined dynamically, so +// somebody can add a new scripting +// language to lldb and have it pickable here without having to change this +// enumeration by hand and rebuild lldb proper. -static OptionEnumValueElement -g_script_option_enumeration[4] = -{ - { eScriptLanguageNone, "command", "Commands are in the lldb command interpreter language"}, - { eScriptLanguagePython, "python", "Commands are in the Python language."}, - { eSortOrderByName, "default-script", "Commands are in the default scripting language."}, - { 0, nullptr, nullptr } -}; +static OptionEnumValueElement g_script_option_enumeration[4] = { + {eScriptLanguageNone, "command", + "Commands are in the lldb command interpreter language"}, + {eScriptLanguagePython, "python", "Commands are in the Python language."}, + {eSortOrderByName, "default-script", + "Commands are in the default scripting language."}, + {0, nullptr, nullptr}}; OptionDefinition -CommandObjectBreakpointCommandAdd::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectBreakpointCommandAdd::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." }, {LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Specify whether breakpoint command execution should terminate on error." }, {LLDB_OPT_SET_ALL, false, "script-type", 's', OptionParser::eRequiredArgument, nullptr, g_script_option_enumeration, 0, eArgTypeNone, "Specify the language for the commands - if none is specified, the lldb command interpreter will be used."}, {LLDB_OPT_SET_2, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonFunction, "Give the name of a Python function to run as command for this breakpoint. Be sure to give a module name if appropriate."}, {LLDB_OPT_SET_ALL, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Sets Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectBreakpointCommandDelete //------------------------------------------------------------------------- -class CommandObjectBreakpointCommandDelete : public CommandObjectParsed -{ +class CommandObjectBreakpointCommandDelete : public CommandObjectParsed { public: - CommandObjectBreakpointCommandDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "delete", + CommandObjectBreakpointCommandDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "delete", "Delete the set of commands from a breakpoint.", nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData bp_id_arg; + m_options() { + CommandArgumentEntry arg; + CommandArgumentData bp_id_arg; - // Define the first (and only) variant of this arg. - bp_id_arg.arg_type = eArgTypeBreakpointID; - bp_id_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + bp_id_arg.arg_type = eArgTypeBreakpointID; + bp_id_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (bp_id_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(bp_id_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectBreakpointCommandDelete() override = default; + ~CommandObjectBreakpointCommandDelete() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_use_dummy(false) - { - } + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_use_dummy(false) {} - ~CommandOptions() override = default; + ~CommandOptions() override = default; - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - switch (short_option) - { - case 'D': - m_use_dummy = true; - break; + switch (short_option) { + case 'D': + m_use_dummy = true; + break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } - return error; - } + return error; + } - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_use_dummy = false; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_use_dummy = false; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. - bool m_use_dummy; - }; + // Instance variables to hold the values for command options. + bool m_use_dummy; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no breakpoints from which to delete commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(m_options.m_use_dummy); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "breakpoints from which to delete commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + const BreakpointList &breakpoints = target->GetBreakpointList(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist to have commands deleted"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist to have commands deleted"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - result.AppendError ("No breakpoint specified from which to delete the commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (command.GetArgumentCount() == 0) { + result.AppendError( + "No breakpoint specified from which to delete the commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *bp = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - BreakpointLocationSP bp_loc_sp (bp->FindLocationByID (cur_bp_id.GetLocationID())); - if (bp_loc_sp) - bp_loc_sp->ClearCallback(); - else - { - result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n", - cur_bp_id.GetBreakpointID(), - cur_bp_id.GetLocationID()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - bp->ClearCallback(); - } - } + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *bp = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + BreakpointLocationSP bp_loc_sp( + bp->FindLocationByID(cur_bp_id.GetLocationID())); + if (bp_loc_sp) + bp_loc_sp->ClearCallback(); + else { + result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n", + cur_bp_id.GetBreakpointID(), + cur_bp_id.GetLocationID()); + result.SetStatus(eReturnStatusFailed); + return false; } + } else { + bp->ClearCallback(); + } } - return result.Succeeded(); + } } + return result.Succeeded(); + } private: - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectBreakpointCommandDelete::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectBreakpointCommandDelete::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "dummy-breakpoints", 'D', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Delete commands from Dummy breakpoints - i.e. breakpoints set before a file is provided, which prime new targets."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectBreakpointCommandList //------------------------------------------------------------------------- -class CommandObjectBreakpointCommandList : public CommandObjectParsed -{ +class CommandObjectBreakpointCommandList : public CommandObjectParsed { public: - CommandObjectBreakpointCommandList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "list", - "List the script or set of commands to be executed when the breakpoint is hit.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData bp_id_arg; - - // Define the first (and only) variant of this arg. - bp_id_arg.arg_type = eArgTypeBreakpointID; - bp_id_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (bp_id_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectBreakpointCommandList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "list", "List the script or set of " + "commands to be executed when " + "the breakpoint is hit.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData bp_id_arg; + + // Define the first (and only) variant of this arg. + bp_id_arg.arg_type = eArgTypeBreakpointID; + bp_id_arg.arg_repetition = eArgRepeatPlain; - ~CommandObjectBreakpointCommandList() override = default; + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(bp_id_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectBreakpointCommandList() override = default; protected: - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no breakpoints for which to list commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "breakpoints for which to list commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const BreakpointList &breakpoints = target->GetBreakpointList(); - size_t num_breakpoints = breakpoints.GetSize(); + const BreakpointList &breakpoints = target->GetBreakpointList(); + size_t num_breakpoints = breakpoints.GetSize(); - if (num_breakpoints == 0) - { - result.AppendError ("No breakpoints exist for which to list commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_breakpoints == 0) { + result.AppendError("No breakpoints exist for which to list commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - result.AppendError ("No breakpoint specified for which to list the commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (command.GetArgumentCount() == 0) { + result.AppendError( + "No breakpoint specified for which to list the commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - BreakpointIDList valid_bp_ids; - CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs (command, target, result, &valid_bp_ids); - - if (result.Succeeded()) - { - const size_t count = valid_bp_ids.GetSize(); - for (size_t i = 0; i < count; ++i) - { - BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex (i); - if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) - { - Breakpoint *bp = target->GetBreakpointByID (cur_bp_id.GetBreakpointID()).get(); - - if (bp) - { - const BreakpointOptions *bp_options = nullptr; - if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) - { - BreakpointLocationSP bp_loc_sp(bp->FindLocationByID (cur_bp_id.GetLocationID())); - if (bp_loc_sp) - bp_options = bp_loc_sp->GetOptionsNoCreate(); - else - { - result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n", - cur_bp_id.GetBreakpointID(), - cur_bp_id.GetLocationID()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - bp_options = bp->GetOptions(); - } - - if (bp_options) - { - StreamString id_str; - BreakpointID::GetCanonicalReference (&id_str, - cur_bp_id.GetBreakpointID(), - cur_bp_id.GetLocationID()); - const Baton *baton = bp_options->GetBaton(); - if (baton) - { - result.GetOutputStream().Printf ("Breakpoint %s:\n", id_str.GetData()); - result.GetOutputStream().IndentMore (); - baton->GetDescription(&result.GetOutputStream(), eDescriptionLevelFull); - result.GetOutputStream().IndentLess (); - } - else - { - result.AppendMessageWithFormat ("Breakpoint %s does not have an associated command.\n", - id_str.GetData()); - } - } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n", cur_bp_id.GetBreakpointID()); - result.SetStatus (eReturnStatusFailed); - } - } + BreakpointIDList valid_bp_ids; + CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs( + command, target, result, &valid_bp_ids); + + if (result.Succeeded()) { + const size_t count = valid_bp_ids.GetSize(); + for (size_t i = 0; i < count; ++i) { + BreakpointID cur_bp_id = valid_bp_ids.GetBreakpointIDAtIndex(i); + if (cur_bp_id.GetBreakpointID() != LLDB_INVALID_BREAK_ID) { + Breakpoint *bp = + target->GetBreakpointByID(cur_bp_id.GetBreakpointID()).get(); + + if (bp) { + const BreakpointOptions *bp_options = nullptr; + if (cur_bp_id.GetLocationID() != LLDB_INVALID_BREAK_ID) { + BreakpointLocationSP bp_loc_sp( + bp->FindLocationByID(cur_bp_id.GetLocationID())); + if (bp_loc_sp) + bp_options = bp_loc_sp->GetOptionsNoCreate(); + else { + result.AppendErrorWithFormat("Invalid breakpoint ID: %u.%u.\n", + cur_bp_id.GetBreakpointID(), + cur_bp_id.GetLocationID()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + bp_options = bp->GetOptions(); } - } - return result.Succeeded(); + if (bp_options) { + StreamString id_str; + BreakpointID::GetCanonicalReference(&id_str, + cur_bp_id.GetBreakpointID(), + cur_bp_id.GetLocationID()); + const Baton *baton = bp_options->GetBaton(); + if (baton) { + result.GetOutputStream().Printf("Breakpoint %s:\n", + id_str.GetData()); + result.GetOutputStream().IndentMore(); + baton->GetDescription(&result.GetOutputStream(), + eDescriptionLevelFull); + result.GetOutputStream().IndentLess(); + } else { + result.AppendMessageWithFormat( + "Breakpoint %s does not have an associated command.\n", + id_str.GetData()); + } + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Invalid breakpoint ID: %u.\n", + cur_bp_id.GetBreakpointID()); + result.SetStatus(eReturnStatusFailed); + } + } + } } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectBreakpointCommand //------------------------------------------------------------------------- -CommandObjectBreakpointCommand::CommandObjectBreakpointCommand(CommandInterpreter &interpreter) +CommandObjectBreakpointCommand::CommandObjectBreakpointCommand( + CommandInterpreter &interpreter) : CommandObjectMultiword( - interpreter, "command", - "Commands for adding, removing and listing LLDB commands executed when a breakpoint is hit.", - "command [] ") -{ - CommandObjectSP add_command_object (new CommandObjectBreakpointCommandAdd (interpreter)); - CommandObjectSP delete_command_object (new CommandObjectBreakpointCommandDelete (interpreter)); - CommandObjectSP list_command_object (new CommandObjectBreakpointCommandList (interpreter)); - - add_command_object->SetCommandName ("breakpoint command add"); - delete_command_object->SetCommandName ("breakpoint command delete"); - list_command_object->SetCommandName ("breakpoint command list"); - - LoadSubCommand ("add", add_command_object); - LoadSubCommand ("delete", delete_command_object); - LoadSubCommand ("list", list_command_object); + interpreter, "command", "Commands for adding, removing and listing " + "LLDB commands executed when a breakpoint is " + "hit.", + "command [] ") { + CommandObjectSP add_command_object( + new CommandObjectBreakpointCommandAdd(interpreter)); + CommandObjectSP delete_command_object( + new CommandObjectBreakpointCommandDelete(interpreter)); + CommandObjectSP list_command_object( + new CommandObjectBreakpointCommandList(interpreter)); + + add_command_object->SetCommandName("breakpoint command add"); + delete_command_object->SetCommandName("breakpoint command delete"); + list_command_object->SetCommandName("breakpoint command list"); + + LoadSubCommand("add", add_command_object); + LoadSubCommand("delete", delete_command_object); + LoadSubCommand("list", list_command_object); } CommandObjectBreakpointCommand::~CommandObjectBreakpointCommand() = default; diff --git a/lldb/source/Commands/CommandObjectBreakpointCommand.h b/lldb/source/Commands/CommandObjectBreakpointCommand.h index 94afc785c57..048cc5e07c1 100644 --- a/lldb/source/Commands/CommandObjectBreakpointCommand.h +++ b/lldb/source/Commands/CommandObjectBreakpointCommand.h @@ -16,11 +16,11 @@ // Other libraries and framework includes // Project includes -#include "lldb/lldb-types.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/CommandObject.h" -#include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" +#include "lldb/lldb-types.h" namespace lldb_private { @@ -28,12 +28,11 @@ namespace lldb_private { // CommandObjectMultiwordBreakpoint //------------------------------------------------------------------------- -class CommandObjectBreakpointCommand : public CommandObjectMultiword -{ +class CommandObjectBreakpointCommand : public CommandObjectMultiword { public: - CommandObjectBreakpointCommand (CommandInterpreter &interpreter); + CommandObjectBreakpointCommand(CommandInterpreter &interpreter); - ~CommandObjectBreakpointCommand() override; + ~CommandObjectBreakpointCommand() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectBugreport.cpp b/lldb/source/Commands/CommandObjectBugreport.cpp index 7dd19792ba3..04050e3a669 100644 --- a/lldb/source/Commands/CommandObjectBugreport.cpp +++ b/lldb/source/Commands/CommandObjectBugreport.cpp @@ -28,100 +28,87 @@ using namespace lldb_private; // "bugreport unwind" //------------------------------------------------------------------------- -class CommandObjectBugreportUnwind : public CommandObjectParsed -{ +class CommandObjectBugreportUnwind : public CommandObjectParsed { public: - CommandObjectBugreportUnwind(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "bugreport unwind", - "Create a bugreport for a bug in the stack unwinding code.", - nullptr), - m_option_group(), - m_outfile_options() - { - m_option_group.Append (&m_outfile_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); - m_option_group.Finalize(); - } + CommandObjectBugreportUnwind(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "bugreport unwind", + "Create a bugreport for a bug in the stack unwinding code.", + nullptr), + m_option_group(), m_outfile_options() { + m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); + m_option_group.Finalize(); + } - ~CommandObjectBugreportUnwind() override - { - } + ~CommandObjectBugreportUnwind() override {} - Options * - GetOptions() override - { - return &m_option_group; - } + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute(Args& command, CommandReturnObject &result) override - { - StringList commands; - commands.AppendString("thread backtrace"); - - Thread *thread = m_exe_ctx.GetThreadPtr(); - if (thread) - { - char command_buffer[256]; - - uint32_t frame_count = thread->GetStackFrameCount(); - for (uint32_t i = 0; i < frame_count; ++i) - { - StackFrameSP frame = thread->GetStackFrameAtIndex(i); - lldb::addr_t pc = frame->GetStackID().GetPC(); - - snprintf(command_buffer, sizeof(command_buffer), "disassemble --bytes --address 0x%" PRIx64, pc); - commands.AppendString(command_buffer); - - snprintf(command_buffer, sizeof(command_buffer), "image show-unwind --address 0x%" PRIx64, pc); - commands.AppendString(command_buffer); - } - } - - const FileSpec &outfile_spec = m_outfile_options.GetFile().GetCurrentValue(); - if (outfile_spec) - { - char path[PATH_MAX]; - outfile_spec.GetPath (path, sizeof(path)); - - uint32_t open_options = File::eOpenOptionWrite | - File::eOpenOptionCanCreate | - File::eOpenOptionAppend | - File::eOpenOptionCloseOnExec; - - const bool append = m_outfile_options.GetAppend().GetCurrentValue(); - if (!append) - open_options |= File::eOpenOptionTruncate; - - StreamFileSP outfile_stream = std::make_shared(); - Error error = outfile_stream->GetFile().Open(path, open_options); - if (error.Fail()) - { - result.AppendErrorWithFormat("Failed to open file '%s' for %s: %s\n", - path, - append ? "append" : "write", - error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - result.SetImmediateOutputStream(outfile_stream); - } - - CommandInterpreterRunOptions options; - options.SetStopOnError(false); - options.SetEchoCommands(true); - options.SetPrintResults(true); - options.SetAddToHistory(false); - m_interpreter.HandleCommands(commands, &m_exe_ctx, options, result); - - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + StringList commands; + commands.AppendString("thread backtrace"); + + Thread *thread = m_exe_ctx.GetThreadPtr(); + if (thread) { + char command_buffer[256]; + + uint32_t frame_count = thread->GetStackFrameCount(); + for (uint32_t i = 0; i < frame_count; ++i) { + StackFrameSP frame = thread->GetStackFrameAtIndex(i); + lldb::addr_t pc = frame->GetStackID().GetPC(); + + snprintf(command_buffer, sizeof(command_buffer), + "disassemble --bytes --address 0x%" PRIx64, pc); + commands.AppendString(command_buffer); + + snprintf(command_buffer, sizeof(command_buffer), + "image show-unwind --address 0x%" PRIx64, pc); + commands.AppendString(command_buffer); + } + } + + const FileSpec &outfile_spec = + m_outfile_options.GetFile().GetCurrentValue(); + if (outfile_spec) { + char path[PATH_MAX]; + outfile_spec.GetPath(path, sizeof(path)); + + uint32_t open_options = + File::eOpenOptionWrite | File::eOpenOptionCanCreate | + File::eOpenOptionAppend | File::eOpenOptionCloseOnExec; + + const bool append = m_outfile_options.GetAppend().GetCurrentValue(); + if (!append) + open_options |= File::eOpenOptionTruncate; + + StreamFileSP outfile_stream = std::make_shared(); + Error error = outfile_stream->GetFile().Open(path, open_options); + if (error.Fail()) { + result.AppendErrorWithFormat("Failed to open file '%s' for %s: %s\n", + path, append ? "append" : "write", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + result.SetImmediateOutputStream(outfile_stream); } + CommandInterpreterRunOptions options; + options.SetStopOnError(false); + options.SetEchoCommands(true); + options.SetPrintResults(true); + options.SetAddToHistory(false); + m_interpreter.HandleCommands(commands, &m_exe_ctx, options, result); + + return result.Succeeded(); + } + private: - OptionGroupOptions m_option_group; - OptionGroupOutputFile m_outfile_options; + OptionGroupOptions m_option_group; + OptionGroupOutputFile m_outfile_options; }; #pragma mark CommandObjectMultiwordBugreport @@ -130,14 +117,15 @@ private: // CommandObjectMultiwordBugreport //------------------------------------------------------------------------- -CommandObjectMultiwordBugreport::CommandObjectMultiwordBugreport(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "bugreport", "Commands for creating domain-specific bug reports.", - "bugreport []") -{ +CommandObjectMultiwordBugreport::CommandObjectMultiwordBugreport( + CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "bugreport", + "Commands for creating domain-specific bug reports.", + "bugreport []") { - LoadSubCommand("unwind", CommandObjectSP(new CommandObjectBugreportUnwind(interpreter))); + LoadSubCommand( + "unwind", CommandObjectSP(new CommandObjectBugreportUnwind(interpreter))); } -CommandObjectMultiwordBugreport::~CommandObjectMultiwordBugreport () -{ -} +CommandObjectMultiwordBugreport::~CommandObjectMultiwordBugreport() {} diff --git a/lldb/source/Commands/CommandObjectBugreport.h b/lldb/source/Commands/CommandObjectBugreport.h index 3adde51e027..281ea2dd203 100644 --- a/lldb/source/Commands/CommandObjectBugreport.h +++ b/lldb/source/Commands/CommandObjectBugreport.h @@ -22,12 +22,11 @@ namespace lldb_private { // CommandObjectMultiwordBugreport //------------------------------------------------------------------------- -class CommandObjectMultiwordBugreport : public CommandObjectMultiword -{ +class CommandObjectMultiwordBugreport : public CommandObjectMultiword { public: - CommandObjectMultiwordBugreport(CommandInterpreter &interpreter); + CommandObjectMultiwordBugreport(CommandInterpreter &interpreter); - ~CommandObjectMultiwordBugreport() override; + ~CommandObjectMultiwordBugreport() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectCommands.cpp b/lldb/source/Commands/CommandObjectCommands.cpp index 2ffee58fbc2..f4f3afb32ba 100644 --- a/lldb/source/Commands/CommandObjectCommands.cpp +++ b/lldb/source/Commands/CommandObjectCommands.cpp @@ -36,392 +36,318 @@ using namespace lldb_private; // CommandObjectCommandsSource //------------------------------------------------------------------------- -class CommandObjectCommandsHistory : public CommandObjectParsed -{ +class CommandObjectCommandsHistory : public CommandObjectParsed { public: - CommandObjectCommandsHistory(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command history", + CommandObjectCommandsHistory(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command history", "Dump the history of commands in this session.", nullptr), - m_options() - { - } + m_options() {} - ~CommandObjectCommandsHistory() override = default; + ~CommandObjectCommandsHistory() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_start_idx(0), - m_stop_idx(0), - m_count(0), - m_clear(false) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'c': - error = m_count.SetValueFromString(option_arg,eVarSetOperationAssign); - break; - case 's': - if (option_arg && strcmp("end", option_arg) == 0) - { - m_start_idx.SetCurrentValue(UINT64_MAX); - m_start_idx.SetOptionWasSet(); - } - else - error = m_start_idx.SetValueFromString(option_arg,eVarSetOperationAssign); - break; - case 'e': - error = m_stop_idx.SetValueFromString(option_arg,eVarSetOperationAssign); - break; - case 'C': - m_clear.SetCurrentValue(true); - m_clear.SetOptionWasSet(); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_start_idx.Clear(); - m_stop_idx.Clear(); - m_count.Clear(); - m_clear.Clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_start_idx(0), m_stop_idx(0), m_count(0), m_clear(false) { + } - static OptionDefinition g_option_table[]; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'c': + error = m_count.SetValueFromString(option_arg, eVarSetOperationAssign); + break; + case 's': + if (option_arg && strcmp("end", option_arg) == 0) { + m_start_idx.SetCurrentValue(UINT64_MAX); + m_start_idx.SetOptionWasSet(); + } else + error = m_start_idx.SetValueFromString(option_arg, + eVarSetOperationAssign); + break; + case 'e': + error = + m_stop_idx.SetValueFromString(option_arg, eVarSetOperationAssign); + break; + case 'C': + m_clear.SetCurrentValue(true); + m_clear.SetOptionWasSet(); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } - // Instance variables to hold the values for command options. + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_start_idx.Clear(); + m_stop_idx.Clear(); + m_count.Clear(); + m_clear.Clear(); + } - OptionValueUInt64 m_start_idx; - OptionValueUInt64 m_stop_idx; - OptionValueUInt64 m_count; - OptionValueBoolean m_clear; - }; - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (m_options.m_clear.GetCurrentValue() && m_options.m_clear.OptionWasSet()) - { - m_interpreter.GetCommandHistory().Clear(); - result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); - } - else - { - if (m_options.m_start_idx.OptionWasSet() && m_options.m_stop_idx.OptionWasSet() && m_options.m_count.OptionWasSet()) - { - result.AppendError("--count, --start-index and --end-index cannot be all specified in the same invocation"); - result.SetStatus(lldb::eReturnStatusFailed); + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + OptionValueUInt64 m_start_idx; + OptionValueUInt64 m_stop_idx; + OptionValueUInt64 m_count; + OptionValueBoolean m_clear; + }; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (m_options.m_clear.GetCurrentValue() && + m_options.m_clear.OptionWasSet()) { + m_interpreter.GetCommandHistory().Clear(); + result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); + } else { + if (m_options.m_start_idx.OptionWasSet() && + m_options.m_stop_idx.OptionWasSet() && + m_options.m_count.OptionWasSet()) { + result.AppendError("--count, --start-index and --end-index cannot be " + "all specified in the same invocation"); + result.SetStatus(lldb::eReturnStatusFailed); + } else { + std::pair start_idx( + m_options.m_start_idx.OptionWasSet(), + m_options.m_start_idx.GetCurrentValue()); + std::pair stop_idx( + m_options.m_stop_idx.OptionWasSet(), + m_options.m_stop_idx.GetCurrentValue()); + std::pair count(m_options.m_count.OptionWasSet(), + m_options.m_count.GetCurrentValue()); + + const CommandHistory &history(m_interpreter.GetCommandHistory()); + + if (start_idx.first && start_idx.second == UINT64_MAX) { + if (count.first) { + start_idx.second = history.GetSize() - count.second; + stop_idx.second = history.GetSize() - 1; + } else if (stop_idx.first) { + start_idx.second = stop_idx.second; + stop_idx.second = history.GetSize() - 1; + } else { + start_idx.second = 0; + stop_idx.second = history.GetSize() - 1; + } + } else { + if (!start_idx.first && !stop_idx.first && !count.first) { + start_idx.second = 0; + stop_idx.second = history.GetSize() - 1; + } else if (start_idx.first) { + if (count.first) { + stop_idx.second = start_idx.second + count.second - 1; + } else if (!stop_idx.first) { + stop_idx.second = history.GetSize() - 1; } - else - { - std::pair start_idx(m_options.m_start_idx.OptionWasSet(),m_options.m_start_idx.GetCurrentValue()); - std::pair stop_idx(m_options.m_stop_idx.OptionWasSet(),m_options.m_stop_idx.GetCurrentValue()); - std::pair count(m_options.m_count.OptionWasSet(),m_options.m_count.GetCurrentValue()); - - const CommandHistory& history(m_interpreter.GetCommandHistory()); - - if (start_idx.first && start_idx.second == UINT64_MAX) - { - if (count.first) - { - start_idx.second = history.GetSize() - count.second; - stop_idx.second = history.GetSize() - 1; - } - else if (stop_idx.first) - { - start_idx.second = stop_idx.second; - stop_idx.second = history.GetSize() - 1; - } - else - { - start_idx.second = 0; - stop_idx.second = history.GetSize() - 1; - } - } - else - { - if (!start_idx.first && !stop_idx.first && !count.first) - { - start_idx.second = 0; - stop_idx.second = history.GetSize() - 1; - } - else if (start_idx.first) - { - if (count.first) - { - stop_idx.second = start_idx.second + count.second - 1; - } - else if (!stop_idx.first) - { - stop_idx.second = history.GetSize() - 1; - } - } - else if (stop_idx.first) - { - if (count.first) - { - if (stop_idx.second >= count.second) - start_idx.second = stop_idx.second - count.second + 1; - else - start_idx.second = 0; - } - } - else /* if (count.first) */ - { - start_idx.second = 0; - stop_idx.second = count.second - 1; - } - } - history.Dump(result.GetOutputStream(), start_idx.second, stop_idx.second); + } else if (stop_idx.first) { + if (count.first) { + if (stop_idx.second >= count.second) + start_idx.second = stop_idx.second - count.second + 1; + else + start_idx.second = 0; } - } - return result.Succeeded(); - + } else /* if (count.first) */ + { + start_idx.second = 0; + stop_idx.second = count.second - 1; + } + } + history.Dump(result.GetOutputStream(), start_idx.second, + stop_idx.second); + } } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectCommandsHistory::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectCommandsHistory::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "How many history commands to print."}, {LLDB_OPT_SET_1, false, "start-index", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to start printing history commands (or end to mean tail mode)."}, {LLDB_OPT_SET_1, false, "end-index", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands."}, {LLDB_OPT_SET_2, false, "clear", 'C', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Clears the current command history."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectCommandsSource //------------------------------------------------------------------------- -class CommandObjectCommandsSource : public CommandObjectParsed -{ +class CommandObjectCommandsSource : public CommandObjectParsed { public: - CommandObjectCommandsSource(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "command source", "Read and execute LLDB commands from the file .", - nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData file_arg; - - // Define the first (and only) variant of this arg. - file_arg.arg_type = eArgTypeFilename; - file_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (file_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectCommandsSource() override = default; + CommandObjectCommandsSource(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "command source", + "Read and execute LLDB commands from the file .", + nullptr), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData file_arg; + + // Define the first (and only) variant of this arg. + file_arg.arg_type = eArgTypeFilename; + file_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(file_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectCommandsSource() override = default; + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + return ""; + } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } + + Options *GetOptions() override { return &m_options; } - const char* - GetRepeatCommand (Args ¤t_command_args, uint32_t index) override - { - return ""; - } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); +protected: + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_stop_on_error(true), m_silent_run(false), + m_stop_on_continue(true) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'e': + error = m_stop_on_error.SetValueFromString(option_arg); + break; + + case 'c': + error = m_stop_on_continue.SetValueFromString(option_arg); + break; + + case 's': + error = m_silent_run.SetValueFromString(option_arg); + break; + + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_stop_on_error.Clear(); + m_silent_run.Clear(); + m_stop_on_continue.Clear(); } -protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_stop_on_error (true), - m_silent_run (false), - m_stop_on_continue (true) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'e': - error = m_stop_on_error.SetValueFromString(option_arg); - break; - - case 'c': - error = m_stop_on_continue.SetValueFromString(option_arg); - break; - - case 's': - error = m_silent_run.SetValueFromString(option_arg); - break; - - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_stop_on_error.Clear(); - m_silent_run.Clear(); - m_stop_on_continue.Clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - OptionValueBoolean m_stop_on_error; - OptionValueBoolean m_silent_run; - OptionValueBoolean m_stop_on_continue; - }; - - bool - DoExecute(Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - if (argc == 1) - { - const char *filename = command.GetArgumentAtIndex(0); - - FileSpec cmd_file (filename, true); - ExecutionContext *exe_ctx = nullptr; // Just use the default context. - - // If any options were set, then use them - if (m_options.m_stop_on_error.OptionWasSet() || - m_options.m_silent_run.OptionWasSet() || - m_options.m_stop_on_continue.OptionWasSet()) - { - // Use user set settings - CommandInterpreterRunOptions options; - options.SetStopOnContinue(m_options.m_stop_on_continue.GetCurrentValue()); - options.SetStopOnError (m_options.m_stop_on_error.GetCurrentValue()); - options.SetEchoCommands (!m_options.m_silent_run.GetCurrentValue()); - options.SetPrintResults (!m_options.m_silent_run.GetCurrentValue()); - - m_interpreter.HandleCommandsFromFile (cmd_file, - exe_ctx, - options, - result); - } - else - { - // No options were set, inherit any settings from nested "command source" commands, - // or set to sane default settings... - CommandInterpreterRunOptions options; - m_interpreter.HandleCommandsFromFile (cmd_file, - exe_ctx, - options, - result); - } - } - else - { - result.AppendErrorWithFormat("'%s' takes exactly one executable filename argument.\n", GetCommandName()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + OptionValueBoolean m_stop_on_error; + OptionValueBoolean m_silent_run; + OptionValueBoolean m_stop_on_continue; + }; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + if (argc == 1) { + const char *filename = command.GetArgumentAtIndex(0); + + FileSpec cmd_file(filename, true); + ExecutionContext *exe_ctx = nullptr; // Just use the default context. + + // If any options were set, then use them + if (m_options.m_stop_on_error.OptionWasSet() || + m_options.m_silent_run.OptionWasSet() || + m_options.m_stop_on_continue.OptionWasSet()) { + // Use user set settings + CommandInterpreterRunOptions options; + options.SetStopOnContinue( + m_options.m_stop_on_continue.GetCurrentValue()); + options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue()); + options.SetEchoCommands(!m_options.m_silent_run.GetCurrentValue()); + options.SetPrintResults(!m_options.m_silent_run.GetCurrentValue()); + + m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, + result); + } else { + // No options were set, inherit any settings from nested "command + // source" commands, + // or set to sane default settings... + CommandInterpreterRunOptions options; + m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, + result); + } + } else { + result.AppendErrorWithFormat( + "'%s' takes exactly one executable filename argument.\n", + GetCommandName()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectCommandsSource::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectCommandsSource::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on error."}, {LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on continue."}, {LLDB_OPT_SET_ALL, false, "silent-run", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true don't echo commands while executing."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectCommandsAlias @@ -429,102 +355,81 @@ CommandObjectCommandsSource::CommandOptions::g_option_table[] = // CommandObjectCommandsAlias //------------------------------------------------------------------------- -static const char *g_python_command_instructions = "Enter your Python command(s). Type 'DONE' to end.\n" - "You must define a Python function with this signature:\n" - "def my_command_impl(debugger, args, result, internal_dict):\n"; +static const char *g_python_command_instructions = + "Enter your Python command(s). Type 'DONE' to end.\n" + "You must define a Python function with this signature:\n" + "def my_command_impl(debugger, args, result, internal_dict):\n"; -class CommandObjectCommandsAlias : public CommandObjectRaw -{ +class CommandObjectCommandsAlias : public CommandObjectRaw { protected: - class CommandOptions : public OptionGroup - { - public: - CommandOptions () : - OptionGroup(), - m_help(), - m_long_help() - {} - - ~CommandOptions() override = default; - - uint32_t - GetNumDefinitions () override - { - return 3; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = g_option_table[option_idx].short_option; - - switch (short_option) - { - case 'h': - m_help.SetCurrentValue(option_value); - m_help.SetOptionWasSet(); - break; - - case 'H': - m_long_help.SetCurrentValue(option_value); - m_long_help.SetOptionWasSet(); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_help.Clear(); - m_long_help.Clear(); - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - OptionValueString m_help; - OptionValueString m_long_help; - }; - - OptionGroupOptions m_option_group; - CommandOptions m_command_options; - -public: - Options * - GetOptions () override - { - return &m_option_group; + class CommandOptions : public OptionGroup { + public: + CommandOptions() : OptionGroup(), m_help(), m_long_help() {} + + ~CommandOptions() override = default; + + uint32_t GetNumDefinitions() override { return 3; } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + + const int short_option = g_option_table[option_idx].short_option; + + switch (short_option) { + case 'h': + m_help.SetCurrentValue(option_value); + m_help.SetOptionWasSet(); + break; + + case 'H': + m_long_help.SetCurrentValue(option_value); + m_long_help.SetOptionWasSet(); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; } - CommandObjectCommandsAlias(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "command alias", "Define a custom command in terms of an existing command.", - nullptr), - m_option_group(), - m_command_options() - { - m_option_group.Append(&m_command_options); - m_option_group.Finalize(); + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_help.Clear(); + m_long_help.Clear(); + } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + OptionValueString m_help; + OptionValueString m_long_help; + }; - SetHelpLong( -"'alias' allows the user to create a short-cut or abbreviation for long \ + OptionGroupOptions m_option_group; + CommandOptions m_command_options; + +public: + Options *GetOptions() override { return &m_option_group; } + + CommandObjectCommandsAlias(CommandInterpreter &interpreter) + : CommandObjectRaw( + interpreter, "command alias", + "Define a custom command in terms of an existing command.", + nullptr), + m_option_group(), m_command_options() { + m_option_group.Append(&m_command_options); + m_option_group.Finalize(); + + SetHelpLong( + "'alias' allows the user to create a short-cut or abbreviation for long \ commands, multi-word commands, and commands that take particular options. \ -Below are some simple examples of how one might use the 'alias' command:" R"( +Below are some simple examples of how one might use the 'alias' command:" + R"( (lldb) command alias sc script @@ -532,22 +437,27 @@ Below are some simple examples of how one might use the 'alias' command:" R"( (lldb) command alias bp breakpoint -)" " Creates the abbreviation 'bp' for the 'breakpoint' command. Since \ +)" + " Creates the abbreviation 'bp' for the 'breakpoint' command. Since \ breakpoint commands are two-word commands, the user would still need to \ -enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'." R"( +enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'." + R"( (lldb) command alias bpl breakpoint list Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'. -)" "An alias can include some options for the command, with the values either \ +)" + "An alias can include some options for the command, with the values either \ filled in at the time the alias is created, or specified as positional \ arguments, to be filled in when the alias is invoked. The following example \ -shows how to create aliases with options:" R"( +shows how to create aliases with options:" + R"( (lldb) command alias bfl breakpoint set -f %1 -l %2 -)" " Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \ +)" + " Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \ options already part of the alias. So if the user wants to set a breakpoint \ by file and line without explicitly having to use the -f and -l options, the \ user can now use 'bfl' instead. The '%1' and '%2' are positional placeholders \ @@ -557,18 +467,23 @@ occupies when the alias is used. All the occurrences of '%1' in the alias \ will be replaced with the first argument, all the occurrences of '%2' in the \ alias will be replaced with the second argument, and so on. This also allows \ actual arguments to be used multiple times within an alias (see 'process \ -launch' example below)." R"( +launch' example below)." + R"( -)" "Note: the positional arguments must substitute as whole words in the resultant \ +)" + "Note: the positional arguments must substitute as whole words in the resultant \ command, so you can't at present do something like this to append the file extension \ -\".cpp\":" R"( +\".cpp\":" + R"( (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2 -)" "For more complex aliasing, use the \"command regex\" command instead. In the \ +)" + "For more complex aliasing, use the \"command regex\" command instead. In the \ 'bfl' case above, the actual file value will be filled in with the first argument \ following 'bfl' and the actual line number value will be filled in with the second \ -argument. The user would use this alias as follows:" R"( +argument. The user would use this alias as follows:" + R"( (lldb) command alias bfl breakpoint set -f %1 -l %2 (lldb) bfl my-file.c 137 @@ -582,343 +497,326 @@ Another example: Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0' -)" "If the user always wanted to pass the same value to a particular option, the \ +)" + "If the user always wanted to pass the same value to a particular option, the \ alias could be defined with that value directly in the alias as a constant, \ -rather than using a positional placeholder:" R"( +rather than using a positional placeholder:" + R"( (lldb) command alias bl3 breakpoint set -f %1 -l 3 - Always sets a breakpoint on line 3 of whatever file is indicated.)" - ); - - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentEntry arg3; - CommandArgumentData alias_arg; - CommandArgumentData cmd_arg; - CommandArgumentData options_arg; - - // Define the first (and only) variant of this arg. - alias_arg.arg_type = eArgTypeAliasName; - alias_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (alias_arg); - - // Define the first (and only) variant of this arg. - cmd_arg.arg_type = eArgTypeCommandName; - cmd_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (cmd_arg); - - // Define the first (and only) variant of this arg. - options_arg.arg_type = eArgTypeAliasOptions; - options_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg3.push_back (options_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - m_arguments.push_back (arg3); - } + Always sets a breakpoint on line 3 of whatever file is indicated.)"); + + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentEntry arg3; + CommandArgumentData alias_arg; + CommandArgumentData cmd_arg; + CommandArgumentData options_arg; + + // Define the first (and only) variant of this arg. + alias_arg.arg_type = eArgTypeAliasName; + alias_arg.arg_repetition = eArgRepeatPlain; - ~CommandObjectCommandsAlias() override = default; + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(alias_arg); + + // Define the first (and only) variant of this arg. + cmd_arg.arg_type = eArgTypeCommandName; + cmd_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(cmd_arg); + + // Define the first (and only) variant of this arg. + options_arg.arg_type = eArgTypeAliasOptions; + options_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg3.push_back(options_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + m_arguments.push_back(arg3); + } + + ~CommandObjectCommandsAlias() override = default; protected: - bool - DoExecute (const char *raw_command_line, CommandReturnObject &result) override - { - if (!raw_command_line || !raw_command_line[0]) - { - result.AppendError ("'command alias' requires at least two arguments"); - return false; - } + bool DoExecute(const char *raw_command_line, + CommandReturnObject &result) override { + if (!raw_command_line || !raw_command_line[0]) { + result.AppendError("'command alias' requires at least two arguments"); + return false; + } - ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext(); - m_option_group.NotifyOptionParsingStarting(&exe_ctx); - - const char * remainder = nullptr; - - if (raw_command_line[0] == '-') - { - // We have some options and these options MUST end with --. - const char *end_options = nullptr; - const char *s = raw_command_line; - while (s && s[0]) - { - end_options = ::strstr (s, "--"); - if (end_options) - { - end_options += 2; // Get past the "--" - if (::isspace (end_options[0])) - { - remainder = end_options; - while (::isspace (*remainder)) - ++remainder; - break; - } - } - s = end_options; - } - - if (end_options) - { - Args args (llvm::StringRef(raw_command_line, end_options - raw_command_line)); - if (!ParseOptions (args, result)) - return false; - - Error error (m_option_group.NotifyOptionParsingFinished(&exe_ctx)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - if (nullptr == remainder) - remainder = raw_command_line; - - std::string raw_command_string (remainder); - Args args (raw_command_string.c_str()); - - size_t argc = args.GetArgumentCount(); - - if (argc < 2) - { - result.AppendError ("'command alias' requires at least two arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Get the alias command. - - const std::string alias_command = args.GetArgumentAtIndex (0); - if (alias_command.size() > 1 && - alias_command[0] == '-') - { - result.AppendError("aliases starting with a dash are not supported"); - if (alias_command == "--help" || alias_command == "--long-help") - { - result.AppendWarning("if trying to pass options to 'command alias' add a -- at the end of the options"); - } - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Strip the new alias name off 'raw_command_string' (leave it on args, which gets passed to 'Execute', which - // does the stripping itself. - size_t pos = raw_command_string.find (alias_command); - if (pos == 0) - { - raw_command_string = raw_command_string.substr (alias_command.size()); - pos = raw_command_string.find_first_not_of (' '); - if ((pos != std::string::npos) && (pos > 0)) - raw_command_string = raw_command_string.substr (pos); - } - else - { - result.AppendError ("Error parsing command string. No alias created."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - - // Verify that the command is alias-able. - if (m_interpreter.CommandExists (alias_command.c_str())) - { - result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be redefined.\n", - alias_command.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Get CommandObject that is being aliased. The command name is read from the front of raw_command_string. - // raw_command_string is returned with the name of the command object stripped off the front. - std::string original_raw_command_string(raw_command_string); - CommandObject *cmd_obj = m_interpreter.GetCommandObjectForCommand (raw_command_string); - - if (!cmd_obj) - { - result.AppendErrorWithFormat ("invalid command given to 'command alias'. '%s' does not begin with a valid command." - " No alias created.", original_raw_command_string.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - else if (!cmd_obj->WantsRawCommandString ()) - { - // Note that args was initialized with the original command, and has not been updated to this point. - // Therefore can we pass it to the version of Execute that does not need/expect raw input in the alias. - return HandleAliasingNormalCommand (args, result); - } - else - { - return HandleAliasingRawCommand (alias_command, raw_command_string, *cmd_obj, result); - } - return result.Succeeded(); + ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext(); + m_option_group.NotifyOptionParsingStarting(&exe_ctx); + + const char *remainder = nullptr; + + if (raw_command_line[0] == '-') { + // We have some options and these options MUST end with --. + const char *end_options = nullptr; + const char *s = raw_command_line; + while (s && s[0]) { + end_options = ::strstr(s, "--"); + if (end_options) { + end_options += 2; // Get past the "--" + if (::isspace(end_options[0])) { + remainder = end_options; + while (::isspace(*remainder)) + ++remainder; + break; + } + } + s = end_options; + } + + if (end_options) { + Args args( + llvm::StringRef(raw_command_line, end_options - raw_command_line)); + if (!ParseOptions(args, result)) + return false; + + Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } } + if (nullptr == remainder) + remainder = raw_command_line; - bool - HandleAliasingRawCommand (const std::string &alias_command, std::string &raw_command_string, CommandObject &cmd_obj, CommandReturnObject &result) - { - // Verify & handle any options/arguments passed to the alias command - - OptionArgVectorSP option_arg_vector_sp = OptionArgVectorSP (new OptionArgVector); - - if (CommandObjectSP cmd_obj_sp = m_interpreter.GetCommandSPExact (cmd_obj.GetCommandName(), false)) - { - if (m_interpreter.AliasExists (alias_command.c_str()) - || m_interpreter.UserCommandExists (alias_command.c_str())) - { - result.AppendWarningWithFormat ("Overwriting existing definition for '%s'.\n", - alias_command.c_str()); - } - if (CommandAlias *alias = m_interpreter.AddAlias (alias_command.c_str(), cmd_obj_sp, raw_command_string.c_str())) - { - if (m_command_options.m_help.OptionWasSet()) - alias->SetHelp(m_command_options.m_help.GetCurrentValue()); - if (m_command_options.m_long_help.OptionWasSet()) - alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("Unable to create requested alias.\n"); - result.SetStatus (eReturnStatusFailed); - } + std::string raw_command_string(remainder); + Args args(raw_command_string.c_str()); - } - else - { - result.AppendError ("Unable to create requested alias.\n"); - result.SetStatus (eReturnStatusFailed); - } + size_t argc = args.GetArgumentCount(); - return result.Succeeded (); + if (argc < 2) { + result.AppendError("'command alias' requires at least two arguments"); + result.SetStatus(eReturnStatusFailed); + return false; } - - bool - HandleAliasingNormalCommand (Args& args, CommandReturnObject &result) - { - size_t argc = args.GetArgumentCount(); - if (argc < 2) - { - result.AppendError ("'command alias' requires at least two arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } + // Get the alias command. + + const std::string alias_command = args.GetArgumentAtIndex(0); + if (alias_command.size() > 1 && alias_command[0] == '-') { + result.AppendError("aliases starting with a dash are not supported"); + if (alias_command == "--help" || alias_command == "--long-help") { + result.AppendWarning("if trying to pass options to 'command alias' add " + "a -- at the end of the options"); + } + result.SetStatus(eReturnStatusFailed); + return false; + } + + // Strip the new alias name off 'raw_command_string' (leave it on args, + // which gets passed to 'Execute', which + // does the stripping itself. + size_t pos = raw_command_string.find(alias_command); + if (pos == 0) { + raw_command_string = raw_command_string.substr(alias_command.size()); + pos = raw_command_string.find_first_not_of(' '); + if ((pos != std::string::npos) && (pos > 0)) + raw_command_string = raw_command_string.substr(pos); + } else { + result.AppendError("Error parsing command string. No alias created."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + // Verify that the command is alias-able. + if (m_interpreter.CommandExists(alias_command.c_str())) { + result.AppendErrorWithFormat( + "'%s' is a permanent debugger command and cannot be redefined.\n", + alias_command.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } - const std::string alias_command = args.GetArgumentAtIndex(0); - const std::string actual_command = args.GetArgumentAtIndex(1); + // Get CommandObject that is being aliased. The command name is read from + // the front of raw_command_string. + // raw_command_string is returned with the name of the command object + // stripped off the front. + std::string original_raw_command_string(raw_command_string); + CommandObject *cmd_obj = + m_interpreter.GetCommandObjectForCommand(raw_command_string); + + if (!cmd_obj) { + result.AppendErrorWithFormat("invalid command given to 'command alias'. " + "'%s' does not begin with a valid command." + " No alias created.", + original_raw_command_string.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!cmd_obj->WantsRawCommandString()) { + // Note that args was initialized with the original command, and has not + // been updated to this point. + // Therefore can we pass it to the version of Execute that does not + // need/expect raw input in the alias. + return HandleAliasingNormalCommand(args, result); + } else { + return HandleAliasingRawCommand(alias_command, raw_command_string, + *cmd_obj, result); + } + return result.Succeeded(); + } + + bool HandleAliasingRawCommand(const std::string &alias_command, + std::string &raw_command_string, + CommandObject &cmd_obj, + CommandReturnObject &result) { + // Verify & handle any options/arguments passed to the alias command + + OptionArgVectorSP option_arg_vector_sp = + OptionArgVectorSP(new OptionArgVector); + + if (CommandObjectSP cmd_obj_sp = + m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) { + if (m_interpreter.AliasExists(alias_command.c_str()) || + m_interpreter.UserCommandExists(alias_command.c_str())) { + result.AppendWarningWithFormat( + "Overwriting existing definition for '%s'.\n", + alias_command.c_str()); + } + if (CommandAlias *alias = m_interpreter.AddAlias( + alias_command.c_str(), cmd_obj_sp, raw_command_string.c_str())) { + if (m_command_options.m_help.OptionWasSet()) + alias->SetHelp(m_command_options.m_help.GetCurrentValue()); + if (m_command_options.m_long_help.OptionWasSet()) + alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("Unable to create requested alias.\n"); + result.SetStatus(eReturnStatusFailed); + } + + } else { + result.AppendError("Unable to create requested alias.\n"); + result.SetStatus(eReturnStatusFailed); + } - args.Shift(); // Shift the alias command word off the argument vector. - args.Shift(); // Shift the old command word off the argument vector. + return result.Succeeded(); + } - // Verify that the command is alias'able, and get the appropriate command object. + bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) { + size_t argc = args.GetArgumentCount(); - if (m_interpreter.CommandExists (alias_command.c_str())) - { - result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be redefined.\n", - alias_command.c_str()); - result.SetStatus (eReturnStatusFailed); - } - else - { - CommandObjectSP command_obj_sp(m_interpreter.GetCommandSPExact (actual_command.c_str(), true)); - CommandObjectSP subcommand_obj_sp; - bool use_subcommand = false; - if (command_obj_sp) - { - CommandObject *cmd_obj = command_obj_sp.get(); - CommandObject *sub_cmd_obj = nullptr; - OptionArgVectorSP option_arg_vector_sp = OptionArgVectorSP (new OptionArgVector); - - while (cmd_obj->IsMultiwordObject() && args.GetArgumentCount() > 0) - { - if (argc >= 3) - { - const std::string sub_command = args.GetArgumentAtIndex(0); - assert (sub_command.length() != 0); - subcommand_obj_sp = cmd_obj->GetSubcommandSP (sub_command.c_str()); - if (subcommand_obj_sp) - { - sub_cmd_obj = subcommand_obj_sp.get(); - use_subcommand = true; - args.Shift(); // Shift the sub_command word off the argument vector. - cmd_obj = sub_cmd_obj; - } - else - { - result.AppendErrorWithFormat("'%s' is not a valid sub-command of '%s'. " - "Unable to create alias.\n", - sub_command.c_str(), actual_command.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - - // Verify & handle any options/arguments passed to the alias command - - std::string args_string; - - if (args.GetArgumentCount () > 0) - { - CommandObjectSP tmp_sp = m_interpreter.GetCommandSPExact (cmd_obj->GetCommandName(), false); - if (use_subcommand) - tmp_sp = m_interpreter.GetCommandSPExact (sub_cmd_obj->GetCommandName(), false); - - args.GetCommandString (args_string); - } - - if (m_interpreter.AliasExists (alias_command.c_str()) - || m_interpreter.UserCommandExists (alias_command.c_str())) - { - result.AppendWarningWithFormat ("Overwriting existing definition for '%s'.\n", - alias_command.c_str()); - } - - if (CommandAlias *alias = m_interpreter.AddAlias(alias_command.c_str(), - use_subcommand ? subcommand_obj_sp : command_obj_sp, - args_string.c_str())) - { - if (m_command_options.m_help.OptionWasSet()) - alias->SetHelp(m_command_options.m_help.GetCurrentValue()); - if (m_command_options.m_long_help.OptionWasSet()) - alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("Unable to create requested alias.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - result.AppendErrorWithFormat ("'%s' is not an existing command.\n", actual_command.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } + if (argc < 2) { + result.AppendError("'command alias' requires at least two arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + const std::string alias_command = args.GetArgumentAtIndex(0); + const std::string actual_command = args.GetArgumentAtIndex(1); + + args.Shift(); // Shift the alias command word off the argument vector. + args.Shift(); // Shift the old command word off the argument vector. + + // Verify that the command is alias'able, and get the appropriate command + // object. + + if (m_interpreter.CommandExists(alias_command.c_str())) { + result.AppendErrorWithFormat( + "'%s' is a permanent debugger command and cannot be redefined.\n", + alias_command.c_str()); + result.SetStatus(eReturnStatusFailed); + } else { + CommandObjectSP command_obj_sp( + m_interpreter.GetCommandSPExact(actual_command.c_str(), true)); + CommandObjectSP subcommand_obj_sp; + bool use_subcommand = false; + if (command_obj_sp) { + CommandObject *cmd_obj = command_obj_sp.get(); + CommandObject *sub_cmd_obj = nullptr; + OptionArgVectorSP option_arg_vector_sp = + OptionArgVectorSP(new OptionArgVector); + + while (cmd_obj->IsMultiwordObject() && args.GetArgumentCount() > 0) { + if (argc >= 3) { + const std::string sub_command = args.GetArgumentAtIndex(0); + assert(sub_command.length() != 0); + subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command.c_str()); + if (subcommand_obj_sp) { + sub_cmd_obj = subcommand_obj_sp.get(); + use_subcommand = true; + args.Shift(); // Shift the sub_command word off the argument + // vector. + cmd_obj = sub_cmd_obj; + } else { + result.AppendErrorWithFormat( + "'%s' is not a valid sub-command of '%s'. " + "Unable to create alias.\n", + sub_command.c_str(), actual_command.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + } + + // Verify & handle any options/arguments passed to the alias command + + std::string args_string; + + if (args.GetArgumentCount() > 0) { + CommandObjectSP tmp_sp = + m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false); + if (use_subcommand) + tmp_sp = m_interpreter.GetCommandSPExact( + sub_cmd_obj->GetCommandName(), false); + + args.GetCommandString(args_string); + } + + if (m_interpreter.AliasExists(alias_command.c_str()) || + m_interpreter.UserCommandExists(alias_command.c_str())) { + result.AppendWarningWithFormat( + "Overwriting existing definition for '%s'.\n", + alias_command.c_str()); + } + + if (CommandAlias *alias = m_interpreter.AddAlias( + alias_command.c_str(), + use_subcommand ? subcommand_obj_sp : command_obj_sp, + args_string.c_str())) { + if (m_command_options.m_help.OptionWasSet()) + alias->SetHelp(m_command_options.m_help.GetCurrentValue()); + if (m_command_options.m_long_help.OptionWasSet()) + alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("Unable to create requested alias.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + result.AppendErrorWithFormat("'%s' is not an existing command.\n", + actual_command.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } } + + return result.Succeeded(); + } }; -OptionDefinition -CommandObjectCommandsAlias::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectCommandsAlias::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "help", 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Help text for this command"}, {LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Long help text for this command"}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectCommandsUnalias @@ -926,87 +824,78 @@ CommandObjectCommandsAlias::CommandOptions::g_option_table[] = // CommandObjectCommandsUnalias //------------------------------------------------------------------------- -class CommandObjectCommandsUnalias : public CommandObjectParsed -{ +class CommandObjectCommandsUnalias : public CommandObjectParsed { public: - CommandObjectCommandsUnalias(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "command unalias", - "Delete one or more custom commands defined by 'command alias'.", nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData alias_arg; - - // Define the first (and only) variant of this arg. - alias_arg.arg_type = eArgTypeAliasName; - alias_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (alias_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectCommandsUnalias(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "command unalias", + "Delete one or more custom commands defined by 'command alias'.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData alias_arg; - ~CommandObjectCommandsUnalias() override = default; + // Define the first (and only) variant of this arg. + alias_arg.arg_type = eArgTypeAliasName; + alias_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(alias_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectCommandsUnalias() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - CommandObject::CommandMap::iterator pos; - CommandObject *cmd_obj; - - if (args.GetArgumentCount() != 0) - { - const char *command_name = args.GetArgumentAtIndex(0); - cmd_obj = m_interpreter.GetCommandObject(command_name); - if (cmd_obj) - { - if (m_interpreter.CommandExists (command_name)) - { - if (cmd_obj->IsRemovable()) - { - result.AppendErrorWithFormat ("'%s' is not an alias, it is a debugger command which can be removed using the 'command delete' command.\n", - command_name); - } - else - { - result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be removed.\n", - command_name); - } - result.SetStatus (eReturnStatusFailed); - } - else - { - if (!m_interpreter.RemoveAlias(command_name)) - { - if (m_interpreter.AliasExists (command_name)) - result.AppendErrorWithFormat ("Error occurred while attempting to unalias '%s'.\n", - command_name); - else - result.AppendErrorWithFormat ("'%s' is not an existing alias.\n", command_name); - result.SetStatus (eReturnStatusFailed); - } - else - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - } + bool DoExecute(Args &args, CommandReturnObject &result) override { + CommandObject::CommandMap::iterator pos; + CommandObject *cmd_obj; + + if (args.GetArgumentCount() != 0) { + const char *command_name = args.GetArgumentAtIndex(0); + cmd_obj = m_interpreter.GetCommandObject(command_name); + if (cmd_obj) { + if (m_interpreter.CommandExists(command_name)) { + if (cmd_obj->IsRemovable()) { + result.AppendErrorWithFormat( + "'%s' is not an alias, it is a debugger command which can be " + "removed using the 'command delete' command.\n", + command_name); + } else { + result.AppendErrorWithFormat( + "'%s' is a permanent debugger command and cannot be removed.\n", + command_name); + } + result.SetStatus(eReturnStatusFailed); + } else { + if (!m_interpreter.RemoveAlias(command_name)) { + if (m_interpreter.AliasExists(command_name)) + result.AppendErrorWithFormat( + "Error occurred while attempting to unalias '%s'.\n", + command_name); else - { - result.AppendErrorWithFormat ("'%s' is not a known command.\nTry 'help' to see a " - "current list of commands.\n", - command_name); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("must call 'unalias' with a valid alias"); - result.SetStatus (eReturnStatusFailed); - } - - return result.Succeeded(); + result.AppendErrorWithFormat("'%s' is not an existing alias.\n", + command_name); + result.SetStatus(eReturnStatusFailed); + } else + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } + } else { + result.AppendErrorWithFormat( + "'%s' is not a known command.\nTry 'help' to see a " + "current list of commands.\n", + command_name); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("must call 'unalias' with a valid alias"); + result.SetStatus(eReturnStatusFailed); } + + return result.Succeeded(); + } }; #pragma mark CommandObjectCommandsDelete @@ -1014,76 +903,64 @@ protected: // CommandObjectCommandsDelete //------------------------------------------------------------------------- -class CommandObjectCommandsDelete : public CommandObjectParsed -{ +class CommandObjectCommandsDelete : public CommandObjectParsed { public: - CommandObjectCommandsDelete(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "command delete", - "Delete one or more custom commands defined by 'command regex'.", nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData alias_arg; + CommandObjectCommandsDelete(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "command delete", + "Delete one or more custom commands defined by 'command regex'.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData alias_arg; - // Define the first (and only) variant of this arg. - alias_arg.arg_type = eArgTypeCommandName; - alias_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + alias_arg.arg_type = eArgTypeCommandName; + alias_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (alias_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(alias_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectCommandsDelete() override = default; + ~CommandObjectCommandsDelete() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - CommandObject::CommandMap::iterator pos; - - if (args.GetArgumentCount() != 0) - { - const char *command_name = args.GetArgumentAtIndex(0); - if (m_interpreter.CommandExists (command_name)) - { - if (m_interpreter.RemoveCommand (command_name)) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendErrorWithFormat ("'%s' is a permanent debugger command and cannot be removed.\n", - command_name); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - StreamString error_msg_stream; - const bool generate_apropos = true; - const bool generate_type_lookup = false; - CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, - command_name, - nullptr, - nullptr, - generate_apropos, - generate_type_lookup); - result.AppendErrorWithFormat ("%s", error_msg_stream.GetData()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat( - "must call '%s' with one or more valid user defined regular expression command names", - GetCommandName()); - result.SetStatus (eReturnStatusFailed); - } - - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + CommandObject::CommandMap::iterator pos; + + if (args.GetArgumentCount() != 0) { + const char *command_name = args.GetArgumentAtIndex(0); + if (m_interpreter.CommandExists(command_name)) { + if (m_interpreter.RemoveCommand(command_name)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendErrorWithFormat( + "'%s' is a permanent debugger command and cannot be removed.\n", + command_name); + result.SetStatus(eReturnStatusFailed); + } + } else { + StreamString error_msg_stream; + const bool generate_apropos = true; + const bool generate_type_lookup = false; + CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage( + &error_msg_stream, command_name, nullptr, nullptr, generate_apropos, + generate_type_lookup); + result.AppendErrorWithFormat("%s", error_msg_stream.GetData()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("must call '%s' with one or more valid user " + "defined regular expression command names", + GetCommandName()); + result.SetStatus(eReturnStatusFailed); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1091,1181 +968,967 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectCommandsAddRegex -class CommandObjectCommandsAddRegex : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectCommandsAddRegex : public CommandObjectParsed, + public IOHandlerDelegateMultiline { public: - CommandObjectCommandsAddRegex(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "command regex", - "Define a custom command in terms of existing commands by matching regular expressions.", - "command regex [s/// ...]"), - IOHandlerDelegateMultiline("", IOHandlerDelegate::Completion::LLDBCommand), - m_options() - { - SetHelpLong(R"( -)" "This command allows the user to create powerful regular expression commands \ + CommandObjectCommandsAddRegex(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "command regex", "Define a custom command in terms of " + "existing commands by matching " + "regular expressions.", + "command regex [s/// ...]"), + IOHandlerDelegateMultiline("", + IOHandlerDelegate::Completion::LLDBCommand), + m_options() { + SetHelpLong( + R"( +)" + "This command allows the user to create powerful regular expression commands \ with substitutions. The regular expressions and substitutions are specified \ -using the regular expression substitution format of:" R"( +using the regular expression substitution format of:" + R"( s/// -)" " is a regular expression that can use parenthesis to capture regular \ +)" + " is a regular expression that can use parenthesis to capture regular \ expression input and substitute the captured matches in the output using %1 \ -for the first match, %2 for the second, and so on." R"( +for the first match, %2 for the second, and so on." + R"( -)" "The regular expressions can all be specified on the command line if more than \ +)" + "The regular expressions can all be specified on the command line if more than \ one argument is provided. If just the command name is provided on the command \ line, then the regular expressions and substitutions can be entered on separate \ -lines, followed by an empty line to terminate the command definition." R"( +lines, followed by an empty line to terminate the command definition." + R"( EXAMPLES -)" "The following example will define a regular expression command named 'f' that \ +)" + "The following example will define a regular expression command named 'f' that \ will call 'finish' if there are no arguments, or 'frame select ' if \ -a number follows 'f':" R"( +a number follows 'f':" + R"( - (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')" - ); - } + (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')"); + } - ~CommandObjectCommandsAddRegex() override = default; + ~CommandObjectCommandsAddRegex() override = default; protected: - void - IOHandlerActivated (IOHandler &io_handler) override - { - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString("Enter one of more sed substitution commands in the form: 's///'.\nTerminate the substitution list with an empty line.\n"); - output_sp->Flush(); - } + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString("Enter one of more sed substitution commands in " + "the form: 's///'.\nTerminate the " + "substitution list with an empty line.\n"); + output_sp->Flush(); } - - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override - { - io_handler.SetIsDone(true); - if (m_regex_cmd_ap) - { - StringList lines; - if (lines.SplitIntoLines (data)) - { - const size_t num_lines = lines.GetSize(); - bool check_only = false; - for (size_t i=0; iPrintf("error: %s\n", error.AsCString()); - } - } - } - } - if (m_regex_cmd_ap->HasRegexEntries()) - { - CommandObjectSP cmd_sp (m_regex_cmd_ap.release()); - m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) override { + io_handler.SetIsDone(true); + if (m_regex_cmd_ap) { + StringList lines; + if (lines.SplitIntoLines(data)) { + const size_t num_lines = lines.GetSize(); + bool check_only = false; + for (size_t i = 0; i < num_lines; ++i) { + llvm::StringRef bytes_strref(lines[i]); + Error error = AppendRegexSubstitution(bytes_strref, check_only); + if (error.Fail()) { + if (!m_interpreter.GetDebugger() + .GetCommandInterpreter() + .GetBatchCommandMode()) { + StreamSP out_stream = + m_interpreter.GetDebugger().GetAsyncOutputStream(); + out_stream->Printf("error: %s\n", error.AsCString()); } + } } + } + if (m_regex_cmd_ap->HasRegexEntries()) { + CommandObjectSP cmd_sp(m_regex_cmd_ap.release()); + m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); + } + } + } + + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + if (argc == 0) { + result.AppendError("usage: 'command regex " + "[s/// s/// ...]'\n"); + result.SetStatus(eReturnStatusFailed); + } else { + Error error; + const char *name = command.GetArgumentAtIndex(0); + m_regex_cmd_ap.reset(new CommandObjectRegexCommand( + m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, + 0, true)); + + if (argc == 1) { + Debugger &debugger = m_interpreter.GetDebugger(); + bool color_prompt = debugger.GetUseColor(); + const bool multiple_lines = true; // Get multiple lines + IOHandlerSP io_handler_sp(new IOHandlerEditline( + debugger, IOHandler::Type::Other, + "lldb-regex", // Name of input reader for history + "> ", // Prompt + nullptr, // Continuation prompt + multiple_lines, color_prompt, + 0, // Don't show line numbers + *this)); + + if (io_handler_sp) { + debugger.PushIOHandler(io_handler_sp); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } + } else { + for (size_t arg_idx = 1; arg_idx < argc; ++arg_idx) { + llvm::StringRef arg_strref(command.GetArgumentAtIndex(arg_idx)); + bool check_only = false; + error = AppendRegexSubstitution(arg_strref, check_only); + if (error.Fail()) + break; + } + + if (error.Success()) { + AddRegexCommandToInterpreter(); + } + } + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } } - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - if (argc == 0) - { - result.AppendError ("usage: 'command regex [s/// s/// ...]'\n"); - result.SetStatus (eReturnStatusFailed); - } - else - { - Error error; - const char *name = command.GetArgumentAtIndex(0); - m_regex_cmd_ap.reset (new CommandObjectRegexCommand (m_interpreter, - name, - m_options.GetHelp (), - m_options.GetSyntax (), - 10, - 0, - true)); - - if (argc == 1) - { - Debugger &debugger = m_interpreter.GetDebugger(); - bool color_prompt = debugger.GetUseColor(); - const bool multiple_lines = true; // Get multiple lines - IOHandlerSP io_handler_sp(new IOHandlerEditline(debugger, - IOHandler::Type::Other, - "lldb-regex", // Name of input reader for history - "> ", // Prompt - nullptr, // Continuation prompt - multiple_lines, - color_prompt, - 0, // Don't show line numbers - *this)); - - if (io_handler_sp) - { - debugger.PushIOHandler(io_handler_sp); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - } - else - { - for (size_t arg_idx = 1; arg_idx < argc; ++arg_idx) - { - llvm::StringRef arg_strref (command.GetArgumentAtIndex(arg_idx)); - bool check_only = false; - error = AppendRegexSubstitution (arg_strref, check_only); - if (error.Fail()) - break; - } - - if (error.Success()) - { - AddRegexCommandToInterpreter(); - } - } - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } + return result.Succeeded(); + } + + Error AppendRegexSubstitution(const llvm::StringRef ®ex_sed, + bool check_only) { + Error error; - return result.Succeeded(); + if (!m_regex_cmd_ap) { + error.SetErrorStringWithFormat( + "invalid regular expression command object for: '%.*s'", + (int)regex_sed.size(), regex_sed.data()); + return error; } - - Error - AppendRegexSubstitution (const llvm::StringRef ®ex_sed, bool check_only) - { - Error error; - - if (!m_regex_cmd_ap) - { - error.SetErrorStringWithFormat("invalid regular expression command object for: '%.*s'", - (int)regex_sed.size(), - regex_sed.data()); - return error; - } - - size_t regex_sed_size = regex_sed.size(); - - if (regex_sed_size <= 1) - { - error.SetErrorStringWithFormat("regular expression substitution string is too short: '%.*s'", - (int)regex_sed.size(), - regex_sed.data()); - return error; - } - if (regex_sed[0] != 's') - { - error.SetErrorStringWithFormat("regular expression substitution string doesn't start with 's': '%.*s'", - (int)regex_sed.size(), - regex_sed.data()); - return error; - } - const size_t first_separator_char_pos = 1; - // use the char that follows 's' as the regex separator character - // so we can have "s///" or "s|||" - const char separator_char = regex_sed[first_separator_char_pos]; - const size_t second_separator_char_pos = regex_sed.find (separator_char, first_separator_char_pos + 1); - - if (second_separator_char_pos == std::string::npos) - { - error.SetErrorStringWithFormat("missing second '%c' separator char after '%.*s' in '%.*s'", - separator_char, - (int)(regex_sed.size() - first_separator_char_pos - 1), - regex_sed.data() + (first_separator_char_pos + 1), - (int)regex_sed.size(), - regex_sed.data()); - return error; - } + size_t regex_sed_size = regex_sed.size(); - const size_t third_separator_char_pos = regex_sed.find (separator_char, second_separator_char_pos + 1); - - if (third_separator_char_pos == std::string::npos) - { - error.SetErrorStringWithFormat("missing third '%c' separator char after '%.*s' in '%.*s'", - separator_char, - (int)(regex_sed.size() - second_separator_char_pos - 1), - regex_sed.data() + (second_separator_char_pos + 1), - (int)regex_sed.size(), - regex_sed.data()); - return error; - } + if (regex_sed_size <= 1) { + error.SetErrorStringWithFormat( + "regular expression substitution string is too short: '%.*s'", + (int)regex_sed.size(), regex_sed.data()); + return error; + } - if (third_separator_char_pos != regex_sed_size - 1) - { - // Make sure that everything that follows the last regex - // separator char - if (regex_sed.find_first_not_of("\t\n\v\f\r ", third_separator_char_pos + 1) != std::string::npos) - { - error.SetErrorStringWithFormat("extra data found after the '%.*s' regular expression substitution string: '%.*s'", - (int)third_separator_char_pos + 1, - regex_sed.data(), - (int)(regex_sed.size() - third_separator_char_pos - 1), - regex_sed.data() + (third_separator_char_pos + 1)); - return error; - } - } - else if (first_separator_char_pos + 1 == second_separator_char_pos) - { - error.SetErrorStringWithFormat(" can't be empty in 's%c%c%c' string: '%.*s'", - separator_char, - separator_char, - separator_char, - (int)regex_sed.size(), - regex_sed.data()); - return error; - } - else if (second_separator_char_pos + 1 == third_separator_char_pos) - { - error.SetErrorStringWithFormat(" can't be empty in 's%c%c%c' string: '%.*s'", - separator_char, - separator_char, - separator_char, - (int)regex_sed.size(), - regex_sed.data()); - return error; - } + if (regex_sed[0] != 's') { + error.SetErrorStringWithFormat("regular expression substitution string " + "doesn't start with 's': '%.*s'", + (int)regex_sed.size(), regex_sed.data()); + return error; + } + const size_t first_separator_char_pos = 1; + // use the char that follows 's' as the regex separator character + // so we can have "s///" or "s|||" + const char separator_char = regex_sed[first_separator_char_pos]; + const size_t second_separator_char_pos = + regex_sed.find(separator_char, first_separator_char_pos + 1); + + if (second_separator_char_pos == std::string::npos) { + error.SetErrorStringWithFormat( + "missing second '%c' separator char after '%.*s' in '%.*s'", + separator_char, + (int)(regex_sed.size() - first_separator_char_pos - 1), + regex_sed.data() + (first_separator_char_pos + 1), + (int)regex_sed.size(), regex_sed.data()); + return error; + } - if (!check_only) - { - std::string regex(regex_sed.substr(first_separator_char_pos + 1, second_separator_char_pos - first_separator_char_pos - 1)); - std::string subst(regex_sed.substr(second_separator_char_pos + 1, third_separator_char_pos - second_separator_char_pos - 1)); - m_regex_cmd_ap->AddRegexCommand (regex.c_str(), - subst.c_str()); - } + const size_t third_separator_char_pos = + regex_sed.find(separator_char, second_separator_char_pos + 1); + + if (third_separator_char_pos == std::string::npos) { + error.SetErrorStringWithFormat( + "missing third '%c' separator char after '%.*s' in '%.*s'", + separator_char, + (int)(regex_sed.size() - second_separator_char_pos - 1), + regex_sed.data() + (second_separator_char_pos + 1), + (int)regex_sed.size(), regex_sed.data()); + return error; + } + + if (third_separator_char_pos != regex_sed_size - 1) { + // Make sure that everything that follows the last regex + // separator char + if (regex_sed.find_first_not_of("\t\n\v\f\r ", + third_separator_char_pos + 1) != + std::string::npos) { + error.SetErrorStringWithFormat( + "extra data found after the '%.*s' regular expression substitution " + "string: '%.*s'", + (int)third_separator_char_pos + 1, regex_sed.data(), + (int)(regex_sed.size() - third_separator_char_pos - 1), + regex_sed.data() + (third_separator_char_pos + 1)); return error; + } + } else if (first_separator_char_pos + 1 == second_separator_char_pos) { + error.SetErrorStringWithFormat( + " can't be empty in 's%c%c%c' string: '%.*s'", + separator_char, separator_char, separator_char, (int)regex_sed.size(), + regex_sed.data()); + return error; + } else if (second_separator_char_pos + 1 == third_separator_char_pos) { + error.SetErrorStringWithFormat( + " can't be empty in 's%c%c%c' string: '%.*s'", + separator_char, separator_char, separator_char, (int)regex_sed.size(), + regex_sed.data()); + return error; } - - void - AddRegexCommandToInterpreter() - { - if (m_regex_cmd_ap) - { - if (m_regex_cmd_ap->HasRegexEntries()) - { - CommandObjectSP cmd_sp (m_regex_cmd_ap.release()); - m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); - } - } + + if (!check_only) { + std::string regex(regex_sed.substr(first_separator_char_pos + 1, + second_separator_char_pos - + first_separator_char_pos - 1)); + std::string subst(regex_sed.substr(second_separator_char_pos + 1, + third_separator_char_pos - + second_separator_char_pos - 1)); + m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str()); + } + return error; + } + + void AddRegexCommandToInterpreter() { + if (m_regex_cmd_ap) { + if (m_regex_cmd_ap->HasRegexEntries()) { + CommandObjectSP cmd_sp(m_regex_cmd_ap.release()); + m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true); + } } + } private: - std::unique_ptr m_regex_cmd_ap; - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'h': - m_help.assign (option_arg); - break; - case 's': - m_syntax.assign (option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_help.clear(); - m_syntax.clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - const char * - GetHelp() - { - return (m_help.empty() ? nullptr : m_help.c_str()); - } - - const char * - GetSyntax () - { - return (m_syntax.empty() ? nullptr : m_syntax.c_str()); - } - - protected: - // Instance variables to hold the values for command options. - - std::string m_help; - std::string m_syntax; - }; - - Options * - GetOptions () override - { - return &m_options; - } - - CommandOptions m_options; + std::unique_ptr m_regex_cmd_ap; + + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'h': + m_help.assign(option_arg); + break; + case 's': + m_syntax.assign(option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_help.clear(); + m_syntax.clear(); + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + const char *GetHelp() { + return (m_help.empty() ? nullptr : m_help.c_str()); + } + + const char *GetSyntax() { + return (m_syntax.empty() ? nullptr : m_syntax.c_str()); + } + + protected: + // Instance variables to hold the values for command options. + + std::string m_help; + std::string m_syntax; + }; + + Options *GetOptions() override { return &m_options; } + + CommandOptions m_options; }; OptionDefinition -CommandObjectCommandsAddRegex::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectCommandsAddRegex::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "help" , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The help text to display for this command."}, {LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "A syntax string showing the typical usage syntax."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectPythonFunction : public CommandObjectRaw -{ +class CommandObjectPythonFunction : public CommandObjectRaw { public: - CommandObjectPythonFunction (CommandInterpreter &interpreter, - std::string name, - std::string funct, - std::string help, - ScriptedCommandSynchronicity synch) : - CommandObjectRaw(interpreter, - name.c_str(), - nullptr, - nullptr), - m_function_name(funct), - m_synchro(synch), - m_fetched_help_long(false) - { - if (!help.empty()) - SetHelp(help.c_str()); - else - { - StreamString stream; - stream.Printf("For more information run 'help %s'",name.c_str()); - SetHelp(stream.GetData()); - } + CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name, + std::string funct, std::string help, + ScriptedCommandSynchronicity synch) + : CommandObjectRaw(interpreter, name.c_str(), nullptr, nullptr), + m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) { + if (!help.empty()) + SetHelp(help.c_str()); + else { + StreamString stream; + stream.Printf("For more information run 'help %s'", name.c_str()); + SetHelp(stream.GetData()); } + } - ~CommandObjectPythonFunction() override = default; + ~CommandObjectPythonFunction() override = default; - bool - IsRemovable () const override - { - return true; - } + bool IsRemovable() const override { return true; } - const std::string& - GetFunctionName () - { - return m_function_name; - } + const std::string &GetFunctionName() { return m_function_name; } - ScriptedCommandSynchronicity - GetSynchronicity () - { - return m_synchro; - } - - const char * - GetHelpLong () override - { - if (!m_fetched_help_long) - { - ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter(); - if (scripter) - { - std::string docstring; - m_fetched_help_long = scripter->GetDocumentationForItem(m_function_name.c_str(),docstring); - if (!docstring.empty()) - SetHelpLong(docstring.c_str()); - } - } - return CommandObjectRaw::GetHelpLong(); + ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; } + + const char *GetHelpLong() override { + if (!m_fetched_help_long) { + ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + if (scripter) { + std::string docstring; + m_fetched_help_long = scripter->GetDocumentationForItem( + m_function_name.c_str(), docstring); + if (!docstring.empty()) + SetHelpLong(docstring.c_str()); + } } - + return CommandObjectRaw::GetHelpLong(); + } + protected: - bool - DoExecute (const char *raw_command_line, CommandReturnObject &result) override - { - ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter(); - - Error error; - - result.SetStatus(eReturnStatusInvalid); - - if (!scripter || !scripter->RunScriptBasedCommand(m_function_name.c_str(), - raw_command_line, - m_synchro, - result, - error, - m_exe_ctx)) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } + bool DoExecute(const char *raw_command_line, + CommandReturnObject &result) override { + ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + + Error error; + + result.SetStatus(eReturnStatusInvalid); + + if (!scripter || + !scripter->RunScriptBasedCommand(m_function_name.c_str(), + raw_command_line, m_synchro, result, + error, m_exe_ctx)) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else { + // Don't change the status if the command already set it... + if (result.GetStatus() == eReturnStatusInvalid) { + if (result.GetOutputData() == nullptr || + result.GetOutputData()[0] == '\0') + result.SetStatus(eReturnStatusSuccessFinishNoResult); else - { - // Don't change the status if the command already set it... - if (result.GetStatus() == eReturnStatusInvalid) - { - if (result.GetOutputData() == nullptr || result.GetOutputData()[0] == '\0') - result.SetStatus(eReturnStatusSuccessFinishNoResult); - else - result.SetStatus(eReturnStatusSuccessFinishResult); - } - } - - return result.Succeeded(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } } + return result.Succeeded(); + } + private: - std::string m_function_name; - ScriptedCommandSynchronicity m_synchro; - bool m_fetched_help_long; + std::string m_function_name; + ScriptedCommandSynchronicity m_synchro; + bool m_fetched_help_long; }; -class CommandObjectScriptingObject : public CommandObjectRaw -{ +class CommandObjectScriptingObject : public CommandObjectRaw { public: - CommandObjectScriptingObject (CommandInterpreter &interpreter, - std::string name, - StructuredData::GenericSP cmd_obj_sp, - ScriptedCommandSynchronicity synch) : - CommandObjectRaw(interpreter, - name.c_str(), - nullptr, - nullptr), - m_cmd_obj_sp(cmd_obj_sp), - m_synchro(synch), - m_fetched_help_short(false), - m_fetched_help_long(false) - { - StreamString stream; - stream.Printf("For more information run 'help %s'",name.c_str()); - SetHelp(stream.GetData()); - if (ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter()) - GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp)); + CommandObjectScriptingObject(CommandInterpreter &interpreter, + std::string name, + StructuredData::GenericSP cmd_obj_sp, + ScriptedCommandSynchronicity synch) + : CommandObjectRaw(interpreter, name.c_str(), nullptr, nullptr), + m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false), + m_fetched_help_long(false) { + StreamString stream; + stream.Printf("For more information run 'help %s'", name.c_str()); + SetHelp(stream.GetData()); + if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter()) + GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp)); + } + + ~CommandObjectScriptingObject() override = default; + + bool IsRemovable() const override { return true; } + + StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; } + + ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; } + + const char *GetHelp() override { + if (!m_fetched_help_short) { + ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + if (scripter) { + std::string docstring; + m_fetched_help_short = + scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring); + if (!docstring.empty()) + SetHelp(docstring.c_str()); + } } - - ~CommandObjectScriptingObject() override = default; - - bool - IsRemovable () const override - { - return true; - } - - StructuredData::GenericSP - GetImplementingObject () - { - return m_cmd_obj_sp; - } - - ScriptedCommandSynchronicity - GetSynchronicity () - { - return m_synchro; + return CommandObjectRaw::GetHelp(); + } + + const char *GetHelpLong() override { + if (!m_fetched_help_long) { + ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + if (scripter) { + std::string docstring; + m_fetched_help_long = + scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring); + if (!docstring.empty()) + SetHelpLong(docstring.c_str()); + } } + return CommandObjectRaw::GetHelpLong(); + } - const char * - GetHelp () override - { - if (!m_fetched_help_short) - { - ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter(); - if (scripter) - { - std::string docstring; - m_fetched_help_short = scripter->GetShortHelpForCommandObject(m_cmd_obj_sp,docstring); - if (!docstring.empty()) - SetHelp(docstring.c_str()); - } - } - return CommandObjectRaw::GetHelp(); - } - - const char * - GetHelpLong () override - { - if (!m_fetched_help_long) - { - ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter(); - if (scripter) - { - std::string docstring; - m_fetched_help_long = scripter->GetLongHelpForCommandObject(m_cmd_obj_sp,docstring); - if (!docstring.empty()) - SetHelpLong(docstring.c_str()); - } - } - return CommandObjectRaw::GetHelpLong(); - } - protected: - bool - DoExecute (const char *raw_command_line, CommandReturnObject &result) override - { - ScriptInterpreter* scripter = m_interpreter.GetScriptInterpreter(); - - Error error; - - result.SetStatus(eReturnStatusInvalid); - - if (!scripter || !scripter->RunScriptBasedCommand(m_cmd_obj_sp, - raw_command_line, - m_synchro, - result, - error, - m_exe_ctx)) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } + bool DoExecute(const char *raw_command_line, + CommandReturnObject &result) override { + ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); + + Error error; + + result.SetStatus(eReturnStatusInvalid); + + if (!scripter || + !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line, + m_synchro, result, error, m_exe_ctx)) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else { + // Don't change the status if the command already set it... + if (result.GetStatus() == eReturnStatusInvalid) { + if (result.GetOutputData() == nullptr || + result.GetOutputData()[0] == '\0') + result.SetStatus(eReturnStatusSuccessFinishNoResult); else - { - // Don't change the status if the command already set it... - if (result.GetStatus() == eReturnStatusInvalid) - { - if (result.GetOutputData() == nullptr || result.GetOutputData()[0] == '\0') - result.SetStatus(eReturnStatusSuccessFinishNoResult); - else - result.SetStatus(eReturnStatusSuccessFinishResult); - } - } - - return result.Succeeded(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } } + return result.Succeeded(); + } + private: - StructuredData::GenericSP m_cmd_obj_sp; - ScriptedCommandSynchronicity m_synchro; - bool m_fetched_help_short: 1; - bool m_fetched_help_long: 1; + StructuredData::GenericSP m_cmd_obj_sp; + ScriptedCommandSynchronicity m_synchro; + bool m_fetched_help_short : 1; + bool m_fetched_help_long : 1; }; //------------------------------------------------------------------------- // CommandObjectCommandsScriptImport //------------------------------------------------------------------------- -class CommandObjectCommandsScriptImport : public CommandObjectParsed -{ +class CommandObjectCommandsScriptImport : public CommandObjectParsed { public: - CommandObjectCommandsScriptImport (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command script import", - "Import a scripting module in LLDB.", - nullptr), - m_options() - { - CommandArgumentEntry arg1; - CommandArgumentData cmd_arg; - - // Define the first (and only) variant of this arg. - cmd_arg.arg_type = eArgTypeFilename; - cmd_arg.arg_repetition = eArgRepeatPlus; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (cmd_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); + CommandObjectCommandsScriptImport(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command script import", + "Import a scripting module in LLDB.", nullptr), + m_options() { + CommandArgumentEntry arg1; + CommandArgumentData cmd_arg; + + // Define the first (and only) variant of this arg. + cmd_arg.arg_type = eArgTypeFilename; + cmd_arg.arg_repetition = eArgRepeatPlus; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(cmd_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectCommandsScriptImport() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } + + Options *GetOptions() override { return &m_options; } + +protected: + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'r': + m_allow_reload = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectCommandsScriptImport() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_allow_reload = true; } - - Options * - GetOptions () override - { - return &m_options; + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + bool m_allow_reload; + }; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (m_interpreter.GetDebugger().GetScriptLanguage() != + lldb::eScriptLanguagePython) { + result.AppendError("only scripting language supported for module " + "importing is currently Python"); + result.SetStatus(eReturnStatusFailed); + return false; } -protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } + size_t argc = command.GetArgumentCount(); + if (0 == argc) { + result.AppendError("command script import needs one or more arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'r': - m_allow_reload = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_allow_reload = true; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_allow_reload; - }; - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (m_interpreter.GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) - { - result.AppendError ("only scripting language supported for module importing is currently Python"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - size_t argc = command.GetArgumentCount(); - if (0 == argc) - { - result.AppendError("command script import needs one or more arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - for (size_t i = 0; - i < argc; - i++) - { - std::string path = command.GetArgumentAtIndex(i); - Error error; - - const bool init_session = true; - // FIXME: this is necessary because CommandObject::CheckRequirements() assumes that - // commands won't ever be recursively invoked, but it's actually possible to craft - // a Python script that does other "command script imports" in __lldb_init_module - // the real fix is to have recursive commands possible with a CommandInvocation object - // separate from the CommandObject itself, so that recursive command invocations - // won't stomp on each other (wrt to execution contents, options, and more) - m_exe_ctx.Clear(); - if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(path.c_str(), - m_options.m_allow_reload, - init_session, - error)) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendErrorWithFormat("module importing failed: %s", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - - return result.Succeeded(); + for (size_t i = 0; i < argc; i++) { + std::string path = command.GetArgumentAtIndex(i); + Error error; + + const bool init_session = true; + // FIXME: this is necessary because CommandObject::CheckRequirements() + // assumes that + // commands won't ever be recursively invoked, but it's actually possible + // to craft + // a Python script that does other "command script imports" in + // __lldb_init_module + // the real fix is to have recursive commands possible with a + // CommandInvocation object + // separate from the CommandObject itself, so that recursive command + // invocations + // won't stomp on each other (wrt to execution contents, options, and + // more) + m_exe_ctx.Clear(); + if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule( + path.c_str(), m_options.m_allow_reload, init_session, error)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendErrorWithFormat("module importing failed: %s", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } } - - CommandOptions m_options; + + return result.Succeeded(); + } + + CommandOptions m_options; }; OptionDefinition -CommandObjectCommandsScriptImport::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectCommandsScriptImport::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "allow-reload", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow the script to be loaded even if it was already loaded before. This argument exists for backwards compatibility, but reloading is always allowed, whether you specify it or not."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectCommandsScriptAdd //------------------------------------------------------------------------- -class CommandObjectCommandsScriptAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectCommandsScriptAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { public: - CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command script add", + CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command script add", "Add a scripted function as an LLDB command.", nullptr), - IOHandlerDelegateMultiline ("DONE"), - m_options() - { - CommandArgumentEntry arg1; - CommandArgumentData cmd_arg; - - // Define the first (and only) variant of this arg. - cmd_arg.arg_type = eArgTypeCommandName; - cmd_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (cmd_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - } + IOHandlerDelegateMultiline("DONE"), m_options() { + CommandArgumentEntry arg1; + CommandArgumentData cmd_arg; - ~CommandObjectCommandsScriptAdd() override = default; + // Define the first (and only) variant of this arg. + cmd_arg.arg_type = eArgTypeCommandName; + cmd_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(cmd_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectCommandsScriptAdd() override = default; + + Options *GetOptions() override { return &m_options; } - Options * - GetOptions () override - { - return &m_options; - } - protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_class_name(), - m_funct_name(), - m_short_help(), - m_synchronicity(eScriptedCommandSynchronicitySynchronous) - { - } + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_class_name(), m_funct_name(), m_short_help(), + m_synchronicity(eScriptedCommandSynchronicitySynchronous) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'f': + if (option_arg) + m_funct_name.assign(option_arg); + break; + case 'c': + if (option_arg) + m_class_name.assign(option_arg); + break; + case 'h': + if (option_arg) + m_short_help.assign(option_arg); + break; + case 's': + m_synchronicity = + (ScriptedCommandSynchronicity)Args::StringToOptionEnum( + option_arg, g_option_table[option_idx].enum_values, 0, error); + if (!error.Success()) + error.SetErrorStringWithFormat( + "unrecognized value for synchronicity '%s'", option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'f': - if (option_arg) - m_funct_name.assign(option_arg); - break; - case 'c': - if (option_arg) - m_class_name.assign(option_arg); - break; - case 'h': - if (option_arg) - m_short_help.assign(option_arg); - break; - case 's': - m_synchronicity = (ScriptedCommandSynchronicity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error); - if (!error.Success()) - error.SetErrorStringWithFormat ("unrecognized value for synchronicity '%s'", option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_class_name.clear(); - m_funct_name.clear(); - m_short_help.clear(); - m_synchronicity = eScriptedCommandSynchronicitySynchronous; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - std::string m_class_name; - std::string m_funct_name; - std::string m_short_help; - ScriptedCommandSynchronicity m_synchronicity; - }; - - void - IOHandlerActivated (IOHandler &io_handler) override - { - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString(g_python_command_instructions); - output_sp->Flush(); - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_class_name.clear(); + m_funct_name.clear(); + m_short_help.clear(); + m_synchronicity = eScriptedCommandSynchronicitySynchronous; } - - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override - { - StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (interpreter) - { - - StringList lines; - lines.SplitIntoLines(data); - if (lines.GetSize() > 0) - { - std::string funct_name_str; - if (interpreter->GenerateScriptAliasFunction (lines, funct_name_str)) - { - if (funct_name_str.empty()) - { - error_sp->Printf ("error: unable to obtain a function name, didn't add python command.\n"); - error_sp->Flush(); - } - else - { - // everything should be fine now, let's add this alias - - CommandObjectSP command_obj_sp(new CommandObjectPythonFunction (m_interpreter, - m_cmd_name, - funct_name_str.c_str(), - m_short_help, - m_synchronicity)); - - if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp, true)) - { - error_sp->Printf ("error: unable to add selected command, didn't add python command.\n"); - error_sp->Flush(); - } - } - } - else - { - error_sp->Printf ("error: unable to create function, didn't add python command.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: empty function, didn't add python command.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: script interpreter missing, didn't add python command.\n"); - error_sp->Flush(); - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; - io_handler.SetIsDone(true); + // Instance variables to hold the values for command options. + + std::string m_class_name; + std::string m_funct_name; + std::string m_short_help; + ScriptedCommandSynchronicity m_synchronicity; + }; + + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString(g_python_command_instructions); + output_sp->Flush(); } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) override { + StreamFileSP error_sp = io_handler.GetErrorStreamFile(); + + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (interpreter) { + + StringList lines; + lines.SplitIntoLines(data); + if (lines.GetSize() > 0) { + std::string funct_name_str; + if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) { + if (funct_name_str.empty()) { + error_sp->Printf("error: unable to obtain a function name, didn't " + "add python command.\n"); + error_sp->Flush(); + } else { + // everything should be fine now, let's add this alias + + CommandObjectSP command_obj_sp(new CommandObjectPythonFunction( + m_interpreter, m_cmd_name, funct_name_str.c_str(), m_short_help, + m_synchronicity)); + + if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp, + true)) { + error_sp->Printf("error: unable to add selected command, didn't " + "add python command.\n"); + error_sp->Flush(); + } + } + } else { + error_sp->Printf( + "error: unable to create function, didn't add python command.\n"); + error_sp->Flush(); + } + } else { + error_sp->Printf("error: empty function, didn't add python command.\n"); + error_sp->Flush(); + } + } else { + error_sp->Printf( + "error: script interpreter missing, didn't add python command.\n"); + error_sp->Flush(); + } + + io_handler.SetIsDone(true); + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (m_interpreter.GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) - { - result.AppendError ("only scripting language supported for scripted commands is currently Python"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - size_t argc = command.GetArgumentCount(); - - if (argc != 1) - { - result.AppendError ("'command script add' requires one argument"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Store the options in case we get multi-line input - m_cmd_name = command.GetArgumentAtIndex(0); - m_short_help.assign(m_options.m_short_help); - m_synchronicity = m_options.m_synchronicity; - - if (m_options.m_class_name.empty()) - { - if (m_options.m_funct_name.empty()) - { - m_interpreter.GetPythonCommandsFromIOHandler(" ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - nullptr); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions - } - else - { - CommandObjectSP new_cmd(new CommandObjectPythonFunction(m_interpreter, - m_cmd_name, - m_options.m_funct_name, - m_options.m_short_help, - m_synchronicity)); - if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError("cannot add command"); - result.SetStatus (eReturnStatusFailed); - } - } - } - else - { - ScriptInterpreter *interpreter = GetCommandInterpreter().GetScriptInterpreter(); - if (!interpreter) - { - result.AppendError("cannot find ScriptInterpreter"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - auto cmd_obj_sp = interpreter->CreateScriptCommandObject(m_options.m_class_name.c_str()); - if (!cmd_obj_sp) - { - result.AppendError("cannot create helper object"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - CommandObjectSP new_cmd(new CommandObjectScriptingObject(m_interpreter, - m_cmd_name, - cmd_obj_sp, - m_synchronicity)); - if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError("cannot add command"); - result.SetStatus (eReturnStatusFailed); - } - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (m_interpreter.GetDebugger().GetScriptLanguage() != + lldb::eScriptLanguagePython) { + result.AppendError("only scripting language supported for scripted " + "commands is currently Python"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + size_t argc = command.GetArgumentCount(); + + if (argc != 1) { + result.AppendError("'command script add' requires one argument"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + // Store the options in case we get multi-line input + m_cmd_name = command.GetArgumentAtIndex(0); + m_short_help.assign(m_options.m_short_help); + m_synchronicity = m_options.m_synchronicity; + + if (m_options.m_class_name.empty()) { + if (m_options.m_funct_name.empty()) { + m_interpreter.GetPythonCommandsFromIOHandler( + " ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + nullptr); // Baton for the "io_handler" that will be passed back + // into our IOHandlerDelegate functions + } else { + CommandObjectSP new_cmd(new CommandObjectPythonFunction( + m_interpreter, m_cmd_name, m_options.m_funct_name, + m_options.m_short_help, m_synchronicity)); + if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("cannot add command"); + result.SetStatus(eReturnStatusFailed); + } + } + } else { + ScriptInterpreter *interpreter = + GetCommandInterpreter().GetScriptInterpreter(); + if (!interpreter) { + result.AppendError("cannot find ScriptInterpreter"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + auto cmd_obj_sp = interpreter->CreateScriptCommandObject( + m_options.m_class_name.c_str()); + if (!cmd_obj_sp) { + result.AppendError("cannot create helper object"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + CommandObjectSP new_cmd(new CommandObjectScriptingObject( + m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity)); + if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("cannot add command"); + result.SetStatus(eReturnStatusFailed); + } } - - CommandOptions m_options; - std::string m_cmd_name; - std::string m_short_help; - ScriptedCommandSynchronicity m_synchronicity; -}; -static OptionEnumValueElement g_script_synchro_type[] = -{ - { eScriptedCommandSynchronicitySynchronous, "synchronous", "Run synchronous"}, - { eScriptedCommandSynchronicityAsynchronous, "asynchronous", "Run asynchronous"}, - { eScriptedCommandSynchronicityCurrentValue, "current", "Do not alter current setting"}, - { 0, nullptr, nullptr } + return result.Succeeded(); + } + + CommandOptions m_options; + std::string m_cmd_name; + std::string m_short_help; + ScriptedCommandSynchronicity m_synchronicity; }; +static OptionEnumValueElement g_script_synchro_type[] = { + {eScriptedCommandSynchronicitySynchronous, "synchronous", + "Run synchronous"}, + {eScriptedCommandSynchronicityAsynchronous, "asynchronous", + "Run asynchronous"}, + {eScriptedCommandSynchronicityCurrentValue, "current", + "Do not alter current setting"}, + {0, nullptr, nullptr}}; + OptionDefinition -CommandObjectCommandsScriptAdd::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectCommandsScriptAdd::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "function", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonFunction, "Name of the Python function to bind to this command name."}, {LLDB_OPT_SET_2, false, "class", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonClass, "Name of the Python class to bind to this command name."}, {LLDB_OPT_SET_1, false, "help" , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "The help text to display for this command."}, {LLDB_OPT_SET_ALL, false, "synchronicity", 's', OptionParser::eRequiredArgument, nullptr, g_script_synchro_type, 0, eArgTypeScriptedCommandSynchronicity, "Set the synchronicity of this command's executions with regard to LLDB event system."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectCommandsScriptList //------------------------------------------------------------------------- -class CommandObjectCommandsScriptList : public CommandObjectParsed -{ +class CommandObjectCommandsScriptList : public CommandObjectParsed { public: - CommandObjectCommandsScriptList(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command script list", - "List defined scripted commands.", - nullptr) - { - } + CommandObjectCommandsScriptList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command script list", + "List defined scripted commands.", nullptr) {} - ~CommandObjectCommandsScriptList() override = default; + ~CommandObjectCommandsScriptList() override = default; - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - m_interpreter.GetHelp(result, - CommandInterpreter::eCommandTypesUserDef); - - result.SetStatus (eReturnStatusSuccessFinishResult); - - return true; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef); + + result.SetStatus(eReturnStatusSuccessFinishResult); + + return true; + } }; //------------------------------------------------------------------------- // CommandObjectCommandsScriptClear //------------------------------------------------------------------------- -class CommandObjectCommandsScriptClear : public CommandObjectParsed -{ +class CommandObjectCommandsScriptClear : public CommandObjectParsed { public: - CommandObjectCommandsScriptClear(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command script clear", - "Delete all scripted commands.", - nullptr) - { - } + CommandObjectCommandsScriptClear(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command script clear", + "Delete all scripted commands.", nullptr) {} - ~CommandObjectCommandsScriptClear() override = default; + ~CommandObjectCommandsScriptClear() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - m_interpreter.RemoveAllUser(); - - result.SetStatus (eReturnStatusSuccessFinishResult); - - return true; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + m_interpreter.RemoveAllUser(); + + result.SetStatus(eReturnStatusSuccessFinishResult); + + return true; + } }; //------------------------------------------------------------------------- // CommandObjectCommandsScriptDelete //------------------------------------------------------------------------- -class CommandObjectCommandsScriptDelete : public CommandObjectParsed -{ +class CommandObjectCommandsScriptDelete : public CommandObjectParsed { public: - CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "command script delete", - "Delete a scripted command.", - nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentData cmd_arg; - - // Define the first (and only) variant of this arg. - cmd_arg.arg_type = eArgTypeCommandName; - cmd_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (cmd_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - } + CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "command script delete", + "Delete a scripted command.", nullptr) { + CommandArgumentEntry arg1; + CommandArgumentData cmd_arg; + + // Define the first (and only) variant of this arg. + cmd_arg.arg_type = eArgTypeCommandName; + cmd_arg.arg_repetition = eArgRepeatPlain; - ~CommandObjectCommandsScriptDelete() override = default; + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(cmd_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectCommandsScriptDelete() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - - size_t argc = command.GetArgumentCount(); - - if (argc != 1) - { - result.AppendError ("'command script delete' requires one argument"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const char* cmd_name = command.GetArgumentAtIndex(0); - - if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() && m_interpreter.UserCommandExists(cmd_name)) - { - m_interpreter.RemoveUser(cmd_name); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("command %s not found", cmd_name); - result.SetStatus (eReturnStatusFailed); - } - - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + + size_t argc = command.GetArgumentCount(); + + if (argc != 1) { + result.AppendError("'command script delete' requires one argument"); + result.SetStatus(eReturnStatusFailed); + return false; } + + const char *cmd_name = command.GetArgumentAtIndex(0); + + if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() && + m_interpreter.UserCommandExists(cmd_name)) { + m_interpreter.RemoveUser(cmd_name); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("command %s not found", cmd_name); + result.SetStatus(eReturnStatusFailed); + } + + return result.Succeeded(); + } }; #pragma mark CommandObjectMultiwordCommandsScript @@ -2274,22 +1937,30 @@ protected: // CommandObjectMultiwordCommandsScript //------------------------------------------------------------------------- -class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword -{ +class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword { public: - CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "command script", - "Commands for managing custom commands implemented by interpreter scripts.", - "command script []") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectCommandsScriptAdd (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectCommandsScriptDelete (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectCommandsScriptClear (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectCommandsScriptList (interpreter))); - LoadSubCommand ("import", CommandObjectSP (new CommandObjectCommandsScriptImport (interpreter))); - } - - ~CommandObjectMultiwordCommandsScript() override = default; + CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "command script", "Commands for managing custom " + "commands implemented by " + "interpreter scripts.", + "command script []") { + LoadSubCommand("add", CommandObjectSP( + new CommandObjectCommandsScriptAdd(interpreter))); + LoadSubCommand( + "delete", + CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter))); + LoadSubCommand( + "clear", + CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter))); + LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList( + interpreter))); + LoadSubCommand( + "import", + CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter))); + } + + ~CommandObjectMultiwordCommandsScript() override = default; }; #pragma mark CommandObjectMultiwordCommands @@ -2298,17 +1969,26 @@ public: // CommandObjectMultiwordCommands //------------------------------------------------------------------------- -CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "command", "Commands for managing custom LLDB commands.", - "command []") -{ - LoadSubCommand ("source", CommandObjectSP (new CommandObjectCommandsSource (interpreter))); - LoadSubCommand ("alias", CommandObjectSP (new CommandObjectCommandsAlias (interpreter))); - LoadSubCommand ("unalias", CommandObjectSP (new CommandObjectCommandsUnalias (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectCommandsDelete (interpreter))); - LoadSubCommand ("regex", CommandObjectSP (new CommandObjectCommandsAddRegex (interpreter))); - LoadSubCommand ("history", CommandObjectSP (new CommandObjectCommandsHistory (interpreter))); - LoadSubCommand ("script", CommandObjectSP (new CommandObjectMultiwordCommandsScript (interpreter))); +CommandObjectMultiwordCommands::CommandObjectMultiwordCommands( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "command", + "Commands for managing custom LLDB commands.", + "command []") { + LoadSubCommand("source", + CommandObjectSP(new CommandObjectCommandsSource(interpreter))); + LoadSubCommand("alias", + CommandObjectSP(new CommandObjectCommandsAlias(interpreter))); + LoadSubCommand("unalias", CommandObjectSP( + new CommandObjectCommandsUnalias(interpreter))); + LoadSubCommand("delete", + CommandObjectSP(new CommandObjectCommandsDelete(interpreter))); + LoadSubCommand( + "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter))); + LoadSubCommand("history", CommandObjectSP( + new CommandObjectCommandsHistory(interpreter))); + LoadSubCommand( + "script", + CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter))); } CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default; diff --git a/lldb/source/Commands/CommandObjectCommands.h b/lldb/source/Commands/CommandObjectCommands.h index c12c71051ff..a5ef777aa98 100644 --- a/lldb/source/Commands/CommandObjectCommands.h +++ b/lldb/source/Commands/CommandObjectCommands.h @@ -1,4 +1,5 @@ -//===-- CommandObjectCommands.h -----------------------------------*- C++ -*-===// +//===-- CommandObjectCommands.h -----------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -14,9 +15,9 @@ // C++ Includes // Other libraries and framework includes // Project includes +#include "lldb/Core/STLUtils.h" #include "lldb/Interpreter/CommandObject.h" #include "lldb/Interpreter/CommandObjectMultiword.h" -#include "lldb/Core/STLUtils.h" namespace lldb_private { @@ -24,13 +25,11 @@ namespace lldb_private { // CommandObjectMultiwordCommands //------------------------------------------------------------------------- -class CommandObjectMultiwordCommands : public CommandObjectMultiword -{ +class CommandObjectMultiwordCommands : public CommandObjectMultiword { public: + CommandObjectMultiwordCommands(CommandInterpreter &interpreter); - CommandObjectMultiwordCommands (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordCommands() override; + ~CommandObjectMultiwordCommands() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectDisassemble.cpp b/lldb/source/Commands/CommandObjectDisassemble.cpp index 796db6152d8..7a1291b84a1 100644 --- a/lldb/source/Commands/CommandObjectDisassemble.cpp +++ b/lldb/source/Commands/CommandObjectDisassemble.cpp @@ -29,221 +29,191 @@ #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 -#define DEFAULT_DISASM_NUM_INS 4 +#define DEFAULT_DISASM_NUM_INS 4 using namespace lldb; using namespace lldb_private; -CommandObjectDisassemble::CommandOptions::CommandOptions() : - Options(), - num_lines_context(0), - num_instructions (0), - func_name(), - current_function (false), - start_addr(), - end_addr (), - at_pc (false), - frame_line (false), - plugin_name (), - flavor_string(), - arch(), - some_location_specified (false), - symbol_containing_addr () -{ - OptionParsingStarting(nullptr); +CommandObjectDisassemble::CommandOptions::CommandOptions() + : Options(), num_lines_context(0), num_instructions(0), func_name(), + current_function(false), start_addr(), end_addr(), at_pc(false), + frame_line(false), plugin_name(), flavor_string(), arch(), + some_location_specified(false), symbol_containing_addr() { + OptionParsingStarting(nullptr); } CommandObjectDisassemble::CommandOptions::~CommandOptions() = default; -Error -CommandObjectDisassemble::CommandOptions::SetOptionValue(uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) -{ - Error error; - - const int short_option = m_getopt_table[option_idx].val; - - bool success; - - switch (short_option) - { - case 'm': - show_mixed = true; - break; - - case 'C': - num_lines_context = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat ("invalid num context lines string: \"%s\"", option_arg); - break; - - case 'c': - num_instructions = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat ("invalid num of instructions string: \"%s\"", option_arg); - break; - - case 'b': - show_bytes = true; - break; - - case 's': - { - start_addr = Args::StringToAddress(execution_context, option_arg, - LLDB_INVALID_ADDRESS, &error); - if (start_addr != LLDB_INVALID_ADDRESS) - some_location_specified = true; - } - break; - case 'e': - { - end_addr = Args::StringToAddress(execution_context, option_arg, - LLDB_INVALID_ADDRESS, &error); - if (end_addr != LLDB_INVALID_ADDRESS) - some_location_specified = true; - } - break; - - case 'n': - func_name.assign (option_arg); - some_location_specified = true; - break; - - case 'p': - at_pc = true; - some_location_specified = true; - break; - - case 'l': - frame_line = true; - // Disassemble the current source line kind of implies showing mixed - // source code context. - show_mixed = true; - some_location_specified = true; - break; - - case 'P': - plugin_name.assign (option_arg); - break; - - case 'F': - { - TargetSP target_sp = execution_context ? - execution_context->GetTargetSP() : TargetSP(); - if (target_sp && - (target_sp->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 - || target_sp->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86_64)) - { - flavor_string.assign (option_arg); - } - else - error.SetErrorStringWithFormat("Disassembler flavors are currently only supported for x86 and x86_64 targets."); - break; - } - - case 'r': - raw = true; - break; - - case 'f': - current_function = true; - some_location_specified = true; - break; - - case 'A': - if (execution_context) - { - auto target_sp = execution_context ? - execution_context->GetTargetSP() : TargetSP(); - auto platform_sp = - target_sp ? target_sp->GetPlatform() : PlatformSP(); - if (!arch.SetTriple (option_arg, platform_sp.get())) - arch.SetTriple (option_arg); - } - break; - - case 'a': - { - symbol_containing_addr = - Args::StringToAddress(execution_context,option_arg, - LLDB_INVALID_ADDRESS, &error); - if (symbol_containing_addr != LLDB_INVALID_ADDRESS) - { - some_location_specified = true; - } - } - break; +Error CommandObjectDisassemble::CommandOptions::SetOptionValue( + uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) { + Error error; + + const int short_option = m_getopt_table[option_idx].val; + + bool success; + + switch (short_option) { + case 'm': + show_mixed = true; + break; + + case 'C': + num_lines_context = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid num context lines string: \"%s\"", + option_arg); + break; + + case 'c': + num_instructions = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid num of instructions string: \"%s\"", option_arg); + break; + + case 'b': + show_bytes = true; + break; + + case 's': { + start_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + if (start_addr != LLDB_INVALID_ADDRESS) + some_location_specified = true; + } break; + case 'e': { + end_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + if (end_addr != LLDB_INVALID_ADDRESS) + some_location_specified = true; + } break; + + case 'n': + func_name.assign(option_arg); + some_location_specified = true; + break; + + case 'p': + at_pc = true; + some_location_specified = true; + break; + + case 'l': + frame_line = true; + // Disassemble the current source line kind of implies showing mixed + // source code context. + show_mixed = true; + some_location_specified = true; + break; + + case 'P': + plugin_name.assign(option_arg); + break; + + case 'F': { + TargetSP target_sp = + execution_context ? execution_context->GetTargetSP() : TargetSP(); + if (target_sp && (target_sp->GetArchitecture().GetTriple().getArch() == + llvm::Triple::x86 || + target_sp->GetArchitecture().GetTriple().getArch() == + llvm::Triple::x86_64)) { + flavor_string.assign(option_arg); + } else + error.SetErrorStringWithFormat("Disassembler flavors are currently only " + "supported for x86 and x86_64 targets."); + break; + } + + case 'r': + raw = true; + break; + + case 'f': + current_function = true; + some_location_specified = true; + break; + + case 'A': + if (execution_context) { + auto target_sp = + execution_context ? execution_context->GetTargetSP() : TargetSP(); + auto platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP(); + if (!arch.SetTriple(option_arg, platform_sp.get())) + arch.SetTriple(option_arg); + } + break; - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; + case 'a': { + symbol_containing_addr = Args::StringToAddress( + execution_context, option_arg, LLDB_INVALID_ADDRESS, &error); + if (symbol_containing_addr != LLDB_INVALID_ADDRESS) { + some_location_specified = true; } + } break; + + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } - return error; + return error; } -void -CommandObjectDisassemble::CommandOptions::OptionParsingStarting( - ExecutionContext *execution_context) -{ - show_mixed = false; - show_bytes = false; - num_lines_context = 0; - num_instructions = 0; - func_name.clear(); - current_function = false; - at_pc = false; - frame_line = false; - start_addr = LLDB_INVALID_ADDRESS; - end_addr = LLDB_INVALID_ADDRESS; - symbol_containing_addr = LLDB_INVALID_ADDRESS; - raw = false; - plugin_name.clear(); - - Target *target = - execution_context ? execution_context->GetTargetPtr() : nullptr; - - // This is a hack till we get the ability to specify features based on architecture. For now GetDisassemblyFlavor - // is really only valid for x86 (and for the llvm assembler plugin, but I'm papering over that since that is the - // only disassembler plugin we have... - if (target) - { - if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 - || target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86_64) - { - flavor_string.assign(target->GetDisassemblyFlavor()); - } - else - flavor_string.assign ("default"); - - } - else - flavor_string.assign("default"); - - arch.Clear(); - some_location_specified = false; +void CommandObjectDisassemble::CommandOptions::OptionParsingStarting( + ExecutionContext *execution_context) { + show_mixed = false; + show_bytes = false; + num_lines_context = 0; + num_instructions = 0; + func_name.clear(); + current_function = false; + at_pc = false; + frame_line = false; + start_addr = LLDB_INVALID_ADDRESS; + end_addr = LLDB_INVALID_ADDRESS; + symbol_containing_addr = LLDB_INVALID_ADDRESS; + raw = false; + plugin_name.clear(); + + Target *target = + execution_context ? execution_context->GetTargetPtr() : nullptr; + + // This is a hack till we get the ability to specify features based on + // architecture. For now GetDisassemblyFlavor + // is really only valid for x86 (and for the llvm assembler plugin, but I'm + // papering over that since that is the + // only disassembler plugin we have... + if (target) { + if (target->GetArchitecture().GetTriple().getArch() == llvm::Triple::x86 || + target->GetArchitecture().GetTriple().getArch() == + llvm::Triple::x86_64) { + flavor_string.assign(target->GetDisassemblyFlavor()); + } else + flavor_string.assign("default"); + + } else + flavor_string.assign("default"); + + arch.Clear(); + some_location_specified = false; } -Error -CommandObjectDisassemble::CommandOptions::OptionParsingFinished( - ExecutionContext *execution_context) -{ - if (!some_location_specified) - current_function = true; - return Error(); +Error CommandObjectDisassemble::CommandOptions::OptionParsingFinished( + ExecutionContext *execution_context) { + if (!some_location_specified) + current_function = true; + return Error(); } -const OptionDefinition* -CommandObjectDisassemble::CommandOptions::GetDefinitions () -{ - return g_option_table; +const OptionDefinition * +CommandObjectDisassemble::CommandOptions::GetDefinitions() { + return g_option_table; } -OptionDefinition -CommandObjectDisassemble::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "bytes", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, {LLDB_OPT_SET_ALL, false, "context", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNumLines, "Number of context lines of source to show."}, {LLDB_OPT_SET_ALL, false, "mixed", 'm', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable mixed source and assembly display."}, @@ -267,367 +237,330 @@ CommandObjectDisassemble::CommandOptions::g_option_table[] = "table information, else disassemble around the pc."}, {LLDB_OPT_SET_7, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Disassemble function containing this address."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- -CommandObjectDisassemble::CommandObjectDisassemble(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "disassemble", "Disassemble specified instructions in the current target. " - "Defaults to the current function for the current thread and " - "stack frame.", - "disassemble []"), - m_options() -{ -} +CommandObjectDisassemble::CommandObjectDisassemble( + CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "disassemble", + "Disassemble specified instructions in the current target. " + "Defaults to the current function for the current thread and " + "stack frame.", + "disassemble []"), + m_options() {} CommandObjectDisassemble::~CommandObjectDisassemble() = default; -bool -CommandObjectDisassemble::DoExecute (Args& command, CommandReturnObject &result) -{ - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; +bool CommandObjectDisassemble::DoExecute(Args &command, + CommandReturnObject &result) { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (!m_options.arch.IsValid()) + m_options.arch = target->GetArchitecture(); + + if (!m_options.arch.IsValid()) { + result.AppendError( + "use the --arch option or set the target architecture to disassemble"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const char *plugin_name = m_options.GetPluginName(); + const char *flavor_string = m_options.GetFlavorString(); + + DisassemblerSP disassembler = + Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name); + + if (!disassembler) { + if (plugin_name) { + result.AppendErrorWithFormat( + "Unable to find Disassembler plug-in named '%s' that supports the " + "'%s' architecture.\n", + plugin_name, m_options.arch.GetArchitectureName()); + } else + result.AppendErrorWithFormat( + "Unable to find Disassembler plug-in for the '%s' architecture.\n", + m_options.arch.GetArchitectureName()); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (flavor_string != nullptr && + !disassembler->FlavorValidForArchSpec(m_options.arch, + flavor_string)) + result.AppendWarningWithFormat( + "invalid disassembler flavor \"%s\", using default.\n", flavor_string); + + result.SetStatus(eReturnStatusSuccessFinishResult); + + if (command.GetArgumentCount() != 0) { + result.AppendErrorWithFormat( + "\"disassemble\" arguments are specified as options.\n"); + const int terminal_width = + GetCommandInterpreter().GetDebugger().GetTerminalWidth(); + GetOptions()->GenerateOptionUsage(result.GetErrorStream(), this, + terminal_width); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_options.show_mixed && m_options.num_lines_context == 0) + m_options.num_lines_context = 1; + + // Always show the PC in the disassembly + uint32_t options = Disassembler::eOptionMarkPCAddress; + + // Mark the source line for the current PC only if we are doing mixed source + // and assembly + if (m_options.show_mixed) + options |= Disassembler::eOptionMarkPCSourceLine; + + if (m_options.show_bytes) + options |= Disassembler::eOptionShowBytes; + + if (m_options.raw) + options |= Disassembler::eOptionRawOuput; + + if (!m_options.func_name.empty()) { + ConstString name(m_options.func_name.c_str()); + + if (Disassembler::Disassemble( + m_interpreter.GetDebugger(), m_options.arch, plugin_name, + flavor_string, m_exe_ctx, name, + nullptr, // Module * + m_options.num_instructions, + m_options.show_mixed ? m_options.num_lines_context : 0, options, + result.GetOutputStream())) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Unable to find symbol with name '%s'.\n", + name.GetCString()); + result.SetStatus(eReturnStatusFailed); } - if (!m_options.arch.IsValid()) - m_options.arch = target->GetArchitecture(); - - if (!m_options.arch.IsValid()) - { - result.AppendError ("use the --arch option or set the target architecture to disassemble"); - result.SetStatus (eReturnStatusFailed); + } else { + std::vector ranges; + AddressRange range; + StackFrame *frame = m_exe_ctx.GetFramePtr(); + if (m_options.frame_line) { + if (frame == nullptr) { + result.AppendError("Cannot disassemble around the current line without " + "a selected frame.\n"); + result.SetStatus(eReturnStatusFailed); return false; - } - - const char *plugin_name = m_options.GetPluginName (); - const char *flavor_string = m_options.GetFlavorString(); - - DisassemblerSP disassembler = Disassembler::FindPlugin(m_options.arch, flavor_string, plugin_name); - - if (!disassembler) - { - if (plugin_name) - { - result.AppendErrorWithFormat ("Unable to find Disassembler plug-in named '%s' that supports the '%s' architecture.\n", - plugin_name, - m_options.arch.GetArchitectureName()); - } - else - result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for the '%s' architecture.\n", - m_options.arch.GetArchitectureName()); - result.SetStatus (eReturnStatusFailed); + } + LineEntry pc_line_entry( + frame->GetSymbolContext(eSymbolContextLineEntry).line_entry); + if (pc_line_entry.IsValid()) { + range = pc_line_entry.range; + } else { + m_options.at_pc = + true; // No line entry, so just disassemble around the current pc + m_options.show_mixed = false; + } + } else if (m_options.current_function) { + if (frame == nullptr) { + result.AppendError("Cannot disassemble around the current function " + "without a selected frame.\n"); + result.SetStatus(eReturnStatusFailed); return false; + } + Symbol *symbol = frame->GetSymbolContext(eSymbolContextSymbol).symbol; + if (symbol) { + range.GetBaseAddress() = symbol->GetAddress(); + range.SetByteSize(symbol->GetByteSize()); + } } - else if (flavor_string != nullptr && !disassembler->FlavorValidForArchSpec(m_options.arch, flavor_string)) - result.AppendWarningWithFormat("invalid disassembler flavor \"%s\", using default.\n", flavor_string); - - result.SetStatus (eReturnStatusSuccessFinishResult); - - if (command.GetArgumentCount() != 0) - { - result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); - const int terminal_width = - GetCommandInterpreter().GetDebugger().GetTerminalWidth(); - GetOptions()->GenerateOptionUsage(result.GetErrorStream(), this, - terminal_width); - result.SetStatus (eReturnStatusFailed); - return false; - } - - if (m_options.show_mixed && m_options.num_lines_context == 0) - m_options.num_lines_context = 1; - - // Always show the PC in the disassembly - uint32_t options = Disassembler::eOptionMarkPCAddress; - - // Mark the source line for the current PC only if we are doing mixed source and assembly - if (m_options.show_mixed) - options |= Disassembler::eOptionMarkPCSourceLine; - - if (m_options.show_bytes) - options |= Disassembler::eOptionShowBytes; - - if (m_options.raw) - options |= Disassembler::eOptionRawOuput; - - if (!m_options.func_name.empty()) - { - ConstString name(m_options.func_name.c_str()); - - if (Disassembler::Disassemble(m_interpreter.GetDebugger(), - m_options.arch, - plugin_name, - flavor_string, - m_exe_ctx, - name, - nullptr, // Module * - m_options.num_instructions, - m_options.show_mixed ? m_options.num_lines_context : 0, - options, - result.GetOutputStream())) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); - result.SetStatus (eReturnStatusFailed); + + // Did the "m_options.frame_line" find a valid range already? If so + // skip the rest... + if (range.GetByteSize() == 0) { + if (m_options.at_pc) { + if (frame == nullptr) { + result.AppendError("Cannot disassemble around the current PC without " + "a selected frame.\n"); + result.SetStatus(eReturnStatusFailed); + return false; } - } - else - { - std::vector ranges; - AddressRange range; - StackFrame *frame = m_exe_ctx.GetFramePtr(); - if (m_options.frame_line) - { - if (frame == nullptr) - { - result.AppendError ("Cannot disassemble around the current line without a selected frame.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - LineEntry pc_line_entry (frame->GetSymbolContext(eSymbolContextLineEntry).line_entry); - if (pc_line_entry.IsValid()) - { - range = pc_line_entry.range; - } - else - { - m_options.at_pc = true; // No line entry, so just disassemble around the current pc - m_options.show_mixed = false; - } + range.GetBaseAddress() = frame->GetFrameCodeAddress(); + if (m_options.num_instructions == 0) { + // Disassembling at the PC always disassembles some number of + // instructions (not the whole function). + m_options.num_instructions = DEFAULT_DISASM_NUM_INS; } - else if (m_options.current_function) - { - if (frame == nullptr) - { - result.AppendError ("Cannot disassemble around the current function without a selected frame.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - Symbol *symbol = frame->GetSymbolContext(eSymbolContextSymbol).symbol; - if (symbol) - { - range.GetBaseAddress() = symbol->GetAddress(); - range.SetByteSize(symbol->GetByteSize()); + ranges.push_back(range); + } else { + range.GetBaseAddress().SetOffset(m_options.start_addr); + if (range.GetBaseAddress().IsValid()) { + if (m_options.end_addr != LLDB_INVALID_ADDRESS) { + if (m_options.end_addr <= m_options.start_addr) { + result.AppendErrorWithFormat( + "End address before start address.\n"); + result.SetStatus(eReturnStatusFailed); + return false; } - } - - // Did the "m_options.frame_line" find a valid range already? If so - // skip the rest... - if (range.GetByteSize() == 0) - { - if (m_options.at_pc) - { - if (frame == nullptr) - { - result.AppendError ("Cannot disassemble around the current PC without a selected frame.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - range.GetBaseAddress() = frame->GetFrameCodeAddress(); - if (m_options.num_instructions == 0) - { - // Disassembling at the PC always disassembles some number of instructions (not the whole function). - m_options.num_instructions = DEFAULT_DISASM_NUM_INS; + range.SetByteSize(m_options.end_addr - m_options.start_addr); + } + ranges.push_back(range); + } else { + if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS && + target) { + if (!target->GetSectionLoadList().IsEmpty()) { + bool failed = false; + Address symbol_containing_address; + if (target->GetSectionLoadList().ResolveLoadAddress( + m_options.symbol_containing_addr, + symbol_containing_address)) { + ModuleSP module_sp(symbol_containing_address.GetModule()); + SymbolContext sc; + bool resolve_tail_call_address = true; // PC can be one past the + // address range of the + // function. + module_sp->ResolveSymbolContextForAddress( + symbol_containing_address, eSymbolContextEverything, sc, + resolve_tail_call_address); + if (sc.function || sc.symbol) { + sc.GetAddressRange(eSymbolContextFunction | + eSymbolContextSymbol, + 0, false, range); + } else { + failed = true; } - ranges.push_back(range); - } - else - { - range.GetBaseAddress().SetOffset (m_options.start_addr); - if (range.GetBaseAddress().IsValid()) - { - if (m_options.end_addr != LLDB_INVALID_ADDRESS) - { - if (m_options.end_addr <= m_options.start_addr) - { - result.AppendErrorWithFormat ("End address before start address.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - range.SetByteSize (m_options.end_addr - m_options.start_addr); - } + } else { + failed = true; + } + if (failed) { + result.AppendErrorWithFormat( + "Could not find function bounds for address 0x%" PRIx64 + "\n", + m_options.symbol_containing_addr); + result.SetStatus(eReturnStatusFailed); + return false; + } + ranges.push_back(range); + } else { + for (lldb::ModuleSP module_sp : target->GetImages().Modules()) { + lldb::addr_t file_addr = m_options.symbol_containing_addr; + Address file_address; + if (module_sp->ResolveFileAddress(file_addr, file_address)) { + SymbolContext sc; + bool resolve_tail_call_address = true; // PC can be one past + // the address range of + // the function. + module_sp->ResolveSymbolContextForAddress( + file_address, eSymbolContextEverything, sc, + resolve_tail_call_address); + if (sc.function || sc.symbol) { + sc.GetAddressRange(eSymbolContextFunction | + eSymbolContextSymbol, + 0, false, range); ranges.push_back(range); + } } - else - { - if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS - && target) - { - if (!target->GetSectionLoadList().IsEmpty()) - { - bool failed = false; - Address symbol_containing_address; - if (target->GetSectionLoadList().ResolveLoadAddress (m_options.symbol_containing_addr, symbol_containing_address)) - { - ModuleSP module_sp (symbol_containing_address.GetModule()); - SymbolContext sc; - bool resolve_tail_call_address = true; // PC can be one past the address range of the function. - module_sp->ResolveSymbolContextForAddress (symbol_containing_address, eSymbolContextEverything, sc, - resolve_tail_call_address); - if (sc.function || sc.symbol) - { - sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, range); - } - else - { - failed = true; - } - } - else - { - failed = true; - } - if (failed) - { - result.AppendErrorWithFormat ("Could not find function bounds for address 0x%" PRIx64 "\n", m_options.symbol_containing_addr); - result.SetStatus (eReturnStatusFailed); - return false; - } - ranges.push_back(range); - } - else - { - for (lldb::ModuleSP module_sp : target->GetImages().Modules()) - { - lldb::addr_t file_addr = m_options.symbol_containing_addr; - Address file_address; - if (module_sp->ResolveFileAddress(file_addr, file_address)) - { - SymbolContext sc; - bool resolve_tail_call_address = true; // PC can be one past the address range of the function. - module_sp->ResolveSymbolContextForAddress (file_address, eSymbolContextEverything, sc, resolve_tail_call_address); - if (sc.function || sc.symbol) - { - sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, range); - ranges.push_back(range); - } - } - } - } - } - } + } } + } } - else - ranges.push_back(range); - - if (m_options.num_instructions != 0) - { - if (ranges.empty()) - { - // The default action is to disassemble the current frame function. - if (frame) - { - SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); - if (sc.function) - range.GetBaseAddress() = sc.function->GetAddressRange().GetBaseAddress(); - else if (sc.symbol && sc.symbol->ValueIsAddress()) - range.GetBaseAddress() = sc.symbol->GetAddress(); - else - range.GetBaseAddress() = frame->GetFrameCodeAddress(); - } - - if (!range.GetBaseAddress().IsValid()) - { - result.AppendError ("invalid frame"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - - bool print_sc_header = ranges.size() > 1; - for (AddressRange cur_range : ranges) - { - if (Disassembler::Disassemble (m_interpreter.GetDebugger(), - m_options.arch, - plugin_name, - flavor_string, - m_exe_ctx, - cur_range.GetBaseAddress(), - m_options.num_instructions, - m_options.show_mixed ? m_options.num_lines_context : 0, - options, - result.GetOutputStream())) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - if (m_options.start_addr != LLDB_INVALID_ADDRESS) - result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", m_options.start_addr); - else if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS) - result.AppendErrorWithFormat ("Failed to disassemble memory in function at 0x%8.8" PRIx64 ".\n", m_options.symbol_containing_addr); - result.SetStatus (eReturnStatusFailed); - } - } - if (print_sc_header) - result.AppendMessage("\n"); + } + } else + ranges.push_back(range); + + if (m_options.num_instructions != 0) { + if (ranges.empty()) { + // The default action is to disassemble the current frame function. + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextSymbol)); + if (sc.function) + range.GetBaseAddress() = + sc.function->GetAddressRange().GetBaseAddress(); + else if (sc.symbol && sc.symbol->ValueIsAddress()) + range.GetBaseAddress() = sc.symbol->GetAddress(); + else + range.GetBaseAddress() = frame->GetFrameCodeAddress(); } - else - { - if (ranges.empty()) - { - // The default action is to disassemble the current frame function. - if (frame) - { - SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); - if (sc.function) - range = sc.function->GetAddressRange(); - else if (sc.symbol && sc.symbol->ValueIsAddress()) - { - range.GetBaseAddress() = sc.symbol->GetAddress(); - range.SetByteSize (sc.symbol->GetByteSize()); - } - else - range.GetBaseAddress() = frame->GetFrameCodeAddress(); - } - else - { - result.AppendError ("invalid frame"); - result.SetStatus (eReturnStatusFailed); - return false; - } - ranges.push_back(range); - } - - bool print_sc_header = ranges.size() > 1; - for (AddressRange cur_range : ranges) - { - if (cur_range.GetByteSize() == 0) - cur_range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); - - if (Disassembler::Disassemble (m_interpreter.GetDebugger(), - m_options.arch, - plugin_name, - flavor_string, - m_exe_ctx, - cur_range, - m_options.num_instructions, - m_options.show_mixed ? m_options.num_lines_context : 0, - options, - result.GetOutputStream())) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", m_options.start_addr); - result.SetStatus (eReturnStatusFailed); - } - if (print_sc_header) - result.AppendMessage("\n"); - } + + if (!range.GetBaseAddress().IsValid()) { + result.AppendError("invalid frame"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + bool print_sc_header = ranges.size() > 1; + for (AddressRange cur_range : ranges) { + if (Disassembler::Disassemble( + m_interpreter.GetDebugger(), m_options.arch, plugin_name, + flavor_string, m_exe_ctx, cur_range.GetBaseAddress(), + m_options.num_instructions, + m_options.show_mixed ? m_options.num_lines_context : 0, options, + result.GetOutputStream())) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + if (m_options.start_addr != LLDB_INVALID_ADDRESS) + result.AppendErrorWithFormat( + "Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", + m_options.start_addr); + else if (m_options.symbol_containing_addr != LLDB_INVALID_ADDRESS) + result.AppendErrorWithFormat( + "Failed to disassemble memory in function at 0x%8.8" PRIx64 + ".\n", + m_options.symbol_containing_addr); + result.SetStatus(eReturnStatusFailed); + } + } + if (print_sc_header) + result.AppendMessage("\n"); + } else { + if (ranges.empty()) { + // The default action is to disassemble the current frame function. + if (frame) { + SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | + eSymbolContextSymbol)); + if (sc.function) + range = sc.function->GetAddressRange(); + else if (sc.symbol && sc.symbol->ValueIsAddress()) { + range.GetBaseAddress() = sc.symbol->GetAddress(); + range.SetByteSize(sc.symbol->GetByteSize()); + } else + range.GetBaseAddress() = frame->GetFrameCodeAddress(); + } else { + result.AppendError("invalid frame"); + result.SetStatus(eReturnStatusFailed); + return false; + } + ranges.push_back(range); + } + + bool print_sc_header = ranges.size() > 1; + for (AddressRange cur_range : ranges) { + if (cur_range.GetByteSize() == 0) + cur_range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); + + if (Disassembler::Disassemble( + m_interpreter.GetDebugger(), m_options.arch, plugin_name, + flavor_string, m_exe_ctx, cur_range, m_options.num_instructions, + m_options.show_mixed ? m_options.num_lines_context : 0, options, + result.GetOutputStream())) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "Failed to disassemble memory at 0x%8.8" PRIx64 ".\n", + m_options.start_addr); + result.SetStatus(eReturnStatusFailed); } + if (print_sc_header) + result.AppendMessage("\n"); + } } + } - return result.Succeeded(); + return result.Succeeded(); } diff --git a/lldb/source/Commands/CommandObjectDisassemble.h b/lldb/source/Commands/CommandObjectDisassemble.h index fa951227c99..a4d132aa1e4 100644 --- a/lldb/source/Commands/CommandObjectDisassemble.h +++ b/lldb/source/Commands/CommandObjectDisassemble.h @@ -24,79 +24,64 @@ namespace lldb_private { // CommandObjectDisassemble //------------------------------------------------------------------------- -class CommandObjectDisassemble : public CommandObjectParsed -{ +class CommandObjectDisassemble : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions(); - - ~CommandOptions() override; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override; - - void - OptionParsingStarting(ExecutionContext *execution_context) override; - - const OptionDefinition* - GetDefinitions() override; - - const char * - GetPluginName () - { - return (plugin_name.empty() ? nullptr : plugin_name.c_str()); - } - - const char * - GetFlavorString () - { - if (flavor_string.empty() || flavor_string == "default") - return nullptr; - return flavor_string.c_str(); - } - - Error - OptionParsingFinished(ExecutionContext *execution_context) override; - - bool show_mixed; // Show mixed source/assembly - bool show_bytes; - uint32_t num_lines_context; - uint32_t num_instructions; - bool raw; - std::string func_name; - bool current_function; - lldb::addr_t start_addr; - lldb::addr_t end_addr; - bool at_pc; - bool frame_line; - std::string plugin_name; - std::string flavor_string; - ArchSpec arch; - bool some_location_specified; // If no location was specified, we'll select "at_pc". This should be set - // in SetOptionValue if anything the selects a location is set. - lldb::addr_t symbol_containing_addr; - static OptionDefinition g_option_table[]; - }; - - CommandObjectDisassemble (CommandInterpreter &interpreter); - - ~CommandObjectDisassemble() override; - - Options * - GetOptions() override - { - return &m_options; + class CommandOptions : public Options { + public: + CommandOptions(); + + ~CommandOptions() override; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override; + + void OptionParsingStarting(ExecutionContext *execution_context) override; + + const OptionDefinition *GetDefinitions() override; + + const char *GetPluginName() { + return (plugin_name.empty() ? nullptr : plugin_name.c_str()); + } + + const char *GetFlavorString() { + if (flavor_string.empty() || flavor_string == "default") + return nullptr; + return flavor_string.c_str(); } + Error OptionParsingFinished(ExecutionContext *execution_context) override; + + bool show_mixed; // Show mixed source/assembly + bool show_bytes; + uint32_t num_lines_context; + uint32_t num_instructions; + bool raw; + std::string func_name; + bool current_function; + lldb::addr_t start_addr; + lldb::addr_t end_addr; + bool at_pc; + bool frame_line; + std::string plugin_name; + std::string flavor_string; + ArchSpec arch; + bool some_location_specified; // If no location was specified, we'll select + // "at_pc". This should be set + // in SetOptionValue if anything the selects a location is set. + lldb::addr_t symbol_containing_addr; + static OptionDefinition g_option_table[]; + }; + + CommandObjectDisassemble(CommandInterpreter &interpreter); + + ~CommandObjectDisassemble() override; + + Options *GetOptions() override { return &m_options; } + protected: - bool - DoExecute(Args& command, - CommandReturnObject &result) override; + bool DoExecute(Args &command, CommandReturnObject &result) override; - CommandOptions m_options; + CommandOptions m_options; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectExpression.cpp b/lldb/source/Commands/CommandObjectExpression.cpp index b82a4fdeb9e..be4f54616c5 100644 --- a/lldb/source/Commands/CommandObjectExpression.cpp +++ b/lldb/source/Commands/CommandObjectExpression.cpp @@ -15,21 +15,21 @@ // Project includes #include "CommandObjectExpression.h" +#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" +#include "lldb/Core/Debugger.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/DataFormatters/ValueObjectPrinter.h" -#include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h" -#include "lldb/Expression/UserExpression.h" #include "lldb/Expression/DWARFExpression.h" #include "lldb/Expression/REPL.h" +#include "lldb/Expression/UserExpression.h" #include "lldb/Host/Host.h" #include "lldb/Host/StringConvert.h" -#include "lldb/Core/Debugger.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Target/Language.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/Variable.h" +#include "lldb/Target/Language.h" #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" @@ -38,24 +38,19 @@ using namespace lldb; using namespace lldb_private; -CommandObjectExpression::CommandOptions::CommandOptions () : - OptionGroup() -{ -} +CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {} CommandObjectExpression::CommandOptions::~CommandOptions() = default; -static OptionEnumValueElement g_description_verbosity_type[] = -{ - { eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", "Only show the description string"}, - { eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", "Show the full output, including persistent variable's name and type"}, - { 0, nullptr, nullptr } -}; +static OptionEnumValueElement g_description_verbosity_type[] = { + {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact", + "Only show the description string"}, + {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full", + "Show the full output, including persistent variable's name and type"}, + {0, nullptr, nullptr}}; -OptionDefinition -CommandObjectExpression::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectExpression::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Should we run all threads if the execution doesn't complete on one thread."}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Ignore breakpoint hits while running expressions"}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Timeout value (in microseconds) for running the expression."}, @@ -71,604 +66,572 @@ CommandObjectExpression::CommandOptions::g_option_table[] = "executed."}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "allow-jit", 'j', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Controls whether the expression can fall back to being JITted if it's not supported by " "the interpreter (defaults to true)."} - // clang-format on + // clang-format on }; -uint32_t -CommandObjectExpression::CommandOptions::GetNumDefinitions () -{ - return llvm::array_lengthof(g_option_table); +uint32_t CommandObjectExpression::CommandOptions::GetNumDefinitions() { + return llvm::array_lengthof(g_option_table); } -Error -CommandObjectExpression::CommandOptions::SetOptionValue (uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) -{ - Error error; - - const int short_option = g_option_table[option_idx].short_option; - - switch (short_option) - { - case 'l': - language = Language::GetLanguageTypeFromString (option_arg); - if (language == eLanguageTypeUnknown) - error.SetErrorStringWithFormat ("unknown language type: '%s' for expression", option_arg); - break; - - case 'a': - { - bool success; - bool result; - result = Args::StringToBoolean(option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid all-threads value setting: \"%s\"", option_arg); - else - try_all_threads = result; - } - break; - - case 'i': - { - bool success; - bool tmp_value = Args::StringToBoolean(option_arg, true, &success); - if (success) - ignore_breakpoints = tmp_value; - else - error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); - break; - } - - case 'j': - { - bool success; - bool tmp_value = Args::StringToBoolean(option_arg, true, &success); - if (success) - allow_jit = tmp_value; - else - error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); - break; - } - - case 't': - { - bool success; - uint32_t result; - result = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (success) - timeout = result; - else - error.SetErrorStringWithFormat ("invalid timeout setting \"%s\"", option_arg); - } - break; - - case 'u': - { - bool success; - bool tmp_value = Args::StringToBoolean(option_arg, true, &success); - if (success) - unwind_on_error = tmp_value; - else - error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); - break; - } - - case 'v': - if (!option_arg) - { - m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; - break; - } - m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error); - if (!error.Success()) - error.SetErrorStringWithFormat ("unrecognized value for description-verbosity '%s'", option_arg); - break; - - case 'g': - debug = true; - unwind_on_error = false; - ignore_breakpoints = false; - break; - - case 'p': - top_level = true; - break; - - case 'X': - { - bool success; - bool tmp_value = Args::StringToBoolean(option_arg, true, &success); - if (success) - auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; - else - error.SetErrorStringWithFormat("could not convert \"%s\" to a boolean value.", option_arg); - break; - } - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; +Error CommandObjectExpression::CommandOptions::SetOptionValue( + uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) { + Error error; + + const int short_option = g_option_table[option_idx].short_option; + + switch (short_option) { + case 'l': + language = Language::GetLanguageTypeFromString(option_arg); + if (language == eLanguageTypeUnknown) + error.SetErrorStringWithFormat( + "unknown language type: '%s' for expression", option_arg); + break; + + case 'a': { + bool success; + bool result; + result = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid all-threads value setting: \"%s\"", option_arg); + else + try_all_threads = result; + } break; + + case 'i': { + bool success; + bool tmp_value = Args::StringToBoolean(option_arg, true, &success); + if (success) + ignore_breakpoints = tmp_value; + else + error.SetErrorStringWithFormat( + "could not convert \"%s\" to a boolean value.", option_arg); + break; + } + + case 'j': { + bool success; + bool tmp_value = Args::StringToBoolean(option_arg, true, &success); + if (success) + allow_jit = tmp_value; + else + error.SetErrorStringWithFormat( + "could not convert \"%s\" to a boolean value.", option_arg); + break; + } + + case 't': { + bool success; + uint32_t result; + result = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (success) + timeout = result; + else + error.SetErrorStringWithFormat("invalid timeout setting \"%s\"", + option_arg); + } break; + + case 'u': { + bool success; + bool tmp_value = Args::StringToBoolean(option_arg, true, &success); + if (success) + unwind_on_error = tmp_value; + else + error.SetErrorStringWithFormat( + "could not convert \"%s\" to a boolean value.", option_arg); + break; + } + + case 'v': + if (!option_arg) { + m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull; + break; } - - return error; + m_verbosity = + (LanguageRuntimeDescriptionDisplayVerbosity)Args::StringToOptionEnum( + option_arg, g_option_table[option_idx].enum_values, 0, error); + if (!error.Success()) + error.SetErrorStringWithFormat( + "unrecognized value for description-verbosity '%s'", option_arg); + break; + + case 'g': + debug = true; + unwind_on_error = false; + ignore_breakpoints = false; + break; + + case 'p': + top_level = true; + break; + + case 'X': { + bool success; + bool tmp_value = Args::StringToBoolean(option_arg, true, &success); + if (success) + auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo; + else + error.SetErrorStringWithFormat( + "could not convert \"%s\" to a boolean value.", option_arg); + break; + } + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; } -void -CommandObjectExpression::CommandOptions::OptionParsingStarting( - ExecutionContext *execution_context) -{ - auto process_sp = - execution_context ? execution_context->GetProcessSP() : ProcessSP(); - if (process_sp) - { - ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); - unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); - } - else - { - ignore_breakpoints = true; - unwind_on_error = true; - } - - show_summary = true; - try_all_threads = true; - timeout = 0; - debug = false; - language = eLanguageTypeUnknown; - m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; - auto_apply_fixits = eLazyBoolCalculate; - top_level = false; - allow_jit = true; +void CommandObjectExpression::CommandOptions::OptionParsingStarting( + ExecutionContext *execution_context) { + auto process_sp = + execution_context ? execution_context->GetProcessSP() : ProcessSP(); + if (process_sp) { + ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions(); + unwind_on_error = process_sp->GetUnwindOnErrorInExpressions(); + } else { + ignore_breakpoints = true; + unwind_on_error = true; + } + + show_summary = true; + try_all_threads = true; + timeout = 0; + debug = false; + language = eLanguageTypeUnknown; + m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact; + auto_apply_fixits = eLazyBoolCalculate; + top_level = false; + allow_jit = true; } -const OptionDefinition* -CommandObjectExpression::CommandOptions::GetDefinitions () -{ - return g_option_table; +const OptionDefinition * +CommandObjectExpression::CommandOptions::GetDefinitions() { + return g_option_table; } -CommandObjectExpression::CommandObjectExpression(CommandInterpreter &interpreter) +CommandObjectExpression::CommandObjectExpression( + CommandInterpreter &interpreter) : CommandObjectRaw( - interpreter, "expression", - "Evaluate an expression on the current thread. Displays any returned value with LLDB's default formatting.", + interpreter, "expression", "Evaluate an expression on the current " + "thread. Displays any returned value " + "with LLDB's default formatting.", nullptr, eCommandProcessMustBePaused | eCommandTryTargetAPILock), IOHandlerDelegate(IOHandlerDelegate::Completion::Expression), - m_option_group(), - m_format_options(eFormatDefault), - m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, true), - m_command_options(), - m_expr_line_count(0), - m_expr_lines() -{ - SetHelpLong( -R"( + m_option_group(), m_format_options(eFormatDefault), + m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false, + true), + m_command_options(), m_expr_line_count(0), m_expr_lines() { + SetHelpLong( + R"( Timeouts: -)" " If the expression can be evaluated statically (without running code) then it will be. \ +)" + " If the expression can be evaluated statically (without running code) then it will be. \ Otherwise, by default the expression will run on the current thread with a short timeout: \ currently .25 seconds. If it doesn't return in that time, the evaluation will be interrupted \ and resumed with all threads running. You can use the -a option to disable retrying on all \ -threads. You can use the -t option to set a shorter timeout." R"( +threads. You can use the -t option to set a shorter timeout." + R"( User defined variables: -)" " You can define your own variables for convenience or to be used in subsequent expressions. \ +)" + " You can define your own variables for convenience or to be used in subsequent expressions. \ You define them the same way you would define variables in C. If the first character of \ your user defined variable is a $, then the variable's value will be available in future \ -expressions, otherwise it will just be available in the current expression." R"( +expressions, otherwise it will just be available in the current expression." + R"( Continuing evaluation after a breakpoint: -)" " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ +)" + " If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \ you are done with your investigation, you can either remove the expression execution frames \ from the stack with \"thread return -x\" or if you are still interested in the expression result \ you can issue the \"continue\" command and the expression evaluation will complete and the \ expression result will be available using the \"thread.completed-expression\" key in the thread \ -format." R"( +format." + R"( Examples: expr my_struct->a = my_array[3] expr -f bin -- (index * 8) + 5 expr unsigned int $foo = 5 - expr char c[] = \"foo\"; c[0])" - ); - - CommandArgumentEntry arg; - CommandArgumentData expression_arg; - - // Define the first (and only) variant of this arg. - expression_arg.arg_type = eArgTypeExpression; - expression_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (expression_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - - // Add the "--format" and "--gdb-format" - m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1); - m_option_group.Append (&m_command_options); - m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2); - m_option_group.Append (&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); - m_option_group.Finalize(); + expr char c[] = \"foo\"; c[0])"); + + CommandArgumentEntry arg; + CommandArgumentData expression_arg; + + // Define the first (and only) variant of this arg. + expression_arg.arg_type = eArgTypeExpression; + expression_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the argument + // entry. + arg.push_back(expression_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + + // Add the "--format" and "--gdb-format" + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_FORMAT | + OptionGroupFormat::OPTION_GROUP_GDB_FMT, + LLDB_OPT_SET_1); + m_option_group.Append(&m_command_options); + m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2); + m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); + m_option_group.Finalize(); } CommandObjectExpression::~CommandObjectExpression() = default; -Options * -CommandObjectExpression::GetOptions () -{ - return &m_option_group; -} +Options *CommandObjectExpression::GetOptions() { return &m_option_group; } static lldb_private::Error -CanBeUsedForElementCountPrinting (ValueObject& valobj) -{ - CompilerType type(valobj.GetCompilerType()); - CompilerType pointee; - if (!type.IsPointerType(&pointee)) - return Error("as it does not refer to a pointer"); - if (pointee.IsVoidType()) - return Error("as it refers to a pointer to void"); - return Error(); +CanBeUsedForElementCountPrinting(ValueObject &valobj) { + CompilerType type(valobj.GetCompilerType()); + CompilerType pointee; + if (!type.IsPointerType(&pointee)) + return Error("as it does not refer to a pointer"); + if (pointee.IsVoidType()) + return Error("as it refers to a pointer to void"); + return Error(); } -bool -CommandObjectExpression::EvaluateExpression(const char *expr, - Stream *output_stream, - Stream *error_stream, - CommandReturnObject *result) -{ - // Don't use m_exe_ctx as this might be called asynchronously - // after the command object DoExecute has finished when doing - // multi-line expression that use an input reader... - ExecutionContext exe_ctx (m_interpreter.GetExecutionContext()); - - Target *target = exe_ctx.GetTargetPtr(); - - if (!target) - target = GetDummyTarget(); - - if (target) - { - lldb::ValueObjectSP result_valobj_sp; - bool keep_in_memory = true; - StackFrame *frame = exe_ctx.GetFramePtr(); - - EvaluateExpressionOptions options; - options.SetCoerceToId(m_varobj_options.use_objc); - options.SetUnwindOnError(m_command_options.unwind_on_error); - options.SetIgnoreBreakpoints (m_command_options.ignore_breakpoints); - options.SetKeepInMemory(keep_in_memory); - options.SetUseDynamic(m_varobj_options.use_dynamic); - options.SetTryAllThreads(m_command_options.try_all_threads); - options.SetDebug(m_command_options.debug); - options.SetLanguage(m_command_options.language); - options.SetExecutionPolicy(m_command_options.allow_jit ? - EvaluateExpressionOptions::default_execution_policy : - lldb_private::eExecutionPolicyNever); - - bool auto_apply_fixits; - if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) - auto_apply_fixits = target->GetEnableAutoApplyFixIts(); - else - auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false; - - options.SetAutoApplyFixIts(auto_apply_fixits); - - if (m_command_options.top_level) - options.SetExecutionPolicy(eExecutionPolicyTopLevel); - - // If there is any chance we are going to stop and want to see - // what went wrong with our expression, we should generate debug info - if (!m_command_options.ignore_breakpoints || - !m_command_options.unwind_on_error) - options.SetGenerateDebugInfo(true); - - if (m_command_options.timeout > 0) - options.SetTimeoutUsec(m_command_options.timeout); - else - options.SetTimeoutUsec(0); - - ExpressionResults success = target->EvaluateExpression(expr, frame, result_valobj_sp, options, &m_fixed_expression); - - // We only tell you about the FixIt if we applied it. The compiler errors will suggest the FixIt if it parsed. - if (error_stream && !m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) - { - if (success == eExpressionCompleted) - error_stream->Printf (" Fix-it applied, fixed expression was: \n %s\n", m_fixed_expression.c_str()); - } +bool CommandObjectExpression::EvaluateExpression(const char *expr, + Stream *output_stream, + Stream *error_stream, + CommandReturnObject *result) { + // Don't use m_exe_ctx as this might be called asynchronously + // after the command object DoExecute has finished when doing + // multi-line expression that use an input reader... + ExecutionContext exe_ctx(m_interpreter.GetExecutionContext()); + + Target *target = exe_ctx.GetTargetPtr(); + + if (!target) + target = GetDummyTarget(); + + if (target) { + lldb::ValueObjectSP result_valobj_sp; + bool keep_in_memory = true; + StackFrame *frame = exe_ctx.GetFramePtr(); + + EvaluateExpressionOptions options; + options.SetCoerceToId(m_varobj_options.use_objc); + options.SetUnwindOnError(m_command_options.unwind_on_error); + options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints); + options.SetKeepInMemory(keep_in_memory); + options.SetUseDynamic(m_varobj_options.use_dynamic); + options.SetTryAllThreads(m_command_options.try_all_threads); + options.SetDebug(m_command_options.debug); + options.SetLanguage(m_command_options.language); + options.SetExecutionPolicy( + m_command_options.allow_jit + ? EvaluateExpressionOptions::default_execution_policy + : lldb_private::eExecutionPolicyNever); + + bool auto_apply_fixits; + if (m_command_options.auto_apply_fixits == eLazyBoolCalculate) + auto_apply_fixits = target->GetEnableAutoApplyFixIts(); + else + auto_apply_fixits = + m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false; - if (result_valobj_sp) - { - Format format = m_format_options.GetFormat(); - - if (result_valobj_sp->GetError().Success()) - { - if (format != eFormatVoid) - { - if (format != eFormatDefault) - result_valobj_sp->SetFormat (format); - - if (m_varobj_options.elem_count > 0) - { - Error error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); - if (error.Fail()) - { - result->AppendErrorWithFormat("expression cannot be used with --element-count %s\n", error.AsCString("")); - result->SetStatus(eReturnStatusFailed); - return false; - } - } - - DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(m_command_options.m_verbosity,format)); - options.SetVariableFormatDisplayLanguage(result_valobj_sp->GetPreferredDisplayLanguage()); - - result_valobj_sp->Dump(*output_stream,options); - - if (result) - result->SetStatus (eReturnStatusSuccessFinishResult); - } - } - else - { - if (result_valobj_sp->GetError().GetError() == UserExpression::kNoResult) - { - if (format != eFormatVoid && m_interpreter.GetDebugger().GetNotifyVoid()) - { - error_stream->PutCString("(void)\n"); - } - - if (result) - result->SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - const char *error_cstr = result_valobj_sp->GetError().AsCString(); - if (error_cstr && error_cstr[0]) - { - const size_t error_cstr_len = strlen (error_cstr); - const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n'; - if (strstr(error_cstr, "error:") != error_cstr) - error_stream->PutCString ("error: "); - error_stream->Write(error_cstr, error_cstr_len); - if (!ends_with_newline) - error_stream->EOL(); - } - else - { - error_stream->PutCString ("error: unknown error\n"); - } - - if (result) - result->SetStatus (eReturnStatusFailed); - } - } - } - } + options.SetAutoApplyFixIts(auto_apply_fixits); + + if (m_command_options.top_level) + options.SetExecutionPolicy(eExecutionPolicyTopLevel); + + // If there is any chance we are going to stop and want to see + // what went wrong with our expression, we should generate debug info + if (!m_command_options.ignore_breakpoints || + !m_command_options.unwind_on_error) + options.SetGenerateDebugInfo(true); + + if (m_command_options.timeout > 0) + options.SetTimeoutUsec(m_command_options.timeout); else - { - error_stream->Printf ("error: invalid execution context for expression\n"); - return false; + options.SetTimeoutUsec(0); + + ExpressionResults success = target->EvaluateExpression( + expr, frame, result_valobj_sp, options, &m_fixed_expression); + + // We only tell you about the FixIt if we applied it. The compiler errors + // will suggest the FixIt if it parsed. + if (error_stream && !m_fixed_expression.empty() && + target->GetEnableNotifyAboutFixIts()) { + if (success == eExpressionCompleted) + error_stream->Printf( + " Fix-it applied, fixed expression was: \n %s\n", + m_fixed_expression.c_str()); } - - return true; -} -void -CommandObjectExpression::IOHandlerInputComplete (IOHandler &io_handler, std::string &line) -{ - io_handler.SetIsDone(true); -// StreamSP output_stream = io_handler.GetDebugger().GetAsyncOutputStream(); -// StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - StreamFileSP error_sp(io_handler.GetErrorStreamFile()); - - EvaluateExpression (line.c_str(), - output_sp.get(), - error_sp.get()); - if (output_sp) - output_sp->Flush(); - if (error_sp) - error_sp->Flush(); -} + if (result_valobj_sp) { + Format format = m_format_options.GetFormat(); + + if (result_valobj_sp->GetError().Success()) { + if (format != eFormatVoid) { + if (format != eFormatDefault) + result_valobj_sp->SetFormat(format); + + if (m_varobj_options.elem_count > 0) { + Error error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); + if (error.Fail()) { + result->AppendErrorWithFormat( + "expression cannot be used with --element-count %s\n", + error.AsCString("")); + result->SetStatus(eReturnStatusFailed); + return false; + } + } + + DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( + m_command_options.m_verbosity, format)); + options.SetVariableFormatDisplayLanguage( + result_valobj_sp->GetPreferredDisplayLanguage()); + + result_valobj_sp->Dump(*output_stream, options); -bool -CommandObjectExpression::IOHandlerIsInputComplete (IOHandler &io_handler, - StringList &lines) -{ - // An empty lines is used to indicate the end of input - const size_t num_lines = lines.GetSize(); - if (num_lines > 0 && lines[num_lines - 1].empty()) - { - // Remove the last empty line from "lines" so it doesn't appear - // in our resulting input and return true to indicate we are done - // getting lines - lines.PopBack(); - return true; + if (result) + result->SetStatus(eReturnStatusSuccessFinishResult); + } + } else { + if (result_valobj_sp->GetError().GetError() == + UserExpression::kNoResult) { + if (format != eFormatVoid && + m_interpreter.GetDebugger().GetNotifyVoid()) { + error_stream->PutCString("(void)\n"); + } + + if (result) + result->SetStatus(eReturnStatusSuccessFinishResult); + } else { + const char *error_cstr = result_valobj_sp->GetError().AsCString(); + if (error_cstr && error_cstr[0]) { + const size_t error_cstr_len = strlen(error_cstr); + const bool ends_with_newline = + error_cstr[error_cstr_len - 1] == '\n'; + if (strstr(error_cstr, "error:") != error_cstr) + error_stream->PutCString("error: "); + error_stream->Write(error_cstr, error_cstr_len); + if (!ends_with_newline) + error_stream->EOL(); + } else { + error_stream->PutCString("error: unknown error\n"); + } + + if (result) + result->SetStatus(eReturnStatusFailed); + } + } } + } else { + error_stream->Printf("error: invalid execution context for expression\n"); return false; + } + + return true; } -void -CommandObjectExpression::GetMultilineExpression () -{ - m_expr_lines.clear(); - m_expr_line_count = 0; - - Debugger &debugger = GetCommandInterpreter().GetDebugger(); - bool color_prompt = debugger.GetUseColor(); - const bool multiple_lines = true; // Get multiple lines - IOHandlerSP io_handler_sp(new IOHandlerEditline(debugger, - IOHandler::Type::Expression, - "lldb-expr", // Name of input reader for history - nullptr, // No prompt - nullptr, // Continuation prompt - multiple_lines, - color_prompt, - 1, // Show line numbers starting at 1 - *this)); - - StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString("Enter expressions, then terminate with an empty line to evaluate:\n"); - output_sp->Flush(); - } - debugger.PushIOHandler(io_handler_sp); +void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler, + std::string &line) { + io_handler.SetIsDone(true); + // StreamSP output_stream = + // io_handler.GetDebugger().GetAsyncOutputStream(); + // StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream(); + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + StreamFileSP error_sp(io_handler.GetErrorStreamFile()); + + EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get()); + if (output_sp) + output_sp->Flush(); + if (error_sp) + error_sp->Flush(); } -bool -CommandObjectExpression::DoExecute(const char *command, - CommandReturnObject &result) -{ - m_fixed_expression.clear(); - auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); - m_option_group.NotifyOptionParsingStarting(&exe_ctx); +bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler, + StringList &lines) { + // An empty lines is used to indicate the end of input + const size_t num_lines = lines.GetSize(); + if (num_lines > 0 && lines[num_lines - 1].empty()) { + // Remove the last empty line from "lines" so it doesn't appear + // in our resulting input and return true to indicate we are done + // getting lines + lines.PopBack(); + return true; + } + return false; +} - const char * expr = nullptr; +void CommandObjectExpression::GetMultilineExpression() { + m_expr_lines.clear(); + m_expr_line_count = 0; + + Debugger &debugger = GetCommandInterpreter().GetDebugger(); + bool color_prompt = debugger.GetUseColor(); + const bool multiple_lines = true; // Get multiple lines + IOHandlerSP io_handler_sp( + new IOHandlerEditline(debugger, IOHandler::Type::Expression, + "lldb-expr", // Name of input reader for history + nullptr, // No prompt + nullptr, // Continuation prompt + multiple_lines, color_prompt, + 1, // Show line numbers starting at 1 + *this)); + + StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString( + "Enter expressions, then terminate with an empty line to evaluate:\n"); + output_sp->Flush(); + } + debugger.PushIOHandler(io_handler_sp); +} - if (command[0] == '\0') - { - GetMultilineExpression (); - return result.Succeeded(); +bool CommandObjectExpression::DoExecute(const char *command, + CommandReturnObject &result) { + m_fixed_expression.clear(); + auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); + m_option_group.NotifyOptionParsingStarting(&exe_ctx); + + const char *expr = nullptr; + + if (command[0] == '\0') { + GetMultilineExpression(); + return result.Succeeded(); + } + + if (command[0] == '-') { + // We have some options and these options MUST end with --. + const char *end_options = nullptr; + const char *s = command; + while (s && s[0]) { + end_options = ::strstr(s, "--"); + if (end_options) { + end_options += 2; // Get past the "--" + if (::isspace(end_options[0])) { + expr = end_options; + while (::isspace(*expr)) + ++expr; + break; + } + } + s = end_options; } - if (command[0] == '-') - { - // We have some options and these options MUST end with --. - const char *end_options = nullptr; - const char *s = command; - while (s && s[0]) - { - end_options = ::strstr (s, "--"); - if (end_options) - { - end_options += 2; // Get past the "--" - if (::isspace (end_options[0])) - { - expr = end_options; - while (::isspace (*expr)) - ++expr; - break; - } - } - s = end_options; - } + if (end_options) { + Args args(llvm::StringRef(command, end_options - command)); + if (!ParseOptions(args, result)) + return false; - if (end_options) - { - Args args (llvm::StringRef(command, end_options - command)); - if (!ParseOptions (args, result)) - return false; - - Error error (m_option_group.NotifyOptionParsingFinished(&exe_ctx)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - - if (m_repl_option.GetOptionValue().GetCurrentValue()) - { - Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); - if (target) - { - // Drop into REPL - m_expr_lines.clear(); - m_expr_line_count = 0; - - Debugger &debugger = target->GetDebugger(); - - // Check if the LLDB command interpreter is sitting on top of a REPL that - // launched it... - if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter, IOHandler::Type::REPL)) - { - // the LLDB command interpreter is sitting on top of a REPL that launched it, - // so just say the command interpreter is done and fall back to the existing REPL - m_interpreter.GetIOHandler(false)->SetIsDone(true); - } - else - { - // We are launching the REPL on top of the current LLDB command interpreter, - // so just push one - bool initialize = false; - Error repl_error; - REPLSP repl_sp (target->GetREPL(repl_error, m_command_options.language, nullptr, false)); - - if (!repl_sp) - { - initialize = true; - repl_sp = target->GetREPL(repl_error, m_command_options.language, nullptr, true); - if (!repl_error.Success()) - { - result.SetError(repl_error); - return result.Succeeded(); - } - } - - if (repl_sp) - { - if (initialize) - { - repl_sp->SetCommandOptions(m_command_options); - repl_sp->SetFormatOptions(m_format_options); - repl_sp->SetValueObjectDisplayOptions(m_varobj_options); - } - - IOHandlerSP io_handler_sp (repl_sp->GetIOHandler()); - - io_handler_sp->SetIsDone(false); - - debugger.PushIOHandler(io_handler_sp); - } - else - { - repl_error.SetErrorStringWithFormat("Couldn't create a REPL for %s", Language::GetNameForLanguageType(m_command_options.language)); - result.SetError(repl_error); - return result.Succeeded(); - } - } - } - } - // No expression following options - else if (expr == nullptr || expr[0] == '\0') - { - GetMultilineExpression (); + Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_repl_option.GetOptionValue().GetCurrentValue()) { + Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); + if (target) { + // Drop into REPL + m_expr_lines.clear(); + m_expr_line_count = 0; + + Debugger &debugger = target->GetDebugger(); + + // Check if the LLDB command interpreter is sitting on top of a REPL + // that + // launched it... + if (debugger.CheckTopIOHandlerTypes( + IOHandler::Type::CommandInterpreter, IOHandler::Type::REPL)) { + // the LLDB command interpreter is sitting on top of a REPL that + // launched it, + // so just say the command interpreter is done and fall back to the + // existing REPL + m_interpreter.GetIOHandler(false)->SetIsDone(true); + } else { + // We are launching the REPL on top of the current LLDB command + // interpreter, + // so just push one + bool initialize = false; + Error repl_error; + REPLSP repl_sp(target->GetREPL( + repl_error, m_command_options.language, nullptr, false)); + + if (!repl_sp) { + initialize = true; + repl_sp = target->GetREPL(repl_error, m_command_options.language, + nullptr, true); + if (!repl_error.Success()) { + result.SetError(repl_error); return result.Succeeded(); + } } - } - } - if (expr == nullptr) - expr = command; - - if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result)) - { - Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); - if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) - { - CommandHistory &history = m_interpreter.GetCommandHistory(); - // FIXME: Can we figure out what the user actually typed (e.g. some alias for expr???) - // If we can it would be nice to show that. - std::string fixed_command("expression "); - if (expr == command) - fixed_command.append(m_fixed_expression); - else - { - // Add in any options that might have been in the original command: - fixed_command.append(command, expr - command); - fixed_command.append(m_fixed_expression); + if (repl_sp) { + if (initialize) { + repl_sp->SetCommandOptions(m_command_options); + repl_sp->SetFormatOptions(m_format_options); + repl_sp->SetValueObjectDisplayOptions(m_varobj_options); + } + + IOHandlerSP io_handler_sp(repl_sp->GetIOHandler()); + + io_handler_sp->SetIsDone(false); + + debugger.PushIOHandler(io_handler_sp); + } else { + repl_error.SetErrorStringWithFormat( + "Couldn't create a REPL for %s", + Language::GetNameForLanguageType(m_command_options.language)); + result.SetError(repl_error); + return result.Succeeded(); } - history.AppendString(fixed_command); + } } - return true; + } + // No expression following options + else if (expr == nullptr || expr[0] == '\0') { + GetMultilineExpression(); + return result.Succeeded(); + } + } + } + + if (expr == nullptr) + expr = command; + + if (EvaluateExpression(expr, &(result.GetOutputStream()), + &(result.GetErrorStream()), &result)) { + Target *target = m_interpreter.GetExecutionContext().GetTargetPtr(); + if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) { + CommandHistory &history = m_interpreter.GetCommandHistory(); + // FIXME: Can we figure out what the user actually typed (e.g. some alias + // for expr???) + // If we can it would be nice to show that. + std::string fixed_command("expression "); + if (expr == command) + fixed_command.append(m_fixed_expression); + else { + // Add in any options that might have been in the original command: + fixed_command.append(command, expr - command); + fixed_command.append(m_fixed_expression); + } + history.AppendString(fixed_command); } + return true; + } - result.SetStatus (eReturnStatusFailed); - return false; + result.SetStatus(eReturnStatusFailed); + return false; } diff --git a/lldb/source/Commands/CommandObjectExpression.h b/lldb/source/Commands/CommandObjectExpression.h index 9e6278351d1..5b8173f9dea 100644 --- a/lldb/source/Commands/CommandObjectExpression.h +++ b/lldb/source/Commands/CommandObjectExpression.h @@ -14,101 +14,82 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/lldb-private-enumerations.h" #include "lldb/Core/IOHandler.h" #include "lldb/Interpreter/CommandObject.h" #include "lldb/Interpreter/OptionGroupBoolean.h" #include "lldb/Interpreter/OptionGroupFormat.h" #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" #include "lldb/Target/ExecutionContext.h" +#include "lldb/lldb-private-enumerations.h" namespace lldb_private { -class CommandObjectExpression : - public CommandObjectRaw, - public IOHandlerDelegate -{ +class CommandObjectExpression : public CommandObjectRaw, + public IOHandlerDelegate { public: + class CommandOptions : public OptionGroup { + public: + CommandOptions(); + + ~CommandOptions() override; + + uint32_t GetNumDefinitions() override; + + const OptionDefinition *GetDefinitions() override; + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override; + + void OptionParsingStarting(ExecutionContext *execution_context) override; + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + bool top_level; + bool unwind_on_error; + bool ignore_breakpoints; + bool allow_jit; + bool show_types; + bool show_summary; + bool debug; + uint32_t timeout; + bool try_all_threads; + lldb::LanguageType language; + LanguageRuntimeDescriptionDisplayVerbosity m_verbosity; + LazyBool auto_apply_fixits; + }; + + CommandObjectExpression(CommandInterpreter &interpreter); + + ~CommandObjectExpression() override; - class CommandOptions : public OptionGroup - { - public: - - CommandOptions (); - - ~CommandOptions() override; - - uint32_t - GetNumDefinitions() override; - - const OptionDefinition* - GetDefinitions() override; - - Error - SetOptionValue(uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override; - - void - OptionParsingStarting(ExecutionContext *execution_context) override; - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - bool top_level; - bool unwind_on_error; - bool ignore_breakpoints; - bool allow_jit; - bool show_types; - bool show_summary; - bool debug; - uint32_t timeout; - bool try_all_threads; - lldb::LanguageType language; - LanguageRuntimeDescriptionDisplayVerbosity m_verbosity; - LazyBool auto_apply_fixits; - }; - - CommandObjectExpression (CommandInterpreter &interpreter); - - ~CommandObjectExpression() override; - - Options * - GetOptions() override; + Options *GetOptions() override; protected: - - //------------------------------------------------------------------ - // IOHandler::Delegate functions - //------------------------------------------------------------------ - void - IOHandlerInputComplete(IOHandler &io_handler, - std::string &line) override; - - bool - IOHandlerIsInputComplete (IOHandler &io_handler, - StringList &lines) override; - - bool - DoExecute(const char *command, - CommandReturnObject &result) override; - - bool - EvaluateExpression (const char *expr, - Stream *output_stream, - Stream *error_stream, - CommandReturnObject *result = NULL); - - void - GetMultilineExpression (); - - OptionGroupOptions m_option_group; - OptionGroupFormat m_format_options; - OptionGroupValueObjectDisplay m_varobj_options; - OptionGroupBoolean m_repl_option; - CommandOptions m_command_options; - uint32_t m_expr_line_count; - std::string m_expr_lines; // Multi-line expression support - std::string m_fixed_expression; // Holds the current expression's fixed text. + //------------------------------------------------------------------ + // IOHandler::Delegate functions + //------------------------------------------------------------------ + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &line) override; + + bool IOHandlerIsInputComplete(IOHandler &io_handler, + StringList &lines) override; + + bool DoExecute(const char *command, CommandReturnObject &result) override; + + bool EvaluateExpression(const char *expr, Stream *output_stream, + Stream *error_stream, + CommandReturnObject *result = NULL); + + void GetMultilineExpression(); + + OptionGroupOptions m_option_group; + OptionGroupFormat m_format_options; + OptionGroupValueObjectDisplay m_varobj_options; + OptionGroupBoolean m_repl_option; + CommandOptions m_command_options; + uint32_t m_expr_line_count; + std::string m_expr_lines; // Multi-line expression support + std::string m_fixed_expression; // Holds the current expression's fixed text. }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectFrame.cpp b/lldb/source/Commands/CommandObjectFrame.cpp index a8e73fb7b77..05b16bc31f2 100644 --- a/lldb/source/Commands/CommandObjectFrame.cpp +++ b/lldb/source/Commands/CommandObjectFrame.cpp @@ -29,12 +29,12 @@ #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionGroupFormat.h" #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" #include "lldb/Interpreter/OptionGroupVariable.h" -#include "lldb/Symbol/CompilerType.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Symbol/ClangASTContext.h" +#include "lldb/Symbol/CompilerType.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolContext.h" @@ -44,8 +44,8 @@ #include "lldb/Target/Process.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/StopInfo.h" -#include "lldb/Target/Thread.h" #include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" #include "lldb/Utility/LLDBAssert.h" using namespace lldb; @@ -61,194 +61,168 @@ using namespace lldb_private; // CommandObjectFrameDiagnose //------------------------------------------------------------------------- -class CommandObjectFrameDiagnose : public CommandObjectParsed -{ +class CommandObjectFrameDiagnose : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - switch (short_option) - { - case 'r': - reg = ConstString(option_arg); - break; - - case 'a': - { - bool success = false; - - address = StringConvert::ToUInt64 (option_arg, 0, 0, &success); - if (!success) - { - address.reset(); - error.SetErrorStringWithFormat ("invalid address argument '%s'", option_arg); - } - } - break; - - case 'o': - { - bool success = false; - - offset = StringConvert::ToSInt64 (option_arg, 0, 0, &success); - if (!success) - { - offset.reset(); - error.SetErrorStringWithFormat ("invalid offset argument '%s'", option_arg); - } - } - break; - - default: - error.SetErrorStringWithFormat ("invalid short option character '%c'", short_option); - break; - } - - return error; + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + switch (short_option) { + case 'r': + reg = ConstString(option_arg); + break; + + case 'a': { + bool success = false; + + address = StringConvert::ToUInt64(option_arg, 0, 0, &success); + if (!success) { + address.reset(); + error.SetErrorStringWithFormat("invalid address argument '%s'", + option_arg); } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - address.reset(); - reg.reset(); - offset.reset(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; + } break; + + case 'o': { + bool success = false; + + offset = StringConvert::ToSInt64(option_arg, 0, 0, &success); + if (!success) { + offset.reset(); + error.SetErrorStringWithFormat("invalid offset argument '%s'", + option_arg); } - - // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; - - // Options. - llvm::Optional address; - llvm::Optional reg; - llvm::Optional offset; - }; - - CommandObjectFrameDiagnose(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "frame diagnose", - "Try to determine what path path the current stop location used to get to a register or address", - nullptr, eCommandRequiresThread | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData index_arg; - - // Define the first (and only) variant of this arg. - index_arg.arg_type = eArgTypeFrameIndex; - index_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (index_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + } break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; } - - ~CommandObjectFrameDiagnose() override = default; - - Options * - GetOptions () override - { - return &m_options; + + void OptionParsingStarting(ExecutionContext *execution_context) override { + address.reset(); + reg.reset(); + offset.reset(); } - -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Thread *thread = m_exe_ctx.GetThreadPtr(); - StackFrameSP frame_sp = thread->GetSelectedFrame(); - - ValueObjectSP valobj_sp; - - if (m_options.address.hasValue()) - { - if (m_options.reg.hasValue() || m_options.offset.hasValue()) - { - result.AppendError("`frame diagnose --address` is incompatible with other arguments."); - result.SetStatus(eReturnStatusFailed); - return false; - } - valobj_sp = frame_sp->GuessValueForAddress(m_options.address.getValue()); - } - else if (m_options.reg.hasValue()) - { - valobj_sp = frame_sp->GuessValueForRegisterAndOffset(m_options.reg.getValue(), m_options.offset.getValueOr(0)); - } - else - { - StopInfoSP stop_info_sp = thread->GetStopInfo(); - if (!stop_info_sp) - { - result.AppendError("No arguments provided, and no stop info."); - result.SetStatus(eReturnStatusFailed); - return false; - } - valobj_sp = StopInfo::GetCrashingDereference(stop_info_sp); - } - - if (!valobj_sp) - { - result.AppendError("No diagnosis available."); - result.SetStatus(eReturnStatusFailed); - return false; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + static OptionDefinition g_option_table[]; + + // Options. + llvm::Optional address; + llvm::Optional reg; + llvm::Optional offset; + }; + + CommandObjectFrameDiagnose(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "frame diagnose", + "Try to determine what path path the current stop " + "location used to get to a register or address", + nullptr, + eCommandRequiresThread | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData index_arg; + + // Define the first (and only) variant of this arg. + index_arg.arg_type = eArgTypeFrameIndex; + index_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(index_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectFrameDiagnose() override = default; + + Options *GetOptions() override { return &m_options; } + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Thread *thread = m_exe_ctx.GetThreadPtr(); + StackFrameSP frame_sp = thread->GetSelectedFrame(); + + ValueObjectSP valobj_sp; + + if (m_options.address.hasValue()) { + if (m_options.reg.hasValue() || m_options.offset.hasValue()) { + result.AppendError( + "`frame diagnose --address` is incompatible with other arguments."); + result.SetStatus(eReturnStatusFailed); + return false; + } + valobj_sp = frame_sp->GuessValueForAddress(m_options.address.getValue()); + } else if (m_options.reg.hasValue()) { + valobj_sp = frame_sp->GuessValueForRegisterAndOffset( + m_options.reg.getValue(), m_options.offset.getValueOr(0)); + } else { + StopInfoSP stop_info_sp = thread->GetStopInfo(); + if (!stop_info_sp) { + result.AppendError("No arguments provided, and no stop info."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + valobj_sp = StopInfo::GetCrashingDereference(stop_info_sp); + } - const bool qualify_cxx_base_classes = false; - - DumpValueObjectOptions::DeclPrintingHelper helper = [&valobj_sp, qualify_cxx_base_classes](ConstString type, - ConstString var, - const DumpValueObjectOptions &opts, - Stream &stream) -> bool { - const ValueObject::GetExpressionPathFormat format = ValueObject::GetExpressionPathFormat::eGetExpressionPathFormatHonorPointers; - valobj_sp->GetExpressionPath(stream, qualify_cxx_base_classes, format); - stream.PutCString(" ="); - return true; - }; - - DumpValueObjectOptions options; - options.SetDeclPrintingHelper(helper); - ValueObjectPrinter printer(valobj_sp.get(), &result.GetOutputStream(), options); - printer.PrintValueObject(); - - return true; + if (!valobj_sp) { + result.AppendError("No diagnosis available."); + result.SetStatus(eReturnStatusFailed); + return false; } - + + const bool qualify_cxx_base_classes = false; + + DumpValueObjectOptions::DeclPrintingHelper helper = + [&valobj_sp, qualify_cxx_base_classes]( + ConstString type, ConstString var, + const DumpValueObjectOptions &opts, Stream &stream) -> bool { + const ValueObject::GetExpressionPathFormat format = ValueObject:: + GetExpressionPathFormat::eGetExpressionPathFormatHonorPointers; + valobj_sp->GetExpressionPath(stream, qualify_cxx_base_classes, format); + stream.PutCString(" ="); + return true; + }; + + DumpValueObjectOptions options; + options.SetDeclPrintingHelper(helper); + ValueObjectPrinter printer(valobj_sp.get(), &result.GetOutputStream(), + options); + printer.PrintValueObject(); + + return true; + } + protected: - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectFrameDiagnose::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectFrameDiagnose::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "register", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeRegisterName, "A register to diagnose."}, {LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddress, "An address to diagnose."}, {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "An optional offset. Requires --register."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectFrameInfo @@ -257,27 +231,24 @@ CommandObjectFrameDiagnose::CommandOptions::g_option_table[] = // CommandObjectFrameInfo //------------------------------------------------------------------------- -class CommandObjectFrameInfo : public CommandObjectParsed -{ +class CommandObjectFrameInfo : public CommandObjectParsed { public: - CommandObjectFrameInfo(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "frame info", - "List information about the current stack frame in the current thread.", "frame info", - eCommandRequiresFrame | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused) - { - } + CommandObjectFrameInfo(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "frame info", "List information about the current " + "stack frame in the current thread.", + "frame info", + eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} - ~CommandObjectFrameInfo() override = default; + ~CommandObjectFrameInfo() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - m_exe_ctx.GetFrameRef().DumpUsingSettingsFormat (&result.GetOutputStream()); - result.SetStatus (eReturnStatusSuccessFinishResult); - return result.Succeeded(); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + m_exe_ctx.GetFrameRef().DumpUsingSettingsFormat(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; #pragma mark CommandObjectFrameSelect @@ -286,521 +257,484 @@ protected: // CommandObjectFrameSelect //------------------------------------------------------------------------- -class CommandObjectFrameSelect : public CommandObjectParsed -{ +class CommandObjectFrameSelect : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - bool success = false; - const int short_option = m_getopt_table[option_idx].val; - switch (short_option) - { - case 'r': - relative_frame_offset = StringConvert::ToSInt32 (option_arg, INT32_MIN, 0, &success); - if (!success) - error.SetErrorStringWithFormat ("invalid frame offset argument '%s'", option_arg); - break; - - default: - error.SetErrorStringWithFormat ("invalid short option character '%c'", short_option); - break; - } - - return error; - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + bool success = false; + const int short_option = m_getopt_table[option_idx].val; + switch (short_option) { + case 'r': + relative_frame_offset = + StringConvert::ToSInt32(option_arg, INT32_MIN, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid frame offset argument '%s'", + option_arg); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - relative_frame_offset = INT32_MIN; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + relative_frame_offset = INT32_MIN; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; - int32_t relative_frame_offset; - }; + static OptionDefinition g_option_table[]; + int32_t relative_frame_offset; + }; - CommandObjectFrameSelect(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "frame select", - "Select the current stack frame by index from within the current thread (see 'thread backtrace'.)", - nullptr, eCommandRequiresThread | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData index_arg; + CommandObjectFrameSelect(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "frame select", "Select the current stack frame by " + "index from within the current thread " + "(see 'thread backtrace'.)", + nullptr, + eCommandRequiresThread | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData index_arg; - // Define the first (and only) variant of this arg. - index_arg.arg_type = eArgTypeFrameIndex; - index_arg.arg_repetition = eArgRepeatOptional; + // Define the first (and only) variant of this arg. + index_arg.arg_type = eArgTypeFrameIndex; + index_arg.arg_repetition = eArgRepeatOptional; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (index_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(index_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectFrameSelect() override = default; + ~CommandObjectFrameSelect() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // No need to check "thread" for validity as eCommandRequiresThread ensures it is valid - Thread *thread = m_exe_ctx.GetThreadPtr(); - - uint32_t frame_idx = UINT32_MAX; - if (m_options.relative_frame_offset != INT32_MIN) - { - // The one and only argument is a signed relative frame index - frame_idx = thread->GetSelectedFrameIndex (); - if (frame_idx == UINT32_MAX) - frame_idx = 0; - - if (m_options.relative_frame_offset < 0) - { - if (static_cast(frame_idx) >= -m_options.relative_frame_offset) - frame_idx += m_options.relative_frame_offset; - else - { - if (frame_idx == 0) - { - //If you are already at the bottom of the stack, then just warn and don't reset the frame. - result.AppendError("Already at the bottom of the stack."); - result.SetStatus(eReturnStatusFailed); - return false; - } - else - frame_idx = 0; - } - } - else if (m_options.relative_frame_offset > 0) - { - // I don't want "up 20" where "20" takes you past the top of the stack to produce - // an error, but rather to just go to the top. So I have to count the stack here... - const uint32_t num_frames = thread->GetStackFrameCount(); - if (static_cast(num_frames - frame_idx) > m_options.relative_frame_offset) - frame_idx += m_options.relative_frame_offset; - else - { - if (frame_idx == num_frames - 1) - { - //If we are already at the top of the stack, just warn and don't reset the frame. - result.AppendError("Already at the top of the stack."); - result.SetStatus(eReturnStatusFailed); - return false; - } - else - frame_idx = num_frames - 1; - } - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + // No need to check "thread" for validity as eCommandRequiresThread ensures + // it is valid + Thread *thread = m_exe_ctx.GetThreadPtr(); + + uint32_t frame_idx = UINT32_MAX; + if (m_options.relative_frame_offset != INT32_MIN) { + // The one and only argument is a signed relative frame index + frame_idx = thread->GetSelectedFrameIndex(); + if (frame_idx == UINT32_MAX) + frame_idx = 0; + + if (m_options.relative_frame_offset < 0) { + if (static_cast(frame_idx) >= -m_options.relative_frame_offset) + frame_idx += m_options.relative_frame_offset; + else { + if (frame_idx == 0) { + // If you are already at the bottom of the stack, then just warn and + // don't reset the frame. + result.AppendError("Already at the bottom of the stack."); + result.SetStatus(eReturnStatusFailed); + return false; + } else + frame_idx = 0; } - else - { - if (command.GetArgumentCount() == 1) - { - const char *frame_idx_cstr = command.GetArgumentAtIndex(0); - bool success = false; - frame_idx = StringConvert::ToUInt32 (frame_idx_cstr, UINT32_MAX, 0, &success); - if (!success) - { - result.AppendErrorWithFormat("invalid frame index argument '%s'.", frame_idx_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else if (command.GetArgumentCount() == 0) - { - frame_idx = thread->GetSelectedFrameIndex (); - if (frame_idx == UINT32_MAX) - { - frame_idx = 0; - } - } - else - { - result.AppendErrorWithFormat ("too many arguments; expected frame-index, saw '%s'.\n", - command.GetArgumentAtIndex(0)); - m_options.GenerateOptionUsage(result.GetErrorStream(), this, - GetCommandInterpreter() - .GetDebugger() - .GetTerminalWidth()); - return false; - } + } else if (m_options.relative_frame_offset > 0) { + // I don't want "up 20" where "20" takes you past the top of the stack + // to produce + // an error, but rather to just go to the top. So I have to count the + // stack here... + const uint32_t num_frames = thread->GetStackFrameCount(); + if (static_cast(num_frames - frame_idx) > + m_options.relative_frame_offset) + frame_idx += m_options.relative_frame_offset; + else { + if (frame_idx == num_frames - 1) { + // If we are already at the top of the stack, just warn and don't + // reset the frame. + result.AppendError("Already at the top of the stack."); + result.SetStatus(eReturnStatusFailed); + return false; + } else + frame_idx = num_frames - 1; } - - bool success = thread->SetSelectedFrameByIndexNoisily (frame_idx, result.GetOutputStream()); - if (success) - { - m_exe_ctx.SetFrameSP(thread->GetSelectedFrame ()); - result.SetStatus (eReturnStatusSuccessFinishResult); + } + } else { + if (command.GetArgumentCount() == 1) { + const char *frame_idx_cstr = command.GetArgumentAtIndex(0); + bool success = false; + frame_idx = + StringConvert::ToUInt32(frame_idx_cstr, UINT32_MAX, 0, &success); + if (!success) { + result.AppendErrorWithFormat("invalid frame index argument '%s'.", + frame_idx_cstr); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - result.AppendErrorWithFormat ("Frame index (%u) out of range.\n", frame_idx); - result.SetStatus (eReturnStatusFailed); + } else if (command.GetArgumentCount() == 0) { + frame_idx = thread->GetSelectedFrameIndex(); + if (frame_idx == UINT32_MAX) { + frame_idx = 0; } - - return result.Succeeded(); + } else { + result.AppendErrorWithFormat( + "too many arguments; expected frame-index, saw '%s'.\n", + command.GetArgumentAtIndex(0)); + m_options.GenerateOptionUsage( + result.GetErrorStream(), this, + GetCommandInterpreter().GetDebugger().GetTerminalWidth()); + return false; + } + } + + bool success = thread->SetSelectedFrameByIndexNoisily( + frame_idx, result.GetOutputStream()); + if (success) { + m_exe_ctx.SetFrameSP(thread->GetSelectedFrame()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Frame index (%u) out of range.\n", + frame_idx); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + protected: - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectFrameSelect::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectFrameSelect::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "relative", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "A relative frame index offset from the current frame index."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectFrameVariable //---------------------------------------------------------------------- // List images with associated information //---------------------------------------------------------------------- -class CommandObjectFrameVariable : public CommandObjectParsed -{ +class CommandObjectFrameVariable : public CommandObjectParsed { public: - CommandObjectFrameVariable(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "frame variable", "Show variables for the current stack frame. Defaults to all " - "arguments and local variables in scope. Names of argument, " - "local, file static and file global variables can be specified. " - "Children of aggregate variables can be specified such as " - "'var->child.x'.", - nullptr, eCommandRequiresFrame | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused | eCommandRequiresProcess), - m_option_group(), - m_option_variable(true), // Include the frame specific options by passing "true" - m_option_format(eFormatDefault), - m_varobj_options() - { - CommandArgumentEntry arg; - CommandArgumentData var_name_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeVarName; - var_name_arg.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (var_name_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - - m_option_group.Append (&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_option_format, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1); - m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } - - ~CommandObjectFrameVariable() override = default; - - Options * - GetOptions () override - { - return &m_option_group; - } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - // Arguments are the standard source file completer. - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eVariablePathCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + CommandObjectFrameVariable(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "frame variable", + "Show variables for the current stack frame. Defaults to all " + "arguments and local variables in scope. Names of argument, " + "local, file static and file global variables can be specified. " + "Children of aggregate variables can be specified such as " + "'var->child.x'.", + nullptr, eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused | eCommandRequiresProcess), + m_option_group(), + m_option_variable( + true), // Include the frame specific options by passing "true" + m_option_format(eFormatDefault), + m_varobj_options() { + CommandArgumentEntry arg; + CommandArgumentData var_name_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeVarName; + var_name_arg.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(var_name_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + + m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_option_format, + OptionGroupFormat::OPTION_GROUP_FORMAT | + OptionGroupFormat::OPTION_GROUP_GDB_FMT, + LLDB_OPT_SET_1); + m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectFrameVariable() override = default; + + Options *GetOptions() override { return &m_option_group; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + // Arguments are the standard source file completer. + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eVariablePathCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // No need to check "frame" for validity as eCommandRequiresFrame ensures it is valid - StackFrame *frame = m_exe_ctx.GetFramePtr(); - - Stream &s = result.GetOutputStream(); - - // Be careful about the stack frame, if any summary formatter runs code, it might clear the StackFrameList - // for the thread. So hold onto a shared pointer to the frame so it stays alive. - - VariableList *variable_list = frame->GetVariableList (m_option_variable.show_globals); - - VariableSP var_sp; - ValueObjectSP valobj_sp; - - const char *name_cstr = nullptr; - size_t idx; - - TypeSummaryImplSP summary_format_sp; - if (!m_option_variable.summary.IsCurrentValueEmpty()) - DataVisualization::NamedSummaryFormats::GetSummaryFormat(ConstString(m_option_variable.summary.GetCurrentValue()), summary_format_sp); - else if (!m_option_variable.summary_string.IsCurrentValueEmpty()) - summary_format_sp.reset(new StringSummaryFormat(TypeSummaryImpl::Flags(),m_option_variable.summary_string.GetCurrentValue())); - - DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(eLanguageRuntimeDescriptionDisplayVerbosityFull,eFormatDefault,summary_format_sp)); - - const SymbolContext& sym_ctx = frame->GetSymbolContext(eSymbolContextFunction); - if (sym_ctx.function && sym_ctx.function->IsTopLevelFunction()) - m_option_variable.show_globals = true; - - if (variable_list) - { - const Format format = m_option_format.GetFormat(); - options.SetFormat(format); - - if (command.GetArgumentCount() > 0) - { - VariableList regex_var_list; - - // If we have any args to the variable command, we will make - // variable objects from them... - for (idx = 0; (name_cstr = command.GetArgumentAtIndex(idx)) != nullptr; ++idx) - { - if (m_option_variable.use_regex) - { - const size_t regex_start_index = regex_var_list.GetSize(); - RegularExpression regex (name_cstr); - if (regex.Compile(name_cstr)) - { - size_t num_matches = 0; - const size_t num_new_regex_vars = variable_list->AppendVariablesIfUnique(regex, - regex_var_list, - num_matches); - if (num_new_regex_vars > 0) - { - for (size_t regex_idx = regex_start_index, end_index = regex_var_list.GetSize(); - regex_idx < end_index; - ++regex_idx) - { - var_sp = regex_var_list.GetVariableAtIndex (regex_idx); - if (var_sp) - { - valobj_sp = frame->GetValueObjectForFrameVariable (var_sp, m_varobj_options.use_dynamic); - if (valobj_sp) - { -// if (format != eFormatDefault) -// valobj_sp->SetFormat (format); - - if (m_option_variable.show_decl && var_sp->GetDeclaration ().GetFile()) - { - bool show_fullpaths = false; - bool show_module = true; - if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module)) - s.PutCString (": "); - } - valobj_sp->Dump(result.GetOutputStream(),options); - } - } - } - } - else if (num_matches == 0) - { - result.GetErrorStream().Printf ("error: no variables matched the regular expression '%s'.\n", name_cstr); - } - } - else - { - char regex_error[1024]; - if (regex.GetErrorAsCString(regex_error, sizeof(regex_error))) - result.GetErrorStream().Printf ("error: %s\n", regex_error); - else - result.GetErrorStream().Printf ("error: unknown regex error when compiling '%s'\n", name_cstr); - } - } - else // No regex, either exact variable names or variable expressions. - { - Error error; - uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | - StackFrame::eExpressionPathOptionsAllowDirectIVarAccess | - StackFrame::eExpressionPathOptionsInspectAnonymousUnions; - lldb::VariableSP var_sp; - valobj_sp = frame->GetValueForVariableExpressionPath (name_cstr, - m_varobj_options.use_dynamic, - expr_path_options, - var_sp, - error); - if (valobj_sp) - { -// if (format != eFormatDefault) -// valobj_sp->SetFormat (format); - if (m_option_variable.show_decl && var_sp && var_sp->GetDeclaration ().GetFile()) - { - var_sp->GetDeclaration ().DumpStopContext (&s, false); - s.PutCString (": "); - } - - options.SetFormat(format); - options.SetVariableFormatDisplayLanguage(valobj_sp->GetPreferredDisplayLanguage()); - - Stream &output_stream = result.GetOutputStream(); - options.SetRootValueObjectName(valobj_sp->GetParent() ? name_cstr : nullptr); - valobj_sp->Dump(output_stream,options); - } - else - { - const char *error_cstr = error.AsCString(nullptr); - if (error_cstr) - result.GetErrorStream().Printf("error: %s\n", error_cstr); - else - result.GetErrorStream().Printf( - "error: unable to find any variable expression path that matches '%s'.\n", - name_cstr); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + // No need to check "frame" for validity as eCommandRequiresFrame ensures it + // is valid + StackFrame *frame = m_exe_ctx.GetFramePtr(); + + Stream &s = result.GetOutputStream(); + + // Be careful about the stack frame, if any summary formatter runs code, it + // might clear the StackFrameList + // for the thread. So hold onto a shared pointer to the frame so it stays + // alive. + + VariableList *variable_list = + frame->GetVariableList(m_option_variable.show_globals); + + VariableSP var_sp; + ValueObjectSP valobj_sp; + + const char *name_cstr = nullptr; + size_t idx; + + TypeSummaryImplSP summary_format_sp; + if (!m_option_variable.summary.IsCurrentValueEmpty()) + DataVisualization::NamedSummaryFormats::GetSummaryFormat( + ConstString(m_option_variable.summary.GetCurrentValue()), + summary_format_sp); + else if (!m_option_variable.summary_string.IsCurrentValueEmpty()) + summary_format_sp.reset(new StringSummaryFormat( + TypeSummaryImpl::Flags(), + m_option_variable.summary_string.GetCurrentValue())); + + DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( + eLanguageRuntimeDescriptionDisplayVerbosityFull, eFormatDefault, + summary_format_sp)); + + const SymbolContext &sym_ctx = + frame->GetSymbolContext(eSymbolContextFunction); + if (sym_ctx.function && sym_ctx.function->IsTopLevelFunction()) + m_option_variable.show_globals = true; + + if (variable_list) { + const Format format = m_option_format.GetFormat(); + options.SetFormat(format); + + if (command.GetArgumentCount() > 0) { + VariableList regex_var_list; + + // If we have any args to the variable command, we will make + // variable objects from them... + for (idx = 0; (name_cstr = command.GetArgumentAtIndex(idx)) != nullptr; + ++idx) { + if (m_option_variable.use_regex) { + const size_t regex_start_index = regex_var_list.GetSize(); + RegularExpression regex(name_cstr); + if (regex.Compile(name_cstr)) { + size_t num_matches = 0; + const size_t num_new_regex_vars = + variable_list->AppendVariablesIfUnique(regex, regex_var_list, + num_matches); + if (num_new_regex_vars > 0) { + for (size_t regex_idx = regex_start_index, + end_index = regex_var_list.GetSize(); + regex_idx < end_index; ++regex_idx) { + var_sp = regex_var_list.GetVariableAtIndex(regex_idx); + if (var_sp) { + valobj_sp = frame->GetValueObjectForFrameVariable( + var_sp, m_varobj_options.use_dynamic); + if (valobj_sp) { + // if (format + // != + // eFormatDefault) + // valobj_sp->SetFormat + // (format); + + if (m_option_variable.show_decl && + var_sp->GetDeclaration().GetFile()) { + bool show_fullpaths = false; + bool show_module = true; + if (var_sp->DumpDeclaration(&s, show_fullpaths, + show_module)) + s.PutCString(": "); + } + valobj_sp->Dump(result.GetOutputStream(), options); } + } } + } else if (num_matches == 0) { + result.GetErrorStream().Printf("error: no variables matched " + "the regular expression '%s'.\n", + name_cstr); + } + } else { + char regex_error[1024]; + if (regex.GetErrorAsCString(regex_error, sizeof(regex_error))) + result.GetErrorStream().Printf("error: %s\n", regex_error); + else + result.GetErrorStream().Printf( + "error: unknown regex error when compiling '%s'\n", + name_cstr); } - else // No command arg specified. Use variable_list, instead. - { - const size_t num_variables = variable_list->GetSize(); - if (num_variables > 0) - { - for (size_t i=0; iGetVariableAtIndex(i); - bool dump_variable = true; - std::string scope_string; - switch (var_sp->GetScope()) - { - case eValueTypeVariableGlobal: - // Always dump globals since we only fetched them if - // m_option_variable.show_scope was true - if (dump_variable && m_option_variable.show_scope) - scope_string = "GLOBAL: "; - break; - - case eValueTypeVariableStatic: - // Always dump globals since we only fetched them if - // m_option_variable.show_scope was true, or this is - // a static variable from a block in the current scope - if (dump_variable && m_option_variable.show_scope) - scope_string = "STATIC: "; - break; - - case eValueTypeVariableArgument: - dump_variable = m_option_variable.show_args; - if (dump_variable && m_option_variable.show_scope) - scope_string = " ARG: "; - break; - - case eValueTypeVariableLocal: - dump_variable = m_option_variable.show_locals; - if (dump_variable && m_option_variable.show_scope) - scope_string = " LOCAL: "; - break; - - case eValueTypeVariableThreadLocal: - if (dump_variable && m_option_variable.show_scope) - scope_string = "THREAD: "; - break; - default: - break; - } - - if (dump_variable) - { - // Use the variable object code to make sure we are - // using the same APIs as the public API will be - // using... - valobj_sp = frame->GetValueObjectForFrameVariable (var_sp, - m_varobj_options.use_dynamic); - if (valobj_sp) - { -// if (format != eFormatDefault) -// valobj_sp->SetFormat (format); - - // When dumping all variables, don't print any variables - // that are not in scope to avoid extra unneeded output - if (valobj_sp->IsInScope ()) - { - if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() && - valobj_sp->IsRuntimeSupportValue()) - continue; - - if (!scope_string.empty()) - s.PutCString(scope_string.c_str()); - - if (m_option_variable.show_decl && var_sp->GetDeclaration ().GetFile()) - { - var_sp->GetDeclaration ().DumpStopContext (&s, false); - s.PutCString (": "); - } - - options.SetFormat(format); - options.SetVariableFormatDisplayLanguage(valobj_sp->GetPreferredDisplayLanguage()); - options.SetRootValueObjectName(name_cstr); - valobj_sp->Dump(result.GetOutputStream(),options); - } - } - } - } - } + } else // No regex, either exact variable names or variable + // expressions. + { + Error error; + uint32_t expr_path_options = + StackFrame::eExpressionPathOptionCheckPtrVsMember | + StackFrame::eExpressionPathOptionsAllowDirectIVarAccess | + StackFrame::eExpressionPathOptionsInspectAnonymousUnions; + lldb::VariableSP var_sp; + valobj_sp = frame->GetValueForVariableExpressionPath( + name_cstr, m_varobj_options.use_dynamic, expr_path_options, + var_sp, error); + if (valobj_sp) { + // if (format != eFormatDefault) + // valobj_sp->SetFormat (format); + if (m_option_variable.show_decl && var_sp && + var_sp->GetDeclaration().GetFile()) { + var_sp->GetDeclaration().DumpStopContext(&s, false); + s.PutCString(": "); + } + + options.SetFormat(format); + options.SetVariableFormatDisplayLanguage( + valobj_sp->GetPreferredDisplayLanguage()); + + Stream &output_stream = result.GetOutputStream(); + options.SetRootValueObjectName(valobj_sp->GetParent() ? name_cstr + : nullptr); + valobj_sp->Dump(output_stream, options); + } else { + const char *error_cstr = error.AsCString(nullptr); + if (error_cstr) + result.GetErrorStream().Printf("error: %s\n", error_cstr); + else + result.GetErrorStream().Printf("error: unable to find any " + "variable expression path that " + "matches '%s'.\n", + name_cstr); } - result.SetStatus (eReturnStatusSuccessFinishResult); + } } - - if (m_interpreter.TruncationWarningNecessary()) - { - result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(), - m_cmd_name.c_str()); - m_interpreter.TruncationWarningGiven(); + } else // No command arg specified. Use variable_list, instead. + { + const size_t num_variables = variable_list->GetSize(); + if (num_variables > 0) { + for (size_t i = 0; i < num_variables; i++) { + var_sp = variable_list->GetVariableAtIndex(i); + bool dump_variable = true; + std::string scope_string; + switch (var_sp->GetScope()) { + case eValueTypeVariableGlobal: + // Always dump globals since we only fetched them if + // m_option_variable.show_scope was true + if (dump_variable && m_option_variable.show_scope) + scope_string = "GLOBAL: "; + break; + + case eValueTypeVariableStatic: + // Always dump globals since we only fetched them if + // m_option_variable.show_scope was true, or this is + // a static variable from a block in the current scope + if (dump_variable && m_option_variable.show_scope) + scope_string = "STATIC: "; + break; + + case eValueTypeVariableArgument: + dump_variable = m_option_variable.show_args; + if (dump_variable && m_option_variable.show_scope) + scope_string = " ARG: "; + break; + + case eValueTypeVariableLocal: + dump_variable = m_option_variable.show_locals; + if (dump_variable && m_option_variable.show_scope) + scope_string = " LOCAL: "; + break; + + case eValueTypeVariableThreadLocal: + if (dump_variable && m_option_variable.show_scope) + scope_string = "THREAD: "; + break; + default: + break; + } + + if (dump_variable) { + // Use the variable object code to make sure we are + // using the same APIs as the public API will be + // using... + valobj_sp = frame->GetValueObjectForFrameVariable( + var_sp, m_varobj_options.use_dynamic); + if (valobj_sp) { + // if (format != eFormatDefault) + // valobj_sp->SetFormat + // (format); + + // When dumping all variables, don't print any variables + // that are not in scope to avoid extra unneeded output + if (valobj_sp->IsInScope()) { + if (!valobj_sp->GetTargetSP() + ->GetDisplayRuntimeSupportValues() && + valobj_sp->IsRuntimeSupportValue()) + continue; + + if (!scope_string.empty()) + s.PutCString(scope_string.c_str()); + + if (m_option_variable.show_decl && + var_sp->GetDeclaration().GetFile()) { + var_sp->GetDeclaration().DumpStopContext(&s, false); + s.PutCString(": "); + } + + options.SetFormat(format); + options.SetVariableFormatDisplayLanguage( + valobj_sp->GetPreferredDisplayLanguage()); + options.SetRootValueObjectName(name_cstr); + valobj_sp->Dump(result.GetOutputStream(), options); + } + } + } + } } - - return result.Succeeded(); + } + result.SetStatus(eReturnStatusSuccessFinishResult); } + if (m_interpreter.TruncationWarningNecessary()) { + result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(), + m_cmd_name.c_str()); + m_interpreter.TruncationWarningGiven(); + } + + return result.Succeeded(); + } + protected: - OptionGroupOptions m_option_group; - OptionGroupVariable m_option_variable; - OptionGroupFormat m_option_format; - OptionGroupValueObjectDisplay m_varobj_options; + OptionGroupOptions m_option_group; + OptionGroupVariable m_option_variable; + OptionGroupFormat m_option_format; + OptionGroupValueObjectDisplay m_varobj_options; }; #pragma mark CommandObjectMultiwordFrame @@ -809,15 +743,20 @@ protected: // CommandObjectMultiwordFrame //------------------------------------------------------------------------- -CommandObjectMultiwordFrame::CommandObjectMultiwordFrame(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "frame", - "Commands for selecting and examing the current thread's stack frames.", - "frame []") -{ - LoadSubCommand ("diagnose", CommandObjectSP (new CommandObjectFrameDiagnose (interpreter))); - LoadSubCommand ("info", CommandObjectSP (new CommandObjectFrameInfo (interpreter))); - LoadSubCommand ("select", CommandObjectSP (new CommandObjectFrameSelect (interpreter))); - LoadSubCommand ("variable", CommandObjectSP (new CommandObjectFrameVariable (interpreter))); +CommandObjectMultiwordFrame::CommandObjectMultiwordFrame( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "frame", "Commands for selecting and " + "examing the current " + "thread's stack frames.", + "frame []") { + LoadSubCommand("diagnose", + CommandObjectSP(new CommandObjectFrameDiagnose(interpreter))); + LoadSubCommand("info", + CommandObjectSP(new CommandObjectFrameInfo(interpreter))); + LoadSubCommand("select", + CommandObjectSP(new CommandObjectFrameSelect(interpreter))); + LoadSubCommand("variable", + CommandObjectSP(new CommandObjectFrameVariable(interpreter))); } CommandObjectMultiwordFrame::~CommandObjectMultiwordFrame() = default; diff --git a/lldb/source/Commands/CommandObjectFrame.h b/lldb/source/Commands/CommandObjectFrame.h index a72988078f6..875bcc944a3 100644 --- a/lldb/source/Commands/CommandObjectFrame.h +++ b/lldb/source/Commands/CommandObjectFrame.h @@ -14,9 +14,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Interpreter/Options.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/Interpreter/Options.h" namespace lldb_private { @@ -24,13 +24,11 @@ namespace lldb_private { // CommandObjectMultiwordFrame //------------------------------------------------------------------------- -class CommandObjectMultiwordFrame : public CommandObjectMultiword -{ +class CommandObjectMultiwordFrame : public CommandObjectMultiword { public: + CommandObjectMultiwordFrame(CommandInterpreter &interpreter); - CommandObjectMultiwordFrame (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordFrame() override; + ~CommandObjectMultiwordFrame() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectGUI.cpp b/lldb/source/Commands/CommandObjectGUI.cpp index 0991c7e8487..d65e12e3098 100644 --- a/lldb/source/Commands/CommandObjectGUI.cpp +++ b/lldb/source/Commands/CommandObjectGUI.cpp @@ -13,9 +13,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/lldb-private.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; @@ -24,48 +24,35 @@ using namespace lldb_private; // CommandObjectGUI //------------------------------------------------------------------------- -CommandObjectGUI::CommandObjectGUI (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, "gui", "Switch into the curses based GUI mode.", "gui") -{ -} +CommandObjectGUI::CommandObjectGUI(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "gui", + "Switch into the curses based GUI mode.", "gui") {} -CommandObjectGUI::~CommandObjectGUI () -{ -} +CommandObjectGUI::~CommandObjectGUI() {} -bool -CommandObjectGUI::DoExecute (Args& args, CommandReturnObject &result) -{ +bool CommandObjectGUI::DoExecute(Args &args, CommandReturnObject &result) { #ifndef LLDB_DISABLE_CURSES - if (args.GetArgumentCount() == 0) - { - Debugger &debugger = m_interpreter.GetDebugger(); - - lldb::StreamFileSP input_sp = debugger.GetInputFile(); - if (input_sp && - input_sp->GetFile().GetIsRealTerminal() && - input_sp->GetFile().GetIsInteractive()) - { - IOHandlerSP io_handler_sp (new IOHandlerCursesGUI (debugger)); - if (io_handler_sp) - debugger.PushIOHandler(io_handler_sp); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError("the gui command requires an interactive terminal."); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError("the gui command takes no arguments."); - result.SetStatus (eReturnStatusFailed); + if (args.GetArgumentCount() == 0) { + Debugger &debugger = m_interpreter.GetDebugger(); + + lldb::StreamFileSP input_sp = debugger.GetInputFile(); + if (input_sp && input_sp->GetFile().GetIsRealTerminal() && + input_sp->GetFile().GetIsInteractive()) { + IOHandlerSP io_handler_sp(new IOHandlerCursesGUI(debugger)); + if (io_handler_sp) + debugger.PushIOHandler(io_handler_sp); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("the gui command requires an interactive terminal."); + result.SetStatus(eReturnStatusFailed); } - return true; + } else { + result.AppendError("the gui command takes no arguments."); + result.SetStatus(eReturnStatusFailed); + } + return true; #else - result.AppendError("lldb was not build with gui support"); - return false; + result.AppendError("lldb was not build with gui support"); + return false; #endif } - diff --git a/lldb/source/Commands/CommandObjectGUI.h b/lldb/source/Commands/CommandObjectGUI.h index 494bcc48e20..c71558fa175 100644 --- a/lldb/source/Commands/CommandObjectGUI.h +++ b/lldb/source/Commands/CommandObjectGUI.h @@ -22,18 +22,14 @@ namespace lldb_private { // CommandObjectGUI //------------------------------------------------------------------------- -class CommandObjectGUI : public CommandObjectParsed -{ +class CommandObjectGUI : public CommandObjectParsed { public: + CommandObjectGUI(CommandInterpreter &interpreter); - CommandObjectGUI (CommandInterpreter &interpreter); - - ~CommandObjectGUI() override; + ~CommandObjectGUI() override; protected: - bool - DoExecute(Args& args, - CommandReturnObject &result) override; + bool DoExecute(Args &args, CommandReturnObject &result) override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectHelp.cpp b/lldb/source/Commands/CommandObjectHelp.cpp index 91470f59042..8e9188838be 100644 --- a/lldb/source/Commands/CommandObjectHelp.cpp +++ b/lldb/source/Commands/CommandObjectHelp.cpp @@ -12,10 +12,10 @@ // Other libraries and framework includes // Project includes #include "CommandObjectHelp.h" -#include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/Options.h" +#include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" using namespace lldb; using namespace lldb_private; @@ -24,254 +24,216 @@ using namespace lldb_private; // CommandObjectHelp //------------------------------------------------------------------------- -void -CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage (Stream *s, - const char* command, - const char* prefix, - const char* subcommand, - bool include_apropos, - bool include_type_lookup) -{ - if (s && command && *command) - { - s->Printf("'%s' is not a known command.\n", command); - s->Printf("Try '%shelp' to see a current list of commands.\n", prefix ? prefix : ""); - if (include_apropos) - { - s->Printf("Try '%sapropos %s' for a list of related commands.\n", - prefix ? prefix : "", subcommand ? subcommand : command); - } - if (include_type_lookup) - { - s->Printf("Try '%stype lookup %s' for information on types, methods, functions, modules, etc.", - prefix ? prefix : "", subcommand ? subcommand : command); - } +void CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage( + Stream *s, const char *command, const char *prefix, const char *subcommand, + bool include_apropos, bool include_type_lookup) { + if (s && command && *command) { + s->Printf("'%s' is not a known command.\n", command); + s->Printf("Try '%shelp' to see a current list of commands.\n", + prefix ? prefix : ""); + if (include_apropos) { + s->Printf("Try '%sapropos %s' for a list of related commands.\n", + prefix ? prefix : "", subcommand ? subcommand : command); + } + if (include_type_lookup) { + s->Printf("Try '%stype lookup %s' for information on types, methods, " + "functions, modules, etc.", + prefix ? prefix : "", subcommand ? subcommand : command); } + } } CommandObjectHelp::CommandObjectHelp(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "help", - "Show a list of all debugger commands, or give details about a specific command.", + : CommandObjectParsed(interpreter, "help", "Show a list of all debugger " + "commands, or give details " + "about a specific command.", "help []"), - m_options() -{ - CommandArgumentEntry arg; - CommandArgumentData command_arg; + m_options() { + CommandArgumentEntry arg; + CommandArgumentData command_arg; - // Define the first (and only) variant of this arg. - command_arg.arg_type = eArgTypeCommandName; - command_arg.arg_repetition = eArgRepeatStar; + // Define the first (and only) variant of this arg. + command_arg.arg_type = eArgTypeCommandName; + command_arg.arg_repetition = eArgRepeatStar; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (command_arg); + // There is only one variant this argument could be; put it into the argument + // entry. + arg.push_back(command_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); } CommandObjectHelp::~CommandObjectHelp() = default; -OptionDefinition -CommandObjectHelp::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectHelp::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "hide-aliases", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Hide aliases in the command list."}, {LLDB_OPT_SET_ALL, false, "hide-user-commands", 'u', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Hide user-defined commands from the list."}, {LLDB_OPT_SET_ALL, false, "show-hidden-commands", 'h', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Include commands prefixed with an underscore."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -bool -CommandObjectHelp::DoExecute (Args& command, CommandReturnObject &result) -{ - CommandObject::CommandMap::iterator pos; - CommandObject *cmd_obj; - const size_t argc = command.GetArgumentCount (); - - // 'help' doesn't take any arguments, other than command names. If argc is 0, we show the user - // all commands (aliases and user commands if asked for). Otherwise every argument must be the name of a command or a sub-command. - if (argc == 0) - { - uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin; - if (m_options.m_show_aliases) - cmd_types |= CommandInterpreter::eCommandTypesAliases; - if (m_options.m_show_user_defined) - cmd_types |= CommandInterpreter::eCommandTypesUserDef; - if (m_options.m_show_hidden) - cmd_types |= CommandInterpreter::eCommandTypesHidden; +bool CommandObjectHelp::DoExecute(Args &command, CommandReturnObject &result) { + CommandObject::CommandMap::iterator pos; + CommandObject *cmd_obj; + const size_t argc = command.GetArgumentCount(); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - m_interpreter.GetHelp (result, cmd_types); // General help - } - else - { - // Get command object for the first command argument. Only search built-in command dictionary. - StringList matches; - cmd_obj = m_interpreter.GetCommandObject (command.GetArgumentAtIndex (0), &matches); - bool is_alias_command = m_interpreter.AliasExists (command.GetArgumentAtIndex (0)); - std::string alias_name = command.GetArgumentAtIndex(0); - - if (cmd_obj != nullptr) - { - StringList matches; - bool all_okay = true; - CommandObject *sub_cmd_obj = cmd_obj; - // Loop down through sub_command dictionaries until we find the command object that corresponds - // to the help command entered. - std::string sub_command; - for (size_t i = 1; i < argc && all_okay; ++i) - { - sub_command = command.GetArgumentAtIndex(i); - matches.Clear(); - if (sub_cmd_obj->IsAlias()) - sub_cmd_obj = ((CommandAlias*)sub_cmd_obj)->GetUnderlyingCommand().get(); - if (! sub_cmd_obj->IsMultiwordObject ()) - { - all_okay = false; - } - else - { - CommandObject *found_cmd; - found_cmd = sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches); - if (found_cmd == nullptr) - all_okay = false; - else if (matches.GetSize() > 1) - all_okay = false; - else - sub_cmd_obj = found_cmd; - } - } - - if (!all_okay || (sub_cmd_obj == nullptr)) - { - std::string cmd_string; - command.GetCommandString (cmd_string); - if (matches.GetSize() >= 2) - { - StreamString s; - s.Printf ("ambiguous command %s", cmd_string.c_str()); - size_t num_matches = matches.GetSize(); - for (size_t match_idx = 0; match_idx < num_matches; match_idx++) - { - s.Printf ("\n\t%s", matches.GetStringAtIndex(match_idx)); - } - s.Printf ("\n"); - result.AppendError(s.GetData()); - result.SetStatus (eReturnStatusFailed); - return false; - } - else if (!sub_cmd_obj) - { - StreamString error_msg_stream; - GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, - cmd_string.c_str(), - m_interpreter.GetCommandPrefix(), - sub_command.c_str()); - result.AppendErrorWithFormat("%s",error_msg_stream.GetData()); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - GenerateAdditionalHelpAvenuesMessage(&result.GetOutputStream(), - cmd_string.c_str(), - m_interpreter.GetCommandPrefix(), - sub_command.c_str()); - result.GetOutputStream().Printf("\nThe closest match is '%s'. Help on it follows.\n\n", sub_cmd_obj->GetCommandName()); - } - } - - sub_cmd_obj->GenerateHelpText(result); - - if (is_alias_command) - { - StreamString sstr; - m_interpreter.GetAlias(alias_name.c_str())->GetAliasExpansion(sstr); - result.GetOutputStream().Printf ("\n'%s' is an abbreviation for %s\n", alias_name.c_str(), sstr.GetData()); - } - } - else if (matches.GetSize() > 0) - { - Stream &output_strm = result.GetOutputStream(); - output_strm.Printf("Help requested with ambiguous command name, possible completions:\n"); - const size_t match_count = matches.GetSize(); - for (size_t i = 0; i < match_count; i++) - { - output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i)); - } + // 'help' doesn't take any arguments, other than command names. If argc is 0, + // we show the user + // all commands (aliases and user commands if asked for). Otherwise every + // argument must be the name of a command or a sub-command. + if (argc == 0) { + uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin; + if (m_options.m_show_aliases) + cmd_types |= CommandInterpreter::eCommandTypesAliases; + if (m_options.m_show_user_defined) + cmd_types |= CommandInterpreter::eCommandTypesUserDef; + if (m_options.m_show_hidden) + cmd_types |= CommandInterpreter::eCommandTypesHidden; + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + m_interpreter.GetHelp(result, cmd_types); // General help + } else { + // Get command object for the first command argument. Only search built-in + // command dictionary. + StringList matches; + cmd_obj = + m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0), &matches); + bool is_alias_command = + m_interpreter.AliasExists(command.GetArgumentAtIndex(0)); + std::string alias_name = command.GetArgumentAtIndex(0); + + if (cmd_obj != nullptr) { + StringList matches; + bool all_okay = true; + CommandObject *sub_cmd_obj = cmd_obj; + // Loop down through sub_command dictionaries until we find the command + // object that corresponds + // to the help command entered. + std::string sub_command; + for (size_t i = 1; i < argc && all_okay; ++i) { + sub_command = command.GetArgumentAtIndex(i); + matches.Clear(); + if (sub_cmd_obj->IsAlias()) + sub_cmd_obj = + ((CommandAlias *)sub_cmd_obj)->GetUnderlyingCommand().get(); + if (!sub_cmd_obj->IsMultiwordObject()) { + all_okay = false; + } else { + CommandObject *found_cmd; + found_cmd = + sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches); + if (found_cmd == nullptr) + all_okay = false; + else if (matches.GetSize() > 1) + all_okay = false; + else + sub_cmd_obj = found_cmd; } - else - { - // Maybe the user is asking for help about a command argument rather than a command. - const CommandArgumentType arg_type = CommandObject::LookupArgumentName (command.GetArgumentAtIndex (0)); - if (arg_type != eArgTypeLastArg) - { - Stream &output_strm = result.GetOutputStream (); - CommandObject::GetArgumentHelp (output_strm, arg_type, m_interpreter); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - StreamString error_msg_stream; - GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, command.GetArgumentAtIndex(0), m_interpreter.GetCommandPrefix()); - result.AppendErrorWithFormat("%s",error_msg_stream.GetData()); - result.SetStatus (eReturnStatusFailed); - } + } + + if (!all_okay || (sub_cmd_obj == nullptr)) { + std::string cmd_string; + command.GetCommandString(cmd_string); + if (matches.GetSize() >= 2) { + StreamString s; + s.Printf("ambiguous command %s", cmd_string.c_str()); + size_t num_matches = matches.GetSize(); + for (size_t match_idx = 0; match_idx < num_matches; match_idx++) { + s.Printf("\n\t%s", matches.GetStringAtIndex(match_idx)); + } + s.Printf("\n"); + result.AppendError(s.GetData()); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!sub_cmd_obj) { + StreamString error_msg_stream; + GenerateAdditionalHelpAvenuesMessage( + &error_msg_stream, cmd_string.c_str(), + m_interpreter.GetCommandPrefix(), sub_command.c_str()); + result.AppendErrorWithFormat("%s", error_msg_stream.GetData()); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + GenerateAdditionalHelpAvenuesMessage( + &result.GetOutputStream(), cmd_string.c_str(), + m_interpreter.GetCommandPrefix(), sub_command.c_str()); + result.GetOutputStream().Printf( + "\nThe closest match is '%s'. Help on it follows.\n\n", + sub_cmd_obj->GetCommandName()); } + } + + sub_cmd_obj->GenerateHelpText(result); + + if (is_alias_command) { + StreamString sstr; + m_interpreter.GetAlias(alias_name.c_str())->GetAliasExpansion(sstr); + result.GetOutputStream().Printf("\n'%s' is an abbreviation for %s\n", + alias_name.c_str(), sstr.GetData()); + } + } else if (matches.GetSize() > 0) { + Stream &output_strm = result.GetOutputStream(); + output_strm.Printf("Help requested with ambiguous command name, possible " + "completions:\n"); + const size_t match_count = matches.GetSize(); + for (size_t i = 0; i < match_count; i++) { + output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i)); + } + } else { + // Maybe the user is asking for help about a command argument rather than + // a command. + const CommandArgumentType arg_type = + CommandObject::LookupArgumentName(command.GetArgumentAtIndex(0)); + if (arg_type != eArgTypeLastArg) { + Stream &output_strm = result.GetOutputStream(); + CommandObject::GetArgumentHelp(output_strm, arg_type, m_interpreter); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + StreamString error_msg_stream; + GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, + command.GetArgumentAtIndex(0), + m_interpreter.GetCommandPrefix()); + result.AppendErrorWithFormat("%s", error_msg_stream.GetData()); + result.SetStatus(eReturnStatusFailed); + } } - - return result.Succeeded(); + } + + return result.Succeeded(); } -int -CommandObjectHelp::HandleCompletion(Args &input, - int &cursor_index, - int &cursor_char_position, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) -{ - // Return the completions of the commands in the help system: - if (cursor_index == 0) - { - return m_interpreter.HandleCompletionMatches (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - } - else - { - CommandObject *cmd_obj = m_interpreter.GetCommandObject (input.GetArgumentAtIndex(0)); - - // The command that they are getting help on might be ambiguous, in which case we should complete that, - // otherwise complete with the command the user is getting help on... - - if (cmd_obj) - { - input.Shift(); - cursor_index--; - return cmd_obj->HandleCompletion (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - } - else - { - return m_interpreter.HandleCompletionMatches (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - } +int CommandObjectHelp::HandleCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + int match_start_point, + int max_return_elements, + bool &word_complete, + StringList &matches) { + // Return the completions of the commands in the help system: + if (cursor_index == 0) { + return m_interpreter.HandleCompletionMatches( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); + } else { + CommandObject *cmd_obj = + m_interpreter.GetCommandObject(input.GetArgumentAtIndex(0)); + + // The command that they are getting help on might be ambiguous, in which + // case we should complete that, + // otherwise complete with the command the user is getting help on... + + if (cmd_obj) { + input.Shift(); + cursor_index--; + return cmd_obj->HandleCompletion( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); + } else { + return m_interpreter.HandleCompletionMatches( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); } + } } diff --git a/lldb/source/Commands/CommandObjectHelp.h b/lldb/source/Commands/CommandObjectHelp.h index 6114aa16f07..827eb574de3 100644 --- a/lldb/source/Commands/CommandObjectHelp.h +++ b/lldb/source/Commands/CommandObjectHelp.h @@ -23,106 +23,78 @@ namespace lldb_private { // CommandObjectHelp //------------------------------------------------------------------------- -class CommandObjectHelp : public CommandObjectParsed -{ +class CommandObjectHelp : public CommandObjectParsed { public: + CommandObjectHelp(CommandInterpreter &interpreter); - CommandObjectHelp (CommandInterpreter &interpreter); - - ~CommandObjectHelp() override; - - int - HandleCompletion(Args &input, - int &cursor_index, - int &cursor_char_position, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override; - - static void - GenerateAdditionalHelpAvenuesMessage (Stream *s, - const char* command, - const char* prefix = nullptr, - const char* subcommand = nullptr, - bool include_apropos = true, - bool include_type_lookup = true); - - class CommandOptions : public Options - { - public: - - CommandOptions() : - Options() - { - } - - ~CommandOptions() override {} - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - m_show_aliases = false; - break; - case 'u': - m_show_user_defined = false; - break; - case 'h': - m_show_hidden = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_show_aliases = true; - m_show_user_defined = true; - m_show_hidden = false; - } - - const OptionDefinition* - GetDefinitions() override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_show_aliases; - bool m_show_user_defined; - bool m_show_hidden; - }; - - Options * - GetOptions() override - { - return &m_options; + ~CommandObjectHelp() override; + + int HandleCompletion(Args &input, int &cursor_index, + int &cursor_char_position, int match_start_point, + int max_return_elements, bool &word_complete, + StringList &matches) override; + + static void GenerateAdditionalHelpAvenuesMessage( + Stream *s, const char *command, const char *prefix = nullptr, + const char *subcommand = nullptr, bool include_apropos = true, + bool include_type_lookup = true); + + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override {} + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': + m_show_aliases = false; + break; + case 'u': + m_show_user_defined = false; + break; + case 'h': + m_show_hidden = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_show_aliases = true; + m_show_user_defined = true; + m_show_hidden = false; } - + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + bool m_show_aliases; + bool m_show_user_defined; + bool m_show_hidden; + }; + + Options *GetOptions() override { return &m_options; } + protected: - bool - DoExecute(Args& command, - CommandReturnObject &result) override; - + bool DoExecute(Args &command, CommandReturnObject &result) override; + private: - CommandOptions m_options; + CommandOptions m_options; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectLanguage.cpp b/lldb/source/Commands/CommandObjectLanguage.cpp index ebe33765acc..f0028d65da3 100644 --- a/lldb/source/Commands/CommandObjectLanguage.cpp +++ b/lldb/source/Commands/CommandObjectLanguage.cpp @@ -21,13 +21,11 @@ using namespace lldb; using namespace lldb_private; CommandObjectLanguage::CommandObjectLanguage(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "language", "Commands specific to a source language.", - "language []") -{ - //Let the LanguageRuntime populates this command with subcommands - LanguageRuntime::InitializeCommands(this); + : CommandObjectMultiword( + interpreter, "language", "Commands specific to a source language.", + "language []") { + // Let the LanguageRuntime populates this command with subcommands + LanguageRuntime::InitializeCommands(this); } -CommandObjectLanguage::~CommandObjectLanguage () -{ -} +CommandObjectLanguage::~CommandObjectLanguage() {} diff --git a/lldb/source/Commands/CommandObjectLanguage.h b/lldb/source/Commands/CommandObjectLanguage.h index 6003a590d77..b796c511b51 100644 --- a/lldb/source/Commands/CommandObjectLanguage.h +++ b/lldb/source/Commands/CommandObjectLanguage.h @@ -16,21 +16,19 @@ // Other libraries and framework includes // Project includes -#include "lldb/lldb-types.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/lldb-types.h" namespace lldb_private { - class CommandObjectLanguage : public CommandObjectMultiword - { - public: - CommandObjectLanguage (CommandInterpreter &interpreter); - - ~CommandObjectLanguage() override; - - protected: - bool - DoExecute (Args& command, CommandReturnObject &result); - }; +class CommandObjectLanguage : public CommandObjectMultiword { +public: + CommandObjectLanguage(CommandInterpreter &interpreter); + + ~CommandObjectLanguage() override; + +protected: + bool DoExecute(Args &command, CommandReturnObject &result); +}; } // namespace lldb_private #endif // liblldb_CommandObjectLanguage_h_ diff --git a/lldb/source/Commands/CommandObjectLog.cpp b/lldb/source/Commands/CommandObjectLog.cpp index 7dbca57252c..e4c5a8656ed 100644 --- a/lldb/source/Commands/CommandObjectLog.cpp +++ b/lldb/source/Commands/CommandObjectLog.cpp @@ -12,20 +12,20 @@ // Other libraries and framework includes // Project includes #include "CommandObjectLog.h" -#include "lldb/Interpreter/Args.h" #include "lldb/Core/Debugger.h" -#include "lldb/Host/FileSpec.h" +#include "lldb/Core/Debugger.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Core/RegularExpression.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/Timer.h" -#include "lldb/Core/Debugger.h" +#include "lldb/Host/FileSpec.h" #include "lldb/Host/StringConvert.h" +#include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolFile.h" @@ -36,171 +36,163 @@ using namespace lldb; using namespace lldb_private; -class CommandObjectLogEnable : public CommandObjectParsed -{ +class CommandObjectLogEnable : public CommandObjectParsed { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectLogEnable(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "log enable", + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectLogEnable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "log enable", "Enable logging for a single log channel.", nullptr), - m_options() - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData channel_arg; - CommandArgumentData category_arg; - - // Define the first (and only) variant of this arg. - channel_arg.arg_type = eArgTypeLogChannel; - channel_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (channel_arg); - - category_arg.arg_type = eArgTypeLogCategory; - category_arg.arg_repetition = eArgRepeatPlus; - - arg2.push_back (category_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); + m_options() { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData channel_arg; + CommandArgumentData category_arg; + + // Define the first (and only) variant of this arg. + channel_arg.arg_type = eArgTypeLogChannel; + channel_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(channel_arg); + + category_arg.arg_type = eArgTypeLogCategory; + category_arg.arg_repetition = eArgRepeatPlus; + + arg2.push_back(category_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectLogEnable() override = default; + + Options *GetOptions() override { return &m_options; } + + // int + // HandleArgumentCompletion (Args &input, + // int &cursor_index, + // int &cursor_char_position, + // OptionElementVector &opt_element_vector, + // int match_start_point, + // int max_return_elements, + // bool &word_complete, + // StringList &matches) + // { + // std::string completion_str (input.GetArgumentAtIndex(cursor_index)); + // completion_str.erase (cursor_char_position); + // + // if (cursor_index == 1) + // { + // // + // Log::AutoCompleteChannelName (completion_str.c_str(), matches); + // } + // return matches.GetSize(); + // } + // + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), log_file(), log_options(0) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'f': + log_file.SetFile(option_arg, true); + break; + case 't': + log_options |= LLDB_LOG_OPTION_THREADSAFE; + break; + case 'v': + log_options |= LLDB_LOG_OPTION_VERBOSE; + break; + case 'g': + log_options |= LLDB_LOG_OPTION_DEBUG; + break; + case 's': + log_options |= LLDB_LOG_OPTION_PREPEND_SEQUENCE; + break; + case 'T': + log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP; + break; + case 'p': + log_options |= LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD; + break; + case 'n': + log_options |= LLDB_LOG_OPTION_PREPEND_THREAD_NAME; + break; + case 'S': + log_options |= LLDB_LOG_OPTION_BACKTRACE; + break; + case 'a': + log_options |= LLDB_LOG_OPTION_APPEND; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectLogEnable() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + log_file.Clear(); + log_options = 0; } -// int -// HandleArgumentCompletion (Args &input, -// int &cursor_index, -// int &cursor_char_position, -// OptionElementVector &opt_element_vector, -// int match_start_point, -// int max_return_elements, -// bool &word_complete, -// StringList &matches) -// { -// std::string completion_str (input.GetArgumentAtIndex(cursor_index)); -// completion_str.erase (cursor_char_position); -// -// if (cursor_index == 1) -// { -// // -// Log::AutoCompleteChannelName (completion_str.c_str(), matches); -// } -// return matches.GetSize(); -// } -// + const OptionDefinition *GetDefinitions() override { return g_option_table; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - log_file(), - log_options(0) - { - } + // Options table: Required for subclasses of Options. - ~CommandOptions () override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'f': log_file.SetFile(option_arg, true); break; - case 't': log_options |= LLDB_LOG_OPTION_THREADSAFE; break; - case 'v': log_options |= LLDB_LOG_OPTION_VERBOSE; break; - case 'g': log_options |= LLDB_LOG_OPTION_DEBUG; break; - case 's': log_options |= LLDB_LOG_OPTION_PREPEND_SEQUENCE; break; - case 'T': log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP; break; - case 'p': log_options |= LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD;break; - case 'n': log_options |= LLDB_LOG_OPTION_PREPEND_THREAD_NAME; break; - case 'S': log_options |= LLDB_LOG_OPTION_BACKTRACE; break; - case 'a': log_options |= LLDB_LOG_OPTION_APPEND; break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } + static OptionDefinition g_option_table[]; - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - log_file.Clear(); - log_options = 0; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + // Instance variables to hold the values for command options. - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - FileSpec log_file; - uint32_t log_options; - }; + FileSpec log_file; + uint32_t log_options; + }; protected: - bool - DoExecute (Args& args, - CommandReturnObject &result) override - { - if (args.GetArgumentCount() < 2) - { - result.AppendErrorWithFormat("%s takes a log channel and one or more log types.\n", m_cmd_name.c_str()); - } - else - { - std::string channel(args.GetArgumentAtIndex(0)); - args.Shift (); // Shift off the channel - char log_file[PATH_MAX]; - if (m_options.log_file) - m_options.log_file.GetPath(log_file, sizeof(log_file)); - else - log_file[0] = '\0'; - bool success = m_interpreter.GetDebugger().EnableLog (channel.c_str(), - args.GetConstArgumentVector(), - log_file, - m_options.log_options, - result.GetErrorStream()); - if (success) - result.SetStatus (eReturnStatusSuccessFinishNoResult); - else - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + if (args.GetArgumentCount() < 2) { + result.AppendErrorWithFormat( + "%s takes a log channel and one or more log types.\n", + m_cmd_name.c_str()); + } else { + std::string channel(args.GetArgumentAtIndex(0)); + args.Shift(); // Shift off the channel + char log_file[PATH_MAX]; + if (m_options.log_file) + m_options.log_file.GetPath(log_file, sizeof(log_file)); + else + log_file[0] = '\0'; + bool success = m_interpreter.GetDebugger().EnableLog( + channel.c_str(), args.GetConstArgumentVector(), log_file, + m_options.log_options, result.GetErrorStream()); + if (success) + result.SetStatus(eReturnStatusSuccessFinishNoResult); + else + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectLogEnable::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectLogEnable::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Set the destination file to log to."}, {LLDB_OPT_SET_1, false, "threadsafe", 't', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable thread safe logging to avoid interweaved log lines."}, {LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose logging."}, @@ -212,256 +204,219 @@ CommandObjectLogEnable::CommandOptions::g_option_table[] = {LLDB_OPT_SET_1, false, "stack", 'S', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Append a stack backtrace to each log line."}, {LLDB_OPT_SET_1, false, "append", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Append to the log file instead of overwriting."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectLogDisable : public CommandObjectParsed -{ +class CommandObjectLogDisable : public CommandObjectParsed { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectLogDisable(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "log disable", + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectLogDisable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "log disable", "Disable one or more log channel categories.", - nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData channel_arg; - CommandArgumentData category_arg; - - // Define the first (and only) variant of this arg. - channel_arg.arg_type = eArgTypeLogChannel; - channel_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (channel_arg); - - category_arg.arg_type = eArgTypeLogCategory; - category_arg.arg_repetition = eArgRepeatPlus; - - arg2.push_back (category_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - } + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData channel_arg; + CommandArgumentData category_arg; + + // Define the first (and only) variant of this arg. + channel_arg.arg_type = eArgTypeLogChannel; + channel_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(channel_arg); + + category_arg.arg_type = eArgTypeLogCategory; + category_arg.arg_repetition = eArgRepeatPlus; - ~CommandObjectLogDisable() override = default; + arg2.push_back(category_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectLogDisable() override = default; protected: - bool - DoExecute (Args& args, - CommandReturnObject &result) override - { - const size_t argc = args.GetArgumentCount(); - if (argc == 0) - { - result.AppendErrorWithFormat("%s takes a log channel and one or more log types.\n", m_cmd_name.c_str()); - } - else - { - Log::Callbacks log_callbacks; - - std::string channel(args.GetArgumentAtIndex(0)); - args.Shift (); // Shift off the channel - if (Log::GetLogChannelCallbacks (ConstString(channel.c_str()), log_callbacks)) - { - log_callbacks.disable (args.GetConstArgumentVector(), &result.GetErrorStream()); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else if (channel == "all") - { - Log::DisableAllLogChannels(&result.GetErrorStream()); - } - else - { - LogChannelSP log_channel_sp (LogChannel::FindPlugin(channel.c_str())); - if (log_channel_sp) - { - log_channel_sp->Disable(args.GetConstArgumentVector(), &result.GetErrorStream()); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - result.AppendErrorWithFormat("Invalid log channel '%s'.\n", args.GetArgumentAtIndex(0)); - } - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + const size_t argc = args.GetArgumentCount(); + if (argc == 0) { + result.AppendErrorWithFormat( + "%s takes a log channel and one or more log types.\n", + m_cmd_name.c_str()); + } else { + Log::Callbacks log_callbacks; + + std::string channel(args.GetArgumentAtIndex(0)); + args.Shift(); // Shift off the channel + if (Log::GetLogChannelCallbacks(ConstString(channel.c_str()), + log_callbacks)) { + log_callbacks.disable(args.GetConstArgumentVector(), + &result.GetErrorStream()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else if (channel == "all") { + Log::DisableAllLogChannels(&result.GetErrorStream()); + } else { + LogChannelSP log_channel_sp(LogChannel::FindPlugin(channel.c_str())); + if (log_channel_sp) { + log_channel_sp->Disable(args.GetConstArgumentVector(), + &result.GetErrorStream()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else + result.AppendErrorWithFormat("Invalid log channel '%s'.\n", + args.GetArgumentAtIndex(0)); + } } + return result.Succeeded(); + } }; -class CommandObjectLogList : public CommandObjectParsed -{ +class CommandObjectLogList : public CommandObjectParsed { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectLogList(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "log list", - "List the log categories for one or more log channels. If none specified, lists them all.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData channel_arg; - - // Define the first (and only) variant of this arg. - channel_arg.arg_type = eArgTypeLogChannel; - channel_arg.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (channel_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectLogList() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectLogList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "log list", + "List the log categories for one or more log " + "channels. If none specified, lists them all.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData channel_arg; + + // Define the first (and only) variant of this arg. + channel_arg.arg_type = eArgTypeLogChannel; + channel_arg.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(channel_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectLogList() override = default; protected: - bool - DoExecute (Args& args, - CommandReturnObject &result) override - { - const size_t argc = args.GetArgumentCount(); - if (argc == 0) - { - Log::ListAllLogChannels (&result.GetOutputStream()); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else - { - for (size_t i=0; iListCategories(&result.GetOutputStream()); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - result.AppendErrorWithFormat("Invalid log channel '%s'.\n", args.GetArgumentAtIndex(0)); - } - } + bool DoExecute(Args &args, CommandReturnObject &result) override { + const size_t argc = args.GetArgumentCount(); + if (argc == 0) { + Log::ListAllLogChannels(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + for (size_t i = 0; i < argc; ++i) { + Log::Callbacks log_callbacks; + + std::string channel(args.GetArgumentAtIndex(i)); + if (Log::GetLogChannelCallbacks(ConstString(channel.c_str()), + log_callbacks)) { + log_callbacks.list_categories(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else if (channel == "all") { + Log::ListAllLogChannels(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + LogChannelSP log_channel_sp(LogChannel::FindPlugin(channel.c_str())); + if (log_channel_sp) { + log_channel_sp->ListCategories(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else + result.AppendErrorWithFormat("Invalid log channel '%s'.\n", + args.GetArgumentAtIndex(0)); } - return result.Succeeded(); + } } + return result.Succeeded(); + } }; -class CommandObjectLogTimer : public CommandObjectParsed -{ +class CommandObjectLogTimer : public CommandObjectParsed { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectLogTimer(CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "log timers", - "Enable, disable, dump, and reset LLDB internal performance timers.", - "log timers < enable | disable | dump | increment | reset >") - { - } - - ~CommandObjectLogTimer() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectLogTimer(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "log timers", + "Enable, disable, dump, and reset LLDB internal " + "performance timers.", + "log timers < enable | disable | dump | " + "increment | reset >") {} + + ~CommandObjectLogTimer() override = default; protected: - bool - DoExecute (Args& args, - CommandReturnObject &result) override - { - const size_t argc = args.GetArgumentCount(); - result.SetStatus(eReturnStatusFailed); + bool DoExecute(Args &args, CommandReturnObject &result) override { + const size_t argc = args.GetArgumentCount(); + result.SetStatus(eReturnStatusFailed); + + if (argc == 1) { + const char *sub_command = args.GetArgumentAtIndex(0); + + if (strcasecmp(sub_command, "enable") == 0) { + Timer::SetDisplayDepth(UINT32_MAX); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else if (strcasecmp(sub_command, "disable") == 0) { + Timer::DumpCategoryTimes(&result.GetOutputStream()); + Timer::SetDisplayDepth(0); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else if (strcasecmp(sub_command, "dump") == 0) { + Timer::DumpCategoryTimes(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else if (strcasecmp(sub_command, "reset") == 0) { + Timer::ResetCategoryTimes(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } + } else if (argc == 2) { + const char *sub_command = args.GetArgumentAtIndex(0); + + if (strcasecmp(sub_command, "enable") == 0) { + bool success; + uint32_t depth = + StringConvert::ToUInt32(args.GetArgumentAtIndex(1), 0, 0, &success); + if (success) { + Timer::SetDisplayDepth(depth); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else + result.AppendError( + "Could not convert enable depth to an unsigned integer."); + } + if (strcasecmp(sub_command, "increment") == 0) { + bool success; + bool increment = + Args::StringToBoolean(args.GetArgumentAtIndex(1), false, &success); + if (success) { + Timer::SetQuiet(!increment); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else + result.AppendError("Could not convert increment value to boolean."); + } + } - if (argc == 1) - { - const char *sub_command = args.GetArgumentAtIndex(0); - - if (strcasecmp(sub_command, "enable") == 0) - { - Timer::SetDisplayDepth (UINT32_MAX); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else if (strcasecmp(sub_command, "disable") == 0) - { - Timer::DumpCategoryTimes (&result.GetOutputStream()); - Timer::SetDisplayDepth (0); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else if (strcasecmp(sub_command, "dump") == 0) - { - Timer::DumpCategoryTimes (&result.GetOutputStream()); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else if (strcasecmp(sub_command, "reset") == 0) - { - Timer::ResetCategoryTimes (); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - } - else if (argc == 2) - { - const char *sub_command = args.GetArgumentAtIndex(0); - - if (strcasecmp(sub_command, "enable") == 0) - { - bool success; - uint32_t depth = StringConvert::ToUInt32(args.GetArgumentAtIndex(1), 0, 0, &success); - if (success) - { - Timer::SetDisplayDepth (depth); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - result.AppendError("Could not convert enable depth to an unsigned integer."); - } - if (strcasecmp(sub_command, "increment") == 0) - { - bool success; - bool increment = Args::StringToBoolean(args.GetArgumentAtIndex(1), false, &success); - if (success) - { - Timer::SetQuiet (!increment); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - result.AppendError("Could not convert increment value to boolean."); - } - } - - if (!result.Succeeded()) - { - result.AppendError("Missing subcommand"); - result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str()); - } - return result.Succeeded(); + if (!result.Succeeded()) { + result.AppendError("Missing subcommand"); + result.AppendErrorWithFormat("Usage: %s\n", m_cmd_syntax.c_str()); } + return result.Succeeded(); + } }; CommandObjectLog::CommandObjectLog(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "log", "Commands controlling LLDB internal logging.", - "log []") -{ - LoadSubCommand ("enable", CommandObjectSP (new CommandObjectLogEnable (interpreter))); - LoadSubCommand ("disable", CommandObjectSP (new CommandObjectLogDisable (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectLogList (interpreter))); - LoadSubCommand ("timers", CommandObjectSP (new CommandObjectLogTimer (interpreter))); + : CommandObjectMultiword(interpreter, "log", + "Commands controlling LLDB internal logging.", + "log []") { + LoadSubCommand("enable", + CommandObjectSP(new CommandObjectLogEnable(interpreter))); + LoadSubCommand("disable", + CommandObjectSP(new CommandObjectLogDisable(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectLogList(interpreter))); + LoadSubCommand("timers", + CommandObjectSP(new CommandObjectLogTimer(interpreter))); } CommandObjectLog::~CommandObjectLog() = default; diff --git a/lldb/source/Commands/CommandObjectLog.h b/lldb/source/Commands/CommandObjectLog.h index be5215f2bdc..1e24a4b2ac6 100644 --- a/lldb/source/Commands/CommandObjectLog.h +++ b/lldb/source/Commands/CommandObjectLog.h @@ -25,21 +25,20 @@ namespace lldb_private { // CommandObjectLog //------------------------------------------------------------------------- -class CommandObjectLog : public CommandObjectMultiword -{ +class CommandObjectLog : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectLog(CommandInterpreter &interpreter); + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectLog(CommandInterpreter &interpreter); - ~CommandObjectLog() override; + ~CommandObjectLog() override; private: - //------------------------------------------------------------------ - // For CommandObjectLog only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectLog); + //------------------------------------------------------------------ + // For CommandObjectLog only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectLog); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectMemory.cpp b/lldb/source/Commands/CommandObjectMemory.cpp index 9c9abc55320..54dfdd1ecef 100644 --- a/lldb/source/Commands/CommandObjectMemory.cpp +++ b/lldb/source/Commands/CommandObjectMemory.cpp @@ -48,10 +48,8 @@ using namespace lldb; using namespace lldb_private; -static OptionDefinition -g_option_table[] = -{ - // clang-format off +static OptionDefinition g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNumberPerLine, "The number of items per line to display." }, {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that " "uses the format, size, count and number per line settings." }, @@ -60,1766 +58,1634 @@ g_option_table[] = {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." }, - // clang-format on + // clang-format on }; -class OptionGroupReadMemory : public OptionGroup -{ +class OptionGroupReadMemory : public OptionGroup { public: - OptionGroupReadMemory () : - m_num_per_line (1,1), - m_output_as_binary (false), - m_view_as_type(), - m_offset(0,0) - { - } + OptionGroupReadMemory() + : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(), + m_offset(0, 0) {} - ~OptionGroupReadMemory() override = default; + ~OptionGroupReadMemory() override = default; - uint32_t - GetNumDefinitions () override - { - return sizeof (g_option_table) / sizeof (OptionDefinition); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_option_table[option_idx].short_option; - - switch (short_option) - { - case 'l': - error = m_num_per_line.SetValueFromString (option_arg); - if (m_num_per_line.GetCurrentValue() == 0) - error.SetErrorStringWithFormat("invalid value for --num-per-line option '%s'", option_arg); - break; - - case 'b': - m_output_as_binary = true; - break; - - case 't': - error = m_view_as_type.SetValueFromString (option_arg); - break; - - case 'r': - m_force = true; - break; - - case 'E': - error = m_offset.SetValueFromString(option_arg); - break; - - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_num_per_line.Clear(); - m_output_as_binary = false; - m_view_as_type.Clear(); - m_force = false; - m_offset.Clear(); + uint32_t GetNumDefinitions() override { + return sizeof(g_option_table) / sizeof(OptionDefinition); + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_option_table[option_idx].short_option; + + switch (short_option) { + case 'l': + error = m_num_per_line.SetValueFromString(option_arg); + if (m_num_per_line.GetCurrentValue() == 0) + error.SetErrorStringWithFormat( + "invalid value for --num-per-line option '%s'", option_arg); + break; + + case 'b': + m_output_as_binary = true; + break; + + case 't': + error = m_view_as_type.SetValueFromString(option_arg); + break; + + case 'r': + m_force = true; + break; + + case 'E': + error = m_offset.SetValueFromString(option_arg); + break; + + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; } - - Error - FinalizeSettings (Target *target, OptionGroupFormat& format_options) - { - Error error; - OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue(); - OptionValueUInt64 &count_value = format_options.GetCountValue(); - const bool byte_size_option_set = byte_size_value.OptionWasSet(); - const bool num_per_line_option_set = m_num_per_line.OptionWasSet(); - const bool count_option_set = format_options.GetCountValue().OptionWasSet(); - - switch (format_options.GetFormat()) - { - default: - break; - - case eFormatBoolean: - if (!byte_size_option_set) - byte_size_value = 1; - if (!num_per_line_option_set) - m_num_per_line = 1; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatCString: - break; - - case eFormatInstruction: - if (count_option_set) - byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize(); - m_num_per_line = 1; - break; - - case eFormatAddressInfo: - if (!byte_size_option_set) - byte_size_value = target->GetArchitecture().GetAddressByteSize(); - m_num_per_line = 1; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatPointer: - byte_size_value = target->GetArchitecture().GetAddressByteSize(); - if (!num_per_line_option_set) - m_num_per_line = 4; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatBinary: - case eFormatFloat: - case eFormatOctal: - case eFormatDecimal: - case eFormatEnum: - case eFormatUnicode16: - case eFormatUnicode32: - case eFormatUnsigned: - case eFormatHexFloat: - if (!byte_size_option_set) - byte_size_value = 4; - if (!num_per_line_option_set) - m_num_per_line = 1; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatBytes: - case eFormatBytesWithASCII: - if (byte_size_option_set) - { - if (byte_size_value > 1) - error.SetErrorStringWithFormat( - "display format (bytes/bytes with ASCII) conflicts with the specified byte size %" PRIu64 - "\n" - "\tconsider using a different display format or don't specify the byte size.", - byte_size_value.GetCurrentValue()); - } - else - byte_size_value = 1; - if (!num_per_line_option_set) - m_num_per_line = 16; - if (!count_option_set) - format_options.GetCountValue() = 32; - break; - - case eFormatCharArray: - case eFormatChar: - case eFormatCharPrintable: - if (!byte_size_option_set) - byte_size_value = 1; - if (!num_per_line_option_set) - m_num_per_line = 32; - if (!count_option_set) - format_options.GetCountValue() = 64; - break; - - case eFormatComplex: - if (!byte_size_option_set) - byte_size_value = 8; - if (!num_per_line_option_set) - m_num_per_line = 1; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatComplexInteger: - if (!byte_size_option_set) - byte_size_value = 8; - if (!num_per_line_option_set) - m_num_per_line = 1; - if (!count_option_set) - format_options.GetCountValue() = 8; - break; - - case eFormatHex: - if (!byte_size_option_set) - byte_size_value = 4; - if (!num_per_line_option_set) - { - switch (byte_size_value) - { - case 1: - case 2: - m_num_per_line = 8; - break; - case 4: - m_num_per_line = 4; - break; - case 8: - m_num_per_line = 2; - break; - default: - m_num_per_line = 1; - break; - } - } - if (!count_option_set) - count_value = 8; - break; - - case eFormatVectorOfChar: - case eFormatVectorOfSInt8: - case eFormatVectorOfUInt8: - case eFormatVectorOfSInt16: - case eFormatVectorOfUInt16: - case eFormatVectorOfSInt32: - case eFormatVectorOfUInt32: - case eFormatVectorOfSInt64: - case eFormatVectorOfUInt64: - case eFormatVectorOfFloat16: - case eFormatVectorOfFloat32: - case eFormatVectorOfFloat64: - case eFormatVectorOfUInt128: - if (!byte_size_option_set) - byte_size_value = 128; - if (!num_per_line_option_set) - m_num_per_line = 1; - if (!count_option_set) - count_value = 4; - break; + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_num_per_line.Clear(); + m_output_as_binary = false; + m_view_as_type.Clear(); + m_force = false; + m_offset.Clear(); + } + + Error FinalizeSettings(Target *target, OptionGroupFormat &format_options) { + Error error; + OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue(); + OptionValueUInt64 &count_value = format_options.GetCountValue(); + const bool byte_size_option_set = byte_size_value.OptionWasSet(); + const bool num_per_line_option_set = m_num_per_line.OptionWasSet(); + const bool count_option_set = format_options.GetCountValue().OptionWasSet(); + + switch (format_options.GetFormat()) { + default: + break; + + case eFormatBoolean: + if (!byte_size_option_set) + byte_size_value = 1; + if (!num_per_line_option_set) + m_num_per_line = 1; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatCString: + break; + + case eFormatInstruction: + if (count_option_set) + byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize(); + m_num_per_line = 1; + break; + + case eFormatAddressInfo: + if (!byte_size_option_set) + byte_size_value = target->GetArchitecture().GetAddressByteSize(); + m_num_per_line = 1; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatPointer: + byte_size_value = target->GetArchitecture().GetAddressByteSize(); + if (!num_per_line_option_set) + m_num_per_line = 4; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatBinary: + case eFormatFloat: + case eFormatOctal: + case eFormatDecimal: + case eFormatEnum: + case eFormatUnicode16: + case eFormatUnicode32: + case eFormatUnsigned: + case eFormatHexFloat: + if (!byte_size_option_set) + byte_size_value = 4; + if (!num_per_line_option_set) + m_num_per_line = 1; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatBytes: + case eFormatBytesWithASCII: + if (byte_size_option_set) { + if (byte_size_value > 1) + error.SetErrorStringWithFormat( + "display format (bytes/bytes with ASCII) conflicts with the " + "specified byte size %" PRIu64 "\n" + "\tconsider using a different display format or don't specify " + "the byte size.", + byte_size_value.GetCurrentValue()); + } else + byte_size_value = 1; + if (!num_per_line_option_set) + m_num_per_line = 16; + if (!count_option_set) + format_options.GetCountValue() = 32; + break; + + case eFormatCharArray: + case eFormatChar: + case eFormatCharPrintable: + if (!byte_size_option_set) + byte_size_value = 1; + if (!num_per_line_option_set) + m_num_per_line = 32; + if (!count_option_set) + format_options.GetCountValue() = 64; + break; + + case eFormatComplex: + if (!byte_size_option_set) + byte_size_value = 8; + if (!num_per_line_option_set) + m_num_per_line = 1; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatComplexInteger: + if (!byte_size_option_set) + byte_size_value = 8; + if (!num_per_line_option_set) + m_num_per_line = 1; + if (!count_option_set) + format_options.GetCountValue() = 8; + break; + + case eFormatHex: + if (!byte_size_option_set) + byte_size_value = 4; + if (!num_per_line_option_set) { + switch (byte_size_value) { + case 1: + case 2: + m_num_per_line = 8; + break; + case 4: + m_num_per_line = 4; + break; + case 8: + m_num_per_line = 2; + break; + default: + m_num_per_line = 1; + break; } - return error; + } + if (!count_option_set) + count_value = 8; + break; + + case eFormatVectorOfChar: + case eFormatVectorOfSInt8: + case eFormatVectorOfUInt8: + case eFormatVectorOfSInt16: + case eFormatVectorOfUInt16: + case eFormatVectorOfSInt32: + case eFormatVectorOfUInt32: + case eFormatVectorOfSInt64: + case eFormatVectorOfUInt64: + case eFormatVectorOfFloat16: + case eFormatVectorOfFloat32: + case eFormatVectorOfFloat64: + case eFormatVectorOfUInt128: + if (!byte_size_option_set) + byte_size_value = 128; + if (!num_per_line_option_set) + m_num_per_line = 1; + if (!count_option_set) + count_value = 4; + break; } + return error; + } - bool - AnyOptionWasSet () const - { - return m_num_per_line.OptionWasSet() || - m_output_as_binary || - m_view_as_type.OptionWasSet() || - m_offset.OptionWasSet(); - } - - OptionValueUInt64 m_num_per_line; - bool m_output_as_binary; - OptionValueString m_view_as_type; - bool m_force; - OptionValueUInt64 m_offset; + bool AnyOptionWasSet() const { + return m_num_per_line.OptionWasSet() || m_output_as_binary || + m_view_as_type.OptionWasSet() || m_offset.OptionWasSet(); + } + + OptionValueUInt64 m_num_per_line; + bool m_output_as_binary; + OptionValueString m_view_as_type; + bool m_force; + OptionValueUInt64 m_offset; }; //---------------------------------------------------------------------- // Read memory from the inferior process //---------------------------------------------------------------------- -class CommandObjectMemoryRead : public CommandObjectParsed -{ +class CommandObjectMemoryRead : public CommandObjectParsed { public: - CommandObjectMemoryRead(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "memory read", "Read from the memory of the current target process.", - nullptr, eCommandRequiresTarget | eCommandProcessMustBePaused), - m_option_group(), - m_format_options(eFormatBytesWithASCII, 1, 8), - m_memory_options(), - m_outfile_options(), - m_varobj_options(), - m_next_addr(LLDB_INVALID_ADDRESS), - m_prev_byte_size(0), - m_prev_format_options(eFormatBytesWithASCII, 1, 8), - m_prev_memory_options(), - m_prev_outfile_options(), - m_prev_varobj_options() - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData start_addr_arg; - CommandArgumentData end_addr_arg; - - // Define the first (and only) variant of this arg. - start_addr_arg.arg_type = eArgTypeAddressOrExpression; - start_addr_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (start_addr_arg); - - // Define the first (and only) variant of this arg. - end_addr_arg.arg_type = eArgTypeAddressOrExpression; - end_addr_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (end_addr_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - - // Add the "--format" and "--count" options to group 1 and 3 - m_option_group.Append (&m_format_options, - OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_COUNT, - LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); - m_option_group.Append (&m_format_options, - OptionGroupFormat::OPTION_GROUP_GDB_FMT, - LLDB_OPT_SET_1 | LLDB_OPT_SET_3); - // Add the "--size" option to group 1 and 2 - m_option_group.Append (&m_format_options, - OptionGroupFormat::OPTION_GROUP_SIZE, - LLDB_OPT_SET_1 | LLDB_OPT_SET_2); - m_option_group.Append (&m_memory_options); - m_option_group.Append (&m_outfile_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); - m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); - m_option_group.Finalize(); - } + CommandObjectMemoryRead(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "memory read", + "Read from the memory of the current target process.", nullptr, + eCommandRequiresTarget | eCommandProcessMustBePaused), + m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8), + m_memory_options(), m_outfile_options(), m_varobj_options(), + m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0), + m_prev_format_options(eFormatBytesWithASCII, 1, 8), + m_prev_memory_options(), m_prev_outfile_options(), + m_prev_varobj_options() { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData start_addr_arg; + CommandArgumentData end_addr_arg; - ~CommandObjectMemoryRead() override = default; + // Define the first (and only) variant of this arg. + start_addr_arg.arg_type = eArgTypeAddressOrExpression; + start_addr_arg.arg_repetition = eArgRepeatPlain; - Options * - GetOptions () override - { - return &m_option_group; - } + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(start_addr_arg); - const char * - GetRepeatCommand (Args ¤t_command_args, uint32_t index) override - { - return m_cmd_name.c_str(); - } + // Define the first (and only) variant of this arg. + end_addr_arg.arg_type = eArgTypeAddressOrExpression; + end_addr_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(end_addr_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + + // Add the "--format" and "--count" options to group 1 and 3 + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_FORMAT | + OptionGroupFormat::OPTION_GROUP_COUNT, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_GDB_FMT, + LLDB_OPT_SET_1 | LLDB_OPT_SET_3); + // Add the "--size" option to group 1 and 2 + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_SIZE, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2); + m_option_group.Append(&m_memory_options); + m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); + m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); + m_option_group.Finalize(); + } + + ~CommandObjectMemoryRead() override = default; + + Options *GetOptions() override { return &m_option_group; } + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + return m_cmd_name.c_str(); + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // No need to check "target" for validity as eCommandRequiresTarget ensures it is valid - Target *target = m_exe_ctx.GetTargetPtr(); - - const size_t argc = command.GetArgumentCount(); - - if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) - { - result.AppendErrorWithFormat ("%s takes a start address expression with an optional end address expression.\n", m_cmd_name.c_str()); - result.AppendRawWarning("Expressions should be quoted if they contain spaces or other special characters.\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + // No need to check "target" for validity as eCommandRequiresTarget ensures + // it is valid + Target *target = m_exe_ctx.GetTargetPtr(); + + const size_t argc = command.GetArgumentCount(); + + if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) { + result.AppendErrorWithFormat("%s takes a start address expression with " + "an optional end address expression.\n", + m_cmd_name.c_str()); + result.AppendRawWarning("Expressions should be quoted if they contain " + "spaces or other special characters.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } - CompilerType clang_ast_type; - Error error; + CompilerType clang_ast_type; + Error error; + + const char *view_as_type_cstr = + m_memory_options.m_view_as_type.GetCurrentValue(); + if (view_as_type_cstr && view_as_type_cstr[0]) { + // We are viewing memory as a type + + SymbolContext sc; + const bool exact_match = false; + TypeList type_list; + uint32_t reference_count = 0; + uint32_t pointer_count = 0; + size_t idx; + +#define ALL_KEYWORDS \ + KEYWORD("const") \ + KEYWORD("volatile") \ + KEYWORD("restrict") \ + KEYWORD("struct") \ + KEYWORD("class") \ + KEYWORD("union") - const char *view_as_type_cstr = m_memory_options.m_view_as_type.GetCurrentValue(); - if (view_as_type_cstr && view_as_type_cstr[0]) - { - // We are viewing memory as a type - - SymbolContext sc; - const bool exact_match = false; - TypeList type_list; - uint32_t reference_count = 0; - uint32_t pointer_count = 0; - size_t idx; - -#define ALL_KEYWORDS \ - KEYWORD("const") \ - KEYWORD("volatile") \ - KEYWORD("restrict") \ - KEYWORD("struct") \ - KEYWORD("class") \ - KEYWORD("union") - #define KEYWORD(s) s, - static const char *g_keywords[] = - { - ALL_KEYWORDS - }; + static const char *g_keywords[] = {ALL_KEYWORDS}; #undef KEYWORD #define KEYWORD(s) (sizeof(s) - 1), - static const int g_keyword_lengths[] = - { - ALL_KEYWORDS - }; + static const int g_keyword_lengths[] = {ALL_KEYWORDS}; #undef KEYWORD - + #undef ALL_KEYWORDS - - static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *); - std::string type_str(view_as_type_cstr); - - // Remove all instances of g_keywords that are followed by spaces - for (size_t i = 0; i < g_num_keywords; ++i) - { - const char *keyword = g_keywords[i]; - int keyword_len = g_keyword_lengths[i]; - - idx = 0; - while ((idx = type_str.find (keyword, idx)) != std::string::npos) - { - if (type_str[idx + keyword_len] == ' ' || type_str[idx + keyword_len] == '\t') - { - type_str.erase(idx, keyword_len+1); - idx = 0; - } - else - { - idx += keyword_len; - } - } - } - bool done = type_str.empty(); - // - idx = type_str.find_first_not_of (" \t"); - if (idx > 0 && idx != std::string::npos) - type_str.erase (0, idx); - while (!done) - { - // Strip trailing spaces - if (type_str.empty()) - done = true; - else - { - switch (type_str[type_str.size()-1]) - { - case '*': - ++pointer_count; - LLVM_FALLTHROUGH; - case ' ': - case '\t': - type_str.erase(type_str.size()-1); - break; - - case '&': - if (reference_count == 0) - { - reference_count = 1; - type_str.erase(type_str.size()-1); - } - else - { - result.AppendErrorWithFormat ("invalid type string: '%s'\n", view_as_type_cstr); - result.SetStatus(eReturnStatusFailed); - return false; - } - break; - - default: - done = true; - break; - } - } - } - - llvm::DenseSet searched_symbol_files; - ConstString lookup_type_name(type_str.c_str()); - StackFrame *frame = m_exe_ctx.GetFramePtr(); - if (frame) - { - sc = frame->GetSymbolContext (eSymbolContextModule); - if (sc.module_sp) - { - sc.module_sp->FindTypes (sc, - lookup_type_name, - exact_match, - 1, - searched_symbol_files, - type_list); - } - } - if (type_list.GetSize() == 0) - { - target->GetImages().FindTypes (sc, - lookup_type_name, - exact_match, - 1, - searched_symbol_files, - type_list); - } - if (type_list.GetSize() == 0 && lookup_type_name.GetCString() && *lookup_type_name.GetCString() == '$') - { - if (ClangPersistentVariables *persistent_vars = llvm::dyn_cast_or_null(target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))) - { - clang::TypeDecl *tdecl = llvm::dyn_cast_or_null(persistent_vars->GetPersistentDecl(ConstString(lookup_type_name))); - - if (tdecl) - { - clang_ast_type.SetCompilerType(ClangASTContext::GetASTContext(&tdecl->getASTContext()), - reinterpret_cast(const_cast(tdecl->getTypeForDecl()))); - } - } + static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *); + std::string type_str(view_as_type_cstr); + + // Remove all instances of g_keywords that are followed by spaces + for (size_t i = 0; i < g_num_keywords; ++i) { + const char *keyword = g_keywords[i]; + int keyword_len = g_keyword_lengths[i]; + + idx = 0; + while ((idx = type_str.find(keyword, idx)) != std::string::npos) { + if (type_str[idx + keyword_len] == ' ' || + type_str[idx + keyword_len] == '\t') { + type_str.erase(idx, keyword_len + 1); + idx = 0; + } else { + idx += keyword_len; + } + } + } + bool done = type_str.empty(); + // + idx = type_str.find_first_not_of(" \t"); + if (idx > 0 && idx != std::string::npos) + type_str.erase(0, idx); + while (!done) { + // Strip trailing spaces + if (type_str.empty()) + done = true; + else { + switch (type_str[type_str.size() - 1]) { + case '*': + ++pointer_count; + LLVM_FALLTHROUGH; + case ' ': + case '\t': + type_str.erase(type_str.size() - 1); + break; + + case '&': + if (reference_count == 0) { + reference_count = 1; + type_str.erase(type_str.size() - 1); + } else { + result.AppendErrorWithFormat("invalid type string: '%s'\n", + view_as_type_cstr); + result.SetStatus(eReturnStatusFailed); + return false; } + break; - if (!clang_ast_type.IsValid()) - { - if (type_list.GetSize() == 0) - { - result.AppendErrorWithFormat ("unable to find any types that match the raw type '%s' for full type '%s'\n", - lookup_type_name.GetCString(), - view_as_type_cstr); - result.SetStatus(eReturnStatusFailed); - return false; - } - else - { - TypeSP type_sp (type_list.GetTypeAtIndex(0)); - clang_ast_type = type_sp->GetFullCompilerType (); - } - } - - while (pointer_count > 0) - { - CompilerType pointer_type = clang_ast_type.GetPointerType(); - if (pointer_type.IsValid()) - clang_ast_type = pointer_type; - else - { - result.AppendError ("unable make a pointer type\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } - --pointer_count; - } + default: + done = true; + break; + } + } + } - m_format_options.GetByteSizeValue() = clang_ast_type.GetByteSize(nullptr); - - if (m_format_options.GetByteSizeValue() == 0) - { - result.AppendErrorWithFormat ("unable to get the byte size of the type '%s'\n", - view_as_type_cstr); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (!m_format_options.GetCountValue().OptionWasSet()) - m_format_options.GetCountValue() = 1; + llvm::DenseSet searched_symbol_files; + ConstString lookup_type_name(type_str.c_str()); + StackFrame *frame = m_exe_ctx.GetFramePtr(); + if (frame) { + sc = frame->GetSymbolContext(eSymbolContextModule); + if (sc.module_sp) { + sc.module_sp->FindTypes(sc, lookup_type_name, exact_match, 1, + searched_symbol_files, type_list); } - else - { - error = m_memory_options.FinalizeSettings (target, m_format_options); + } + if (type_list.GetSize() == 0) { + target->GetImages().FindTypes(sc, lookup_type_name, exact_match, 1, + searched_symbol_files, type_list); + } + + if (type_list.GetSize() == 0 && lookup_type_name.GetCString() && + *lookup_type_name.GetCString() == '$') { + if (ClangPersistentVariables *persistent_vars = + llvm::dyn_cast_or_null( + target->GetPersistentExpressionStateForLanguage( + lldb::eLanguageTypeC))) { + clang::TypeDecl *tdecl = llvm::dyn_cast_or_null( + persistent_vars->GetPersistentDecl( + ConstString(lookup_type_name))); + + if (tdecl) { + clang_ast_type.SetCompilerType( + ClangASTContext::GetASTContext(&tdecl->getASTContext()), + reinterpret_cast( + const_cast(tdecl->getTypeForDecl()))); + } } + } - // Look for invalid combinations of settings - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; + if (!clang_ast_type.IsValid()) { + if (type_list.GetSize() == 0) { + result.AppendErrorWithFormat("unable to find any types that match " + "the raw type '%s' for full type '%s'\n", + lookup_type_name.GetCString(), + view_as_type_cstr); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + TypeSP type_sp(type_list.GetTypeAtIndex(0)); + clang_ast_type = type_sp->GetFullCompilerType(); } + } - lldb::addr_t addr; - size_t total_byte_size = 0; - if (argc == 0) - { - // Use the last address and byte size and all options as they were - // if no options have been set - addr = m_next_addr; - total_byte_size = m_prev_byte_size; - clang_ast_type = m_prev_clang_ast_type; - if (!m_format_options.AnyOptionWasSet() && - !m_memory_options.AnyOptionWasSet() && - !m_outfile_options.AnyOptionWasSet() && - !m_varobj_options.AnyOptionWasSet()) - { - m_format_options = m_prev_format_options; - m_memory_options = m_prev_memory_options; - m_outfile_options = m_prev_outfile_options; - m_varobj_options = m_prev_varobj_options; - } + while (pointer_count > 0) { + CompilerType pointer_type = clang_ast_type.GetPointerType(); + if (pointer_type.IsValid()) + clang_ast_type = pointer_type; + else { + result.AppendError("unable make a pointer type\n"); + result.SetStatus(eReturnStatusFailed); + return false; } + --pointer_count; + } - size_t item_count = m_format_options.GetCountValue().GetCurrentValue(); + m_format_options.GetByteSizeValue() = clang_ast_type.GetByteSize(nullptr); - // TODO For non-8-bit byte addressable architectures this needs to be - // revisited to fully support all lldb's range of formatting options. - // Furthermore code memory reads (for those architectures) will not - // be correctly formatted even w/o formatting options. - size_t item_byte_size = - target->GetArchitecture().GetDataByteSize() > 1 ? - target->GetArchitecture().GetDataByteSize() : - m_format_options.GetByteSizeValue().GetCurrentValue(); + if (m_format_options.GetByteSizeValue() == 0) { + result.AppendErrorWithFormat( + "unable to get the byte size of the type '%s'\n", + view_as_type_cstr); + result.SetStatus(eReturnStatusFailed); + return false; + } - const size_t num_per_line = m_memory_options.m_num_per_line.GetCurrentValue(); + if (!m_format_options.GetCountValue().OptionWasSet()) + m_format_options.GetCountValue() = 1; + } else { + error = m_memory_options.FinalizeSettings(target, m_format_options); + } - if (total_byte_size == 0) - { - total_byte_size = item_count * item_byte_size; - if (total_byte_size == 0) - total_byte_size = 32; - } + // Look for invalid combinations of settings + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (argc > 0) - addr = Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), LLDB_INVALID_ADDRESS, &error); + lldb::addr_t addr; + size_t total_byte_size = 0; + if (argc == 0) { + // Use the last address and byte size and all options as they were + // if no options have been set + addr = m_next_addr; + total_byte_size = m_prev_byte_size; + clang_ast_type = m_prev_clang_ast_type; + if (!m_format_options.AnyOptionWasSet() && + !m_memory_options.AnyOptionWasSet() && + !m_outfile_options.AnyOptionWasSet() && + !m_varobj_options.AnyOptionWasSet()) { + m_format_options = m_prev_format_options; + m_memory_options = m_prev_memory_options; + m_outfile_options = m_prev_outfile_options; + m_varobj_options = m_prev_varobj_options; + } + } - if (addr == LLDB_INVALID_ADDRESS) - { - result.AppendError("invalid start address expression."); - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } + size_t item_count = m_format_options.GetCountValue().GetCurrentValue(); - if (argc == 2) - { - lldb::addr_t end_addr = Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1), - LLDB_INVALID_ADDRESS, nullptr); - if (end_addr == LLDB_INVALID_ADDRESS) - { - result.AppendError("invalid end address expression."); - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (end_addr <= addr) - { - result.AppendErrorWithFormat("end address (0x%" PRIx64 ") must be greater that the start address (0x%" PRIx64 ").\n", end_addr, addr); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (m_format_options.GetCountValue().OptionWasSet()) - { - result.AppendErrorWithFormat("specify either the end address (0x%" PRIx64 ") or the count (--count %" PRIu64 "), not both.\n", end_addr, (uint64_t)item_count); - result.SetStatus(eReturnStatusFailed); - return false; - } + // TODO For non-8-bit byte addressable architectures this needs to be + // revisited to fully support all lldb's range of formatting options. + // Furthermore code memory reads (for those architectures) will not + // be correctly formatted even w/o formatting options. + size_t item_byte_size = + target->GetArchitecture().GetDataByteSize() > 1 + ? target->GetArchitecture().GetDataByteSize() + : m_format_options.GetByteSizeValue().GetCurrentValue(); - total_byte_size = end_addr - addr; - item_count = total_byte_size / item_byte_size; - } + const size_t num_per_line = + m_memory_options.m_num_per_line.GetCurrentValue(); - uint32_t max_unforced_size = target->GetMaximumMemReadSize(); - - if (total_byte_size > max_unforced_size && !m_memory_options.m_force) - { - result.AppendErrorWithFormat("Normally, \'memory read\' will not read over %" PRIu32 " bytes of data.\n",max_unforced_size); - result.AppendErrorWithFormat("Please use --force to override this restriction just once.\n"); - result.AppendErrorWithFormat("or set target.max-memory-read-size if you will often need a larger limit.\n"); - return false; - } - - DataBufferSP data_sp; - size_t bytes_read = 0; - if (clang_ast_type.GetOpaqueQualType()) - { - // Make sure we don't display our type as ASCII bytes like the default memory read - if (!m_format_options.GetFormatValue().OptionWasSet()) - m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault); - - bytes_read = clang_ast_type.GetByteSize(nullptr) * m_format_options.GetCountValue().GetCurrentValue(); - - if (argc > 0) - addr = addr + (clang_ast_type.GetByteSize(nullptr) * m_memory_options.m_offset.GetCurrentValue()); - } - else if (m_format_options.GetFormatValue().GetCurrentValue() != eFormatCString) - { - data_sp.reset (new DataBufferHeap (total_byte_size, '\0')); - if (data_sp->GetBytes() == nullptr) - { - result.AppendErrorWithFormat ("can't allocate 0x%" PRIx32 " bytes for the memory read buffer, specify a smaller size to read", (uint32_t)total_byte_size); - result.SetStatus(eReturnStatusFailed); - return false; - } + if (total_byte_size == 0) { + total_byte_size = item_count * item_byte_size; + if (total_byte_size == 0) + total_byte_size = 32; + } - Address address(addr, nullptr); - bytes_read = target->ReadMemory(address, false, data_sp->GetBytes (), data_sp->GetByteSize(), error); - if (bytes_read == 0) - { - const char *error_cstr = error.AsCString(); - if (error_cstr && error_cstr[0]) - { - result.AppendError(error_cstr); - } - else - { - result.AppendErrorWithFormat("failed to read memory from 0x%" PRIx64 ".\n", addr); - } - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (bytes_read < total_byte_size) - result.AppendWarningWithFormat("Not all bytes (%" PRIu64 "/%" PRIu64 ") were able to be read from 0x%" PRIx64 ".\n", (uint64_t)bytes_read, (uint64_t)total_byte_size, addr); - } - else - { - // we treat c-strings as a special case because they do not have a fixed size - if (m_format_options.GetByteSizeValue().OptionWasSet() && !m_format_options.HasGDBFormat()) - item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue(); - else - item_byte_size = target->GetMaximumSizeOfStringSummary(); - if (!m_format_options.GetCountValue().OptionWasSet()) - item_count = 1; - data_sp.reset (new DataBufferHeap ((item_byte_size+1) * item_count, '\0')); // account for NULLs as necessary - if (data_sp->GetBytes() == nullptr) - { - result.AppendErrorWithFormat ("can't allocate 0x%" PRIx64 " bytes for the memory read buffer, specify a smaller size to read", (uint64_t)((item_byte_size+1) * item_count)); - result.SetStatus(eReturnStatusFailed); - return false; - } - uint8_t *data_ptr = data_sp->GetBytes(); - auto data_addr = addr; - auto count = item_count; - item_count = 0; - bool break_on_no_NULL = false; - while (item_count < count) - { - std::string buffer; - buffer.resize(item_byte_size+1,0); - Error error; - size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0], item_byte_size+1, error); - if (error.Fail()) - { - result.AppendErrorWithFormat("failed to read memory from 0x%" PRIx64 ".\n", addr); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (item_byte_size == read) - { - result.AppendWarningWithFormat("unable to find a NULL terminated string at 0x%" PRIx64 ".Consider increasing the maximum read length.\n", data_addr); - --read; - break_on_no_NULL = true; - } - else - ++read; // account for final NULL byte - - memcpy(data_ptr, &buffer[0], read); - data_ptr += read; - data_addr += read; - bytes_read += read; - item_count++; // if we break early we know we only read item_count strings - - if (break_on_no_NULL) - break; - } - data_sp.reset(new DataBufferHeap(data_sp->GetBytes(),bytes_read+1)); - } + if (argc > 0) + addr = Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), + LLDB_INVALID_ADDRESS, &error); - m_next_addr = addr + bytes_read; - m_prev_byte_size = bytes_read; - m_prev_format_options = m_format_options; - m_prev_memory_options = m_memory_options; - m_prev_outfile_options = m_outfile_options; - m_prev_varobj_options = m_varobj_options; - m_prev_clang_ast_type = clang_ast_type; - - StreamFile outfile_stream; - Stream *output_stream = nullptr; - const FileSpec &outfile_spec = m_outfile_options.GetFile().GetCurrentValue(); - if (outfile_spec) - { - char path[PATH_MAX]; - outfile_spec.GetPath (path, sizeof(path)); - - uint32_t open_options = File::eOpenOptionWrite | File::eOpenOptionCanCreate; - const bool append = m_outfile_options.GetAppend().GetCurrentValue(); - if (append) - open_options |= File::eOpenOptionAppend; - - if (outfile_stream.GetFile ().Open (path, open_options).Success()) - { - if (m_memory_options.m_output_as_binary) - { - const size_t bytes_written = outfile_stream.Write (data_sp->GetBytes(), bytes_read); - if (bytes_written > 0) - { - result.GetOutputStream().Printf ("%zi bytes %s to '%s'\n", - bytes_written, - append ? "appended" : "written", - path); - return true; - } - else - { - result.AppendErrorWithFormat("Failed to write %" PRIu64 " bytes to '%s'.\n", (uint64_t)bytes_read, path); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else - { - // We are going to write ASCII to the file just point the - // output_stream to our outfile_stream... - output_stream = &outfile_stream; - } - } - else - { - result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n", path, append ? "append" : "write"); - result.SetStatus(eReturnStatusFailed); - return false; - } + if (addr == LLDB_INVALID_ADDRESS) { + result.AppendError("invalid start address expression."); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (argc == 2) { + lldb::addr_t end_addr = + Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1), + LLDB_INVALID_ADDRESS, nullptr); + if (end_addr == LLDB_INVALID_ADDRESS) { + result.AppendError("invalid end address expression."); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (end_addr <= addr) { + result.AppendErrorWithFormat( + "end address (0x%" PRIx64 + ") must be greater that the start address (0x%" PRIx64 ").\n", + end_addr, addr); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (m_format_options.GetCountValue().OptionWasSet()) { + result.AppendErrorWithFormat( + "specify either the end address (0x%" PRIx64 + ") or the count (--count %" PRIu64 "), not both.\n", + end_addr, (uint64_t)item_count); + result.SetStatus(eReturnStatusFailed); + return false; + } + + total_byte_size = end_addr - addr; + item_count = total_byte_size / item_byte_size; + } + + uint32_t max_unforced_size = target->GetMaximumMemReadSize(); + + if (total_byte_size > max_unforced_size && !m_memory_options.m_force) { + result.AppendErrorWithFormat( + "Normally, \'memory read\' will not read over %" PRIu32 + " bytes of data.\n", + max_unforced_size); + result.AppendErrorWithFormat( + "Please use --force to override this restriction just once.\n"); + result.AppendErrorWithFormat("or set target.max-memory-read-size if you " + "will often need a larger limit.\n"); + return false; + } + + DataBufferSP data_sp; + size_t bytes_read = 0; + if (clang_ast_type.GetOpaqueQualType()) { + // Make sure we don't display our type as ASCII bytes like the default + // memory read + if (!m_format_options.GetFormatValue().OptionWasSet()) + m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault); + + bytes_read = clang_ast_type.GetByteSize(nullptr) * + m_format_options.GetCountValue().GetCurrentValue(); + + if (argc > 0) + addr = addr + (clang_ast_type.GetByteSize(nullptr) * + m_memory_options.m_offset.GetCurrentValue()); + } else if (m_format_options.GetFormatValue().GetCurrentValue() != + eFormatCString) { + data_sp.reset(new DataBufferHeap(total_byte_size, '\0')); + if (data_sp->GetBytes() == nullptr) { + result.AppendErrorWithFormat( + "can't allocate 0x%" PRIx32 + " bytes for the memory read buffer, specify a smaller size to read", + (uint32_t)total_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; + } + + Address address(addr, nullptr); + bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(), + data_sp->GetByteSize(), error); + if (bytes_read == 0) { + const char *error_cstr = error.AsCString(); + if (error_cstr && error_cstr[0]) { + result.AppendError(error_cstr); + } else { + result.AppendErrorWithFormat( + "failed to read memory from 0x%" PRIx64 ".\n", addr); } - else - { - output_stream = &result.GetOutputStream(); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (bytes_read < total_byte_size) + result.AppendWarningWithFormat( + "Not all bytes (%" PRIu64 "/%" PRIu64 + ") were able to be read from 0x%" PRIx64 ".\n", + (uint64_t)bytes_read, (uint64_t)total_byte_size, addr); + } else { + // we treat c-strings as a special case because they do not have a fixed + // size + if (m_format_options.GetByteSizeValue().OptionWasSet() && + !m_format_options.HasGDBFormat()) + item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue(); + else + item_byte_size = target->GetMaximumSizeOfStringSummary(); + if (!m_format_options.GetCountValue().OptionWasSet()) + item_count = 1; + data_sp.reset(new DataBufferHeap((item_byte_size + 1) * item_count, + '\0')); // account for NULLs as necessary + if (data_sp->GetBytes() == nullptr) { + result.AppendErrorWithFormat( + "can't allocate 0x%" PRIx64 + " bytes for the memory read buffer, specify a smaller size to read", + (uint64_t)((item_byte_size + 1) * item_count)); + result.SetStatus(eReturnStatusFailed); + return false; + } + uint8_t *data_ptr = data_sp->GetBytes(); + auto data_addr = addr; + auto count = item_count; + item_count = 0; + bool break_on_no_NULL = false; + while (item_count < count) { + std::string buffer; + buffer.resize(item_byte_size + 1, 0); + Error error; + size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0], + item_byte_size + 1, error); + if (error.Fail()) { + result.AppendErrorWithFormat( + "failed to read memory from 0x%" PRIx64 ".\n", addr); + result.SetStatus(eReturnStatusFailed); + return false; } - ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope(); - if (clang_ast_type.GetOpaqueQualType()) - { - for (uint32_t i = 0; iSetFormat (format); - - DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(eLanguageRuntimeDescriptionDisplayVerbosityFull,format)); - - valobj_sp->Dump(*output_stream,options); - } - else - { - result.AppendErrorWithFormat ("failed to create a value object for: (%s) %s\n", - view_as_type_cstr, - name_strm.GetString().c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } + if (item_byte_size == read) { + result.AppendWarningWithFormat( + "unable to find a NULL terminated string at 0x%" PRIx64 + ".Consider increasing the maximum read length.\n", + data_addr); + --read; + break_on_no_NULL = true; + } else + ++read; // account for final NULL byte + + memcpy(data_ptr, &buffer[0], read); + data_ptr += read; + data_addr += read; + bytes_read += read; + item_count++; // if we break early we know we only read item_count + // strings + + if (break_on_no_NULL) + break; + } + data_sp.reset(new DataBufferHeap(data_sp->GetBytes(), bytes_read + 1)); + } + + m_next_addr = addr + bytes_read; + m_prev_byte_size = bytes_read; + m_prev_format_options = m_format_options; + m_prev_memory_options = m_memory_options; + m_prev_outfile_options = m_outfile_options; + m_prev_varobj_options = m_varobj_options; + m_prev_clang_ast_type = clang_ast_type; + + StreamFile outfile_stream; + Stream *output_stream = nullptr; + const FileSpec &outfile_spec = + m_outfile_options.GetFile().GetCurrentValue(); + if (outfile_spec) { + char path[PATH_MAX]; + outfile_spec.GetPath(path, sizeof(path)); + + uint32_t open_options = + File::eOpenOptionWrite | File::eOpenOptionCanCreate; + const bool append = m_outfile_options.GetAppend().GetCurrentValue(); + if (append) + open_options |= File::eOpenOptionAppend; + + if (outfile_stream.GetFile().Open(path, open_options).Success()) { + if (m_memory_options.m_output_as_binary) { + const size_t bytes_written = + outfile_stream.Write(data_sp->GetBytes(), bytes_read); + if (bytes_written > 0) { + result.GetOutputStream().Printf( + "%zi bytes %s to '%s'\n", bytes_written, + append ? "appended" : "written", path); return true; + } else { + result.AppendErrorWithFormat("Failed to write %" PRIu64 + " bytes to '%s'.\n", + (uint64_t)bytes_read, path); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + // We are going to write ASCII to the file just point the + // output_stream to our outfile_stream... + output_stream = &outfile_stream; } + } else { + result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n", path, + append ? "append" : "write"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + output_stream = &result.GetOutputStream(); + } - result.SetStatus(eReturnStatusSuccessFinishResult); - DataExtractor data (data_sp, - target->GetArchitecture().GetByteOrder(), - target->GetArchitecture().GetAddressByteSize(), - target->GetArchitecture().GetDataByteSize()); - - Format format = m_format_options.GetFormat(); - if ( ( (format == eFormatChar) || (format == eFormatCharPrintable) ) - && (item_byte_size != 1)) - { - // if a count was not passed, or it is 1 - if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) - { - // this turns requests such as - // memory read -fc -s10 -c1 *charPtrPtr - // which make no sense (what is a char of size 10?) - // into a request for fetching 10 chars of size 1 from the same memory location - format = eFormatCharArray; - item_count = item_byte_size; - item_byte_size = 1; - } - else - { - // here we passed a count, and it was not 1 - // so we have a byte_size and a count - // we could well multiply those, but instead let's just fail - result.AppendErrorWithFormat("reading memory as characters of size %" PRIu64 " is not supported", (uint64_t)item_byte_size); - result.SetStatus(eReturnStatusFailed); - return false; - } + ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope(); + if (clang_ast_type.GetOpaqueQualType()) { + for (uint32_t i = 0; i < item_count; ++i) { + addr_t item_addr = addr + (i * item_byte_size); + Address address(item_addr); + StreamString name_strm; + name_strm.Printf("0x%" PRIx64, item_addr); + ValueObjectSP valobj_sp(ValueObjectMemory::Create( + exe_scope, name_strm.GetString().c_str(), address, clang_ast_type)); + if (valobj_sp) { + Format format = m_format_options.GetFormat(); + if (format != eFormatDefault) + valobj_sp->SetFormat(format); + + DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( + eLanguageRuntimeDescriptionDisplayVerbosityFull, format)); + + valobj_sp->Dump(*output_stream, options); + } else { + result.AppendErrorWithFormat( + "failed to create a value object for: (%s) %s\n", + view_as_type_cstr, name_strm.GetString().c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } + } + return true; + } - assert (output_stream); - size_t bytes_dumped = data.Dump (output_stream, - 0, - format, - item_byte_size, - item_count, - num_per_line / target->GetArchitecture().GetDataByteSize(), - addr, - 0, - 0, - exe_scope); - m_next_addr = addr + bytes_dumped; - output_stream->EOL(); - return true; + result.SetStatus(eReturnStatusSuccessFinishResult); + DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(), + target->GetArchitecture().GetAddressByteSize(), + target->GetArchitecture().GetDataByteSize()); + + Format format = m_format_options.GetFormat(); + if (((format == eFormatChar) || (format == eFormatCharPrintable)) && + (item_byte_size != 1)) { + // if a count was not passed, or it is 1 + if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) { + // this turns requests such as + // memory read -fc -s10 -c1 *charPtrPtr + // which make no sense (what is a char of size 10?) + // into a request for fetching 10 chars of size 1 from the same memory + // location + format = eFormatCharArray; + item_count = item_byte_size; + item_byte_size = 1; + } else { + // here we passed a count, and it was not 1 + // so we have a byte_size and a count + // we could well multiply those, but instead let's just fail + result.AppendErrorWithFormat( + "reading memory as characters of size %" PRIu64 " is not supported", + (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; + } } - OptionGroupOptions m_option_group; - OptionGroupFormat m_format_options; - OptionGroupReadMemory m_memory_options; - OptionGroupOutputFile m_outfile_options; - OptionGroupValueObjectDisplay m_varobj_options; - lldb::addr_t m_next_addr; - lldb::addr_t m_prev_byte_size; - OptionGroupFormat m_prev_format_options; - OptionGroupReadMemory m_prev_memory_options; - OptionGroupOutputFile m_prev_outfile_options; - OptionGroupValueObjectDisplay m_prev_varobj_options; - CompilerType m_prev_clang_ast_type; + assert(output_stream); + size_t bytes_dumped = + data.Dump(output_stream, 0, format, item_byte_size, item_count, + num_per_line / target->GetArchitecture().GetDataByteSize(), + addr, 0, 0, exe_scope); + m_next_addr = addr + bytes_dumped; + output_stream->EOL(); + return true; + } + + OptionGroupOptions m_option_group; + OptionGroupFormat m_format_options; + OptionGroupReadMemory m_memory_options; + OptionGroupOutputFile m_outfile_options; + OptionGroupValueObjectDisplay m_varobj_options; + lldb::addr_t m_next_addr; + lldb::addr_t m_prev_byte_size; + OptionGroupFormat m_prev_format_options; + OptionGroupReadMemory m_prev_memory_options; + OptionGroupOutputFile m_prev_outfile_options; + OptionGroupValueObjectDisplay m_prev_varobj_options; + CompilerType m_prev_clang_ast_type; }; -OptionDefinition -g_memory_find_option_table[] = -{ - // clang-format off +OptionDefinition g_memory_find_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, true, "expression", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeExpression, "Evaluate an expression to obtain a byte pattern."}, {LLDB_OPT_SET_2, true, "string", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Use text to find a byte pattern."}, {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many times to perform the search."}, {LLDB_OPT_SET_ALL, false, "dump-offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "When dumping memory for a match, an offset from the match location to start dumping from."}, - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // Find the specified data in memory //---------------------------------------------------------------------- -class CommandObjectMemoryFind : public CommandObjectParsed -{ +class CommandObjectMemoryFind : public CommandObjectParsed { public: - class OptionGroupFindMemory : public OptionGroup - { + class OptionGroupFindMemory : public OptionGroup { public: - OptionGroupFindMemory () : - OptionGroup(), - m_count(1), - m_offset(0) - { - } + OptionGroupFindMemory() : OptionGroup(), m_count(1), m_offset(0) {} ~OptionGroupFindMemory() override = default; - uint32_t - GetNumDefinitions () override - { - return sizeof (g_memory_find_option_table) / sizeof (OptionDefinition); + uint32_t GetNumDefinitions() override { + return sizeof(g_memory_find_option_table) / sizeof(OptionDefinition); } - - const OptionDefinition* - GetDefinitions () override - { + + const OptionDefinition *GetDefinitions() override { return g_memory_find_option_table; } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_memory_find_option_table[option_idx].short_option; - - switch (short_option) - { - case 'e': - m_expr.SetValueFromString(option_arg); - break; - - case 's': - m_string.SetValueFromString(option_arg); - break; - - case 'c': - if (m_count.SetValueFromString(option_arg).Fail()) - error.SetErrorString("unrecognized value for count"); - break; - - case 'o': - if (m_offset.SetValueFromString(option_arg).Fail()) - error.SetErrorString("unrecognized value for dump-offset"); - break; - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - return error; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = + g_memory_find_option_table[option_idx].short_option; + + switch (short_option) { + case 'e': + m_expr.SetValueFromString(option_arg); + break; + + case 's': + m_string.SetValueFromString(option_arg); + break; + + case 'c': + if (m_count.SetValueFromString(option_arg).Fail()) + error.SetErrorString("unrecognized value for count"); + break; + + case 'o': + if (m_offset.SetValueFromString(option_arg).Fail()) + error.SetErrorString("unrecognized value for dump-offset"); + break; + + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } + return error; } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_expr.Clear(); - m_string.Clear(); - m_count.Clear(); + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_expr.Clear(); + m_string.Clear(); + m_count.Clear(); } - - OptionValueString m_expr; - OptionValueString m_string; - OptionValueUInt64 m_count; - OptionValueUInt64 m_offset; + + OptionValueString m_expr; + OptionValueString m_string; + OptionValueUInt64 m_count; + OptionValueUInt64 m_offset; }; CommandObjectMemoryFind(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "memory find", "Find a value in the memory of the current target process.", - nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched), - m_option_group(), - m_memory_options() - { + : CommandObjectParsed( + interpreter, "memory find", + "Find a value in the memory of the current target process.", + nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched), + m_option_group(), m_memory_options() { CommandArgumentEntry arg1; CommandArgumentEntry arg2; CommandArgumentData addr_arg; CommandArgumentData value_arg; - + // Define the first (and only) variant of this arg. addr_arg.arg_type = eArgTypeAddressOrExpression; addr_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (addr_arg); - + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(addr_arg); + // Define the first (and only) variant of this arg. value_arg.arg_type = eArgTypeAddressOrExpression; value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (value_arg); - + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(value_arg); + // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - - m_option_group.Append (&m_memory_options); + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + + m_option_group.Append(&m_memory_options); m_option_group.Finalize(); } ~CommandObjectMemoryFind() override = default; - Options * - GetOptions () override - { - return &m_option_group; - } - + Options *GetOptions() override { return &m_option_group; } + protected: - class ProcessMemoryIterator - { + class ProcessMemoryIterator { public: - ProcessMemoryIterator (ProcessSP process_sp, - lldb::addr_t base) : - m_process_sp(process_sp), - m_base_addr(base), - m_is_valid(true) - { - lldbassert(process_sp.get() != nullptr); - } - - bool - IsValid () - { - return m_is_valid; - } - - uint8_t - operator [](lldb::addr_t offset) - { - if (!IsValid()) - return 0; - - uint8_t retval = 0; - Error error; - if (0 == m_process_sp->ReadMemory(m_base_addr+offset, &retval, 1, error)) - { - m_is_valid = false; - return 0; - } + ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base) + : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) { + lldbassert(process_sp.get() != nullptr); + } - return retval; + bool IsValid() { return m_is_valid; } + + uint8_t operator[](lldb::addr_t offset) { + if (!IsValid()) + return 0; + + uint8_t retval = 0; + Error error; + if (0 == + m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) { + m_is_valid = false; + return 0; } + + return retval; + } + private: - ProcessSP m_process_sp; - lldb::addr_t m_base_addr; - bool m_is_valid; + ProcessSP m_process_sp; + lldb::addr_t m_base_addr; + bool m_is_valid; }; - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // No need to check "process" for validity as eCommandRequiresProcess ensures it is valid - Process *process = m_exe_ctx.GetProcessPtr(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + // No need to check "process" for validity as eCommandRequiresProcess + // ensures it is valid + Process *process = m_exe_ctx.GetProcessPtr(); - const size_t argc = command.GetArgumentCount(); + const size_t argc = command.GetArgumentCount(); - if (argc != 2) - { - result.AppendError("two addresses needed for memory find"); - return false; - } + if (argc != 2) { + result.AppendError("two addresses needed for memory find"); + return false; + } - Error error; - lldb::addr_t low_addr = Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0),LLDB_INVALID_ADDRESS,&error); - if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) - { - result.AppendError("invalid low address"); + Error error; + lldb::addr_t low_addr = + Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), + LLDB_INVALID_ADDRESS, &error); + if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) { + result.AppendError("invalid low address"); + return false; + } + lldb::addr_t high_addr = + Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1), + LLDB_INVALID_ADDRESS, &error); + if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) { + result.AppendError("invalid high address"); + return false; + } + + if (high_addr <= low_addr) { + result.AppendError( + "starting address must be smaller than ending address"); + return false; + } + + lldb::addr_t found_location = LLDB_INVALID_ADDRESS; + + DataBufferHeap buffer; + + if (m_memory_options.m_string.OptionWasSet()) + buffer.CopyData(m_memory_options.m_string.GetStringValue(), + strlen(m_memory_options.m_string.GetStringValue())); + else if (m_memory_options.m_expr.OptionWasSet()) { + StackFrame *frame = m_exe_ctx.GetFramePtr(); + ValueObjectSP result_sp; + if ((eExpressionCompleted == + process->GetTarget().EvaluateExpression( + m_memory_options.m_expr.GetStringValue(), frame, result_sp)) && + result_sp) { + uint64_t value = result_sp->GetValueAsUnsigned(0); + switch (result_sp->GetCompilerType().GetByteSize(nullptr)) { + case 1: { + uint8_t byte = (uint8_t)value; + buffer.CopyData(&byte, 1); + } break; + case 2: { + uint16_t word = (uint16_t)value; + buffer.CopyData(&word, 2); + } break; + case 4: { + uint32_t lword = (uint32_t)value; + buffer.CopyData(&lword, 4); + } break; + case 8: { + buffer.CopyData(&value, 8); + } break; + case 3: + case 5: + case 6: + case 7: + result.AppendError("unknown type. pass a string instead"); return false; - } - lldb::addr_t high_addr = Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1),LLDB_INVALID_ADDRESS,&error); - if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) - { - result.AppendError("invalid high address"); + default: + result.AppendError( + "result size larger than 8 bytes. pass a string instead"); return false; + } + } else { + result.AppendError( + "expression evaluation failed. pass a string instead"); + return false; } + } else { + result.AppendError( + "please pass either a block of text, or an expression to evaluate."); + return false; + } - if (high_addr <= low_addr) - { - result.AppendError("starting address must be smaller than ending address"); - return false; + size_t count = m_memory_options.m_count.GetCurrentValue(); + found_location = low_addr; + bool ever_found = false; + while (count) { + found_location = FastSearch(found_location, high_addr, buffer.GetBytes(), + buffer.GetByteSize()); + if (found_location == LLDB_INVALID_ADDRESS) { + if (!ever_found) { + result.AppendMessage("data not found within the range.\n"); + result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); + } else + result.AppendMessage("no more matches within the range.\n"); + break; } - - lldb::addr_t found_location = LLDB_INVALID_ADDRESS; - - DataBufferHeap buffer; - - if (m_memory_options.m_string.OptionWasSet()) - buffer.CopyData(m_memory_options.m_string.GetStringValue(), strlen(m_memory_options.m_string.GetStringValue())); - else if (m_memory_options.m_expr.OptionWasSet()) - { - StackFrame* frame = m_exe_ctx.GetFramePtr(); - ValueObjectSP result_sp; - if ((eExpressionCompleted == process->GetTarget().EvaluateExpression(m_memory_options.m_expr.GetStringValue(), frame, result_sp)) && - result_sp) - { - uint64_t value = result_sp->GetValueAsUnsigned(0); - switch (result_sp->GetCompilerType().GetByteSize(nullptr)) - { - case 1: { - uint8_t byte = (uint8_t)value; - buffer.CopyData(&byte,1); - } - break; - case 2: { - uint16_t word = (uint16_t)value; - buffer.CopyData(&word,2); - } - break; - case 4: { - uint32_t lword = (uint32_t)value; - buffer.CopyData(&lword,4); - } - break; - case 8: { - buffer.CopyData(&value, 8); - } - break; - case 3: - case 5: - case 6: - case 7: - result.AppendError("unknown type. pass a string instead"); - return false; - default: - result.AppendError("result size larger than 8 bytes. pass a string instead"); - return false; - } - } - else - { - result.AppendError("expression evaluation failed. pass a string instead"); - return false; - } + result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n", + found_location); + + DataBufferHeap dumpbuffer(32, 0); + process->ReadMemory( + found_location + m_memory_options.m_offset.GetCurrentValue(), + dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error); + if (!error.Fail()) { + DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), + process->GetByteOrder(), + process->GetAddressByteSize()); + data.Dump(&result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1, + dumpbuffer.GetByteSize(), 16, + found_location + m_memory_options.m_offset.GetCurrentValue(), + 0, 0); + result.GetOutputStream().EOL(); } - else - { - result.AppendError("please pass either a block of text, or an expression to evaluate."); - return false; - } - - size_t count = m_memory_options.m_count.GetCurrentValue(); - found_location = low_addr; - bool ever_found = false; - while (count) - { - found_location = FastSearch(found_location, high_addr, buffer.GetBytes(), buffer.GetByteSize()); - if (found_location == LLDB_INVALID_ADDRESS) - { - if (!ever_found) - { - result.AppendMessage("data not found within the range.\n"); - result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); - } - else - result.AppendMessage("no more matches within the range.\n"); - break; - } - result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n", found_location); - - DataBufferHeap dumpbuffer(32,0); - process->ReadMemory(found_location+m_memory_options.m_offset.GetCurrentValue(), dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error); - if (!error.Fail()) - { - DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), process->GetByteOrder(), process->GetAddressByteSize()); - data.Dump(&result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1, dumpbuffer.GetByteSize(), 16, found_location+m_memory_options.m_offset.GetCurrentValue(), 0, 0); - result.GetOutputStream().EOL(); - } - --count; - found_location++; - ever_found = true; - } - - result.SetStatus(lldb::eReturnStatusSuccessFinishResult); - return true; + --count; + found_location++; + ever_found = true; + } + + result.SetStatus(lldb::eReturnStatusSuccessFinishResult); + return true; } - - lldb::addr_t - FastSearch (lldb::addr_t low, - lldb::addr_t high, - uint8_t *buffer, - size_t buffer_size) - { - const size_t region_size = high-low; - - if (region_size < buffer_size) - return LLDB_INVALID_ADDRESS; - - std::vector bad_char_heuristic(256, buffer_size); - ProcessSP process_sp = m_exe_ctx.GetProcessSP(); - ProcessMemoryIterator iterator(process_sp, low); - - for (size_t idx = 0; - idx < buffer_size-1; - idx++) - { - decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx]; - bad_char_heuristic[bcu_idx] = buffer_size - idx - 1; - } - for (size_t s = 0; - s <= (region_size - buffer_size); - ) - { - int64_t j = buffer_size-1; - while (j >= 0 && buffer[j] == iterator[s + j]) - j--; - if (j < 0) - return low+s; - else - s += bad_char_heuristic[iterator[s + buffer_size - 1]]; - } - - return LLDB_INVALID_ADDRESS; + + lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer, + size_t buffer_size) { + const size_t region_size = high - low; + + if (region_size < buffer_size) + return LLDB_INVALID_ADDRESS; + + std::vector bad_char_heuristic(256, buffer_size); + ProcessSP process_sp = m_exe_ctx.GetProcessSP(); + ProcessMemoryIterator iterator(process_sp, low); + + for (size_t idx = 0; idx < buffer_size - 1; idx++) { + decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx]; + bad_char_heuristic[bcu_idx] = buffer_size - idx - 1; } - - OptionGroupOptions m_option_group; - OptionGroupFindMemory m_memory_options; + for (size_t s = 0; s <= (region_size - buffer_size);) { + int64_t j = buffer_size - 1; + while (j >= 0 && buffer[j] == iterator[s + j]) + j--; + if (j < 0) + return low + s; + else + s += bad_char_heuristic[iterator[s + buffer_size - 1]]; + } + + return LLDB_INVALID_ADDRESS; + } + + OptionGroupOptions m_option_group; + OptionGroupFindMemory m_memory_options; }; -OptionDefinition -g_memory_write_option_table[] = -{ - // clang-format off +OptionDefinition g_memory_write_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Write memory using the contents of a file."}, {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "Start writing bytes from an offset within the input file."}, - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // Write memory to the inferior process //---------------------------------------------------------------------- -class CommandObjectMemoryWrite : public CommandObjectParsed -{ +class CommandObjectMemoryWrite : public CommandObjectParsed { public: - class OptionGroupWriteMemory : public OptionGroup - { - public: - OptionGroupWriteMemory () : - OptionGroup() - { - } + class OptionGroupWriteMemory : public OptionGroup { + public: + OptionGroupWriteMemory() : OptionGroup() {} - ~OptionGroupWriteMemory() override = default; + ~OptionGroupWriteMemory() override = default; - uint32_t - GetNumDefinitions () override - { - return sizeof (g_memory_write_option_table) / sizeof (OptionDefinition); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_memory_write_option_table; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_memory_write_option_table[option_idx].short_option; - - switch (short_option) - { - case 'i': - m_infile.SetFile (option_arg, true); - if (!m_infile.Exists()) - { - m_infile.Clear(); - error.SetErrorStringWithFormat("input file does not exist: '%s'", option_arg); - } - break; - - case 'o': - { - bool success; - m_infile_offset = StringConvert::ToUInt64(option_arg, 0, 0, &success); - if (!success) - { - error.SetErrorStringWithFormat("invalid offset string '%s'", option_arg); - } - } - break; - - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - return error; + uint32_t GetNumDefinitions() override { + return sizeof(g_memory_write_option_table) / sizeof(OptionDefinition); + } + + const OptionDefinition *GetDefinitions() override { + return g_memory_write_option_table; + } + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = + g_memory_write_option_table[option_idx].short_option; + + switch (short_option) { + case 'i': + m_infile.SetFile(option_arg, true); + if (!m_infile.Exists()) { + m_infile.Clear(); + error.SetErrorStringWithFormat("input file does not exist: '%s'", + option_arg); } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_infile.Clear(); - m_infile_offset = 0; + break; + + case 'o': { + bool success; + m_infile_offset = StringConvert::ToUInt64(option_arg, 0, 0, &success); + if (!success) { + error.SetErrorStringWithFormat("invalid offset string '%s'", + option_arg); } + } break; - FileSpec m_infile; - off_t m_infile_offset; - }; - - CommandObjectMemoryWrite(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "memory write", "Write to the memory of the current target process.", - nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched), - m_option_group(), - m_format_options(eFormatBytes, 1, UINT64_MAX), - m_memory_options() - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData addr_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - addr_arg.arg_type = eArgTypeAddress; - addr_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (addr_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlus; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - - m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT, LLDB_OPT_SET_1); - m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_SIZE , LLDB_OPT_SET_1|LLDB_OPT_SET_2); - m_option_group.Append (&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2); - m_option_group.Finalize(); + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } + return error; } - ~CommandObjectMemoryWrite() override = default; - - Options * - GetOptions () override - { - return &m_option_group; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_infile.Clear(); + m_infile_offset = 0; } - bool - UIntValueIsValidForSize (uint64_t uval64, size_t total_byte_size) - { - if (total_byte_size > 8) - return false; + FileSpec m_infile; + off_t m_infile_offset; + }; - if (total_byte_size == 8) - return true; + CommandObjectMemoryWrite(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "memory write", + "Write to the memory of the current target process.", nullptr, + eCommandRequiresProcess | eCommandProcessMustBeLaunched), + m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX), + m_memory_options() { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData addr_arg; + CommandArgumentData value_arg; - const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1; - return uval64 <= max; + // Define the first (and only) variant of this arg. + addr_arg.arg_type = eArgTypeAddress; + addr_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(addr_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlus; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_FORMAT, + LLDB_OPT_SET_1); + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_SIZE, + LLDB_OPT_SET_1 | LLDB_OPT_SET_2); + m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2); + m_option_group.Finalize(); + } + + ~CommandObjectMemoryWrite() override = default; + + Options *GetOptions() override { return &m_option_group; } + + bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) { + if (total_byte_size > 8) + return false; + + if (total_byte_size == 8) + return true; + + const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1; + return uval64 <= max; + } + + bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) { + if (total_byte_size > 8) + return false; + + if (total_byte_size == 8) + return true; + + const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1; + const int64_t min = ~(max); + return min <= sval64 && sval64 <= max; + } + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + // No need to check "process" for validity as eCommandRequiresProcess + // ensures it is valid + Process *process = m_exe_ctx.GetProcessPtr(); + + const size_t argc = command.GetArgumentCount(); + + if (m_memory_options.m_infile) { + if (argc < 1) { + result.AppendErrorWithFormat( + "%s takes a destination address when writing file contents.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else if (argc < 2) { + result.AppendErrorWithFormat( + "%s takes a destination address and at least one value.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } - bool - SIntValueIsValidForSize (int64_t sval64, size_t total_byte_size) - { - if (total_byte_size > 8) - return false; + StreamString buffer( + Stream::eBinary, + process->GetTarget().GetArchitecture().GetAddressByteSize(), + process->GetTarget().GetArchitecture().GetByteOrder()); - if (total_byte_size == 8) - return true; + OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); + size_t item_byte_size = byte_size_value.GetCurrentValue(); + + Error error; + lldb::addr_t addr = + Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), + LLDB_INVALID_ADDRESS, &error); - const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1; - const int64_t min = ~(max); - return min <= sval64 && sval64 <= max; + if (addr == LLDB_INVALID_ADDRESS) { + result.AppendError("invalid address expression\n"); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // No need to check "process" for validity as eCommandRequiresProcess ensures it is valid - Process *process = m_exe_ctx.GetProcessPtr(); - - const size_t argc = command.GetArgumentCount(); - - if (m_memory_options.m_infile) - { - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes a destination address when writing file contents.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else if (argc < 2) - { - result.AppendErrorWithFormat ("%s takes a destination address and at least one value.\n", m_cmd_name.c_str()); + if (m_memory_options.m_infile) { + size_t length = SIZE_MAX; + if (item_byte_size > 1) + length = item_byte_size; + lldb::DataBufferSP data_sp(m_memory_options.m_infile.ReadFileContents( + m_memory_options.m_infile_offset, length)); + if (data_sp) { + length = data_sp->GetByteSize(); + if (length > 0) { + Error error; + size_t bytes_written = + process->WriteMemory(addr, data_sp->GetBytes(), length, error); + + if (bytes_written == length) { + // All bytes written + result.GetOutputStream().Printf( + "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n", + (uint64_t)bytes_written, addr); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else if (bytes_written > 0) { + // Some byte written + result.GetOutputStream().Printf( + "%" PRIu64 " bytes of %" PRIu64 + " requested were written to 0x%" PRIx64 "\n", + (uint64_t)bytes_written, (uint64_t)length, addr); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 + " failed: %s.\n", + addr, error.AsCString()); result.SetStatus(eReturnStatusFailed); - return false; + } } + } else { + result.AppendErrorWithFormat("Unable to read contents of file.\n"); + result.SetStatus(eReturnStatusFailed); + } + return result.Succeeded(); + } else if (item_byte_size == 0) { + if (m_format_options.GetFormat() == eFormatPointer) + item_byte_size = buffer.GetAddressByteSize(); + else + item_byte_size = 1; + } - StreamString buffer (Stream::eBinary, - process->GetTarget().GetArchitecture().GetAddressByteSize(), - process->GetTarget().GetArchitecture().GetByteOrder()); - - OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); - size_t item_byte_size = byte_size_value.GetCurrentValue(); - - Error error; - lldb::addr_t addr = Args::StringToAddress (&m_exe_ctx, - command.GetArgumentAtIndex(0), - LLDB_INVALID_ADDRESS, - &error); - - if (addr == LLDB_INVALID_ADDRESS) - { - result.AppendError("invalid address expression\n"); - result.AppendError(error.AsCString()); + command.Shift(); // shift off the address argument + uint64_t uval64; + int64_t sval64; + bool success = false; + const size_t num_value_args = command.GetArgumentCount(); + for (size_t i = 0; i < num_value_args; ++i) { + const char *value_str = command.GetArgumentAtIndex(i); + + switch (m_format_options.GetFormat()) { + case kNumFormats: + case eFormatFloat: // TODO: add support for floats soon + case eFormatCharPrintable: + case eFormatBytesWithASCII: + case eFormatComplex: + case eFormatEnum: + case eFormatUnicode16: + case eFormatUnicode32: + case eFormatVectorOfChar: + case eFormatVectorOfSInt8: + case eFormatVectorOfUInt8: + case eFormatVectorOfSInt16: + case eFormatVectorOfUInt16: + case eFormatVectorOfSInt32: + case eFormatVectorOfUInt32: + case eFormatVectorOfSInt64: + case eFormatVectorOfUInt64: + case eFormatVectorOfFloat16: + case eFormatVectorOfFloat32: + case eFormatVectorOfFloat64: + case eFormatVectorOfUInt128: + case eFormatOSType: + case eFormatComplexInteger: + case eFormatAddressInfo: + case eFormatHexFloat: + case eFormatInstruction: + case eFormatVoid: + result.AppendError("unsupported format for writing memory"); + result.SetStatus(eReturnStatusFailed); + return false; + + case eFormatDefault: + case eFormatBytes: + case eFormatHex: + case eFormatHexUppercase: + case eFormatPointer: + // Decode hex bytes + uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 16, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid hex string value.\n", value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { + result.AppendErrorWithFormat("Value 0x%" PRIx64 + " is too large to fit in a %" PRIu64 + " byte unsigned integer value.\n", + uval64, (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; + } + buffer.PutMaxHex64(uval64, item_byte_size); + break; + + case eFormatBoolean: + uval64 = Args::StringToBoolean(value_str, false, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid boolean string value.\n", value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } + buffer.PutMaxHex64(uval64, item_byte_size); + break; + + case eFormatBinary: + uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 2, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid binary string value.\n", value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { + result.AppendErrorWithFormat("Value 0x%" PRIx64 + " is too large to fit in a %" PRIu64 + " byte unsigned integer value.\n", + uval64, (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; + } + buffer.PutMaxHex64(uval64, item_byte_size); + break; + + case eFormatCharArray: + case eFormatChar: + case eFormatCString: + if (value_str[0]) { + size_t len = strlen(value_str); + // Include the NULL for C strings... + if (m_format_options.GetFormat() == eFormatCString) + ++len; + Error error; + if (process->WriteMemory(addr, value_str, len, error) == len) { + addr += len; + } else { + result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 + " failed: %s.\n", + addr, error.AsCString()); result.SetStatus(eReturnStatusFailed); return false; + } } - - if (m_memory_options.m_infile) - { - size_t length = SIZE_MAX; - if (item_byte_size > 1) - length = item_byte_size; - lldb::DataBufferSP data_sp (m_memory_options.m_infile.ReadFileContents (m_memory_options.m_infile_offset, length)); - if (data_sp) - { - length = data_sp->GetByteSize(); - if (length > 0) - { - Error error; - size_t bytes_written = process->WriteMemory (addr, data_sp->GetBytes(), length, error); - - if (bytes_written == length) - { - // All bytes written - result.GetOutputStream().Printf("%" PRIu64 " bytes were written to 0x%" PRIx64 "\n", (uint64_t)bytes_written, addr); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else if (bytes_written > 0) - { - // Some byte written - result.GetOutputStream().Printf("%" PRIu64 " bytes of %" PRIu64 " requested were written to 0x%" PRIx64 "\n", (uint64_t)bytes_written, (uint64_t)length, addr); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Memory write to 0x%" PRIx64 " failed: %s.\n", addr, error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } - } - } - else - { - result.AppendErrorWithFormat ("Unable to read contents of file.\n"); - result.SetStatus(eReturnStatusFailed); - } - return result.Succeeded(); + break; + + case eFormatDecimal: + sval64 = StringConvert::ToSInt64(value_str, INT64_MAX, 0, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid signed decimal value.\n", value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) { + result.AppendErrorWithFormat( + "Value %" PRIi64 " is too large or small to fit in a %" PRIu64 + " byte signed integer value.\n", + sval64, (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; } - else if (item_byte_size == 0) - { - if (m_format_options.GetFormat() == eFormatPointer) - item_byte_size = buffer.GetAddressByteSize(); - else - item_byte_size = 1; + buffer.PutMaxHex64(sval64, item_byte_size); + break; + + case eFormatUnsigned: + uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 0, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid unsigned decimal string value.\n", + value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { + result.AppendErrorWithFormat("Value %" PRIu64 + " is too large to fit in a %" PRIu64 + " byte unsigned integer value.\n", + uval64, (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; } - - command.Shift(); // shift off the address argument - uint64_t uval64; - int64_t sval64; - bool success = false; - const size_t num_value_args = command.GetArgumentCount(); - for (size_t i=0; iWriteMemory (addr, value_str, len, error) == len) - { - addr += len; - } - else - { - result.AppendErrorWithFormat ("Memory write to 0x%" PRIx64 " failed: %s.\n", addr, error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - break; - - case eFormatDecimal: - sval64 = StringConvert::ToSInt64(value_str, INT64_MAX, 0, &success); - if (!success) - { - result.AppendErrorWithFormat ("'%s' is not a valid signed decimal value.\n", value_str); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (!SIntValueIsValidForSize (sval64, item_byte_size)) - { - result.AppendErrorWithFormat ("Value %" PRIi64 " is too large or small to fit in a %" PRIu64 " byte signed integer value.\n", sval64, (uint64_t)item_byte_size); - result.SetStatus(eReturnStatusFailed); - return false; - } - buffer.PutMaxHex64 (sval64, item_byte_size); - break; - - case eFormatUnsigned: - uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 0, &success); - if (!success) - { - result.AppendErrorWithFormat ("'%s' is not a valid unsigned decimal string value.\n", value_str); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (!UIntValueIsValidForSize (uval64, item_byte_size)) - { - result.AppendErrorWithFormat ("Value %" PRIu64 " is too large to fit in a %" PRIu64 " byte unsigned integer value.\n", uval64, (uint64_t)item_byte_size); - result.SetStatus(eReturnStatusFailed); - return false; - } - buffer.PutMaxHex64 (uval64, item_byte_size); - break; - - case eFormatOctal: - uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 8, &success); - if (!success) - { - result.AppendErrorWithFormat ("'%s' is not a valid octal string value.\n", value_str); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (!UIntValueIsValidForSize (uval64, item_byte_size)) - { - result.AppendErrorWithFormat ("Value %" PRIo64 " is too large to fit in a %" PRIu64 " byte unsigned integer value.\n", uval64, (uint64_t)item_byte_size); - result.SetStatus(eReturnStatusFailed); - return false; - } - buffer.PutMaxHex64 (uval64, item_byte_size); - break; - } + buffer.PutMaxHex64(uval64, item_byte_size); + break; + + case eFormatOctal: + uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 8, &success); + if (!success) { + result.AppendErrorWithFormat( + "'%s' is not a valid octal string value.\n", value_str); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { + result.AppendErrorWithFormat("Value %" PRIo64 + " is too large to fit in a %" PRIu64 + " byte unsigned integer value.\n", + uval64, (uint64_t)item_byte_size); + result.SetStatus(eReturnStatusFailed); + return false; } + buffer.PutMaxHex64(uval64, item_byte_size); + break; + } + } - if (!buffer.GetString().empty()) - { - Error error; - if (process->WriteMemory (addr, buffer.GetString().c_str(), buffer.GetString().size(), error) == buffer.GetString().size()) - return true; - else - { - result.AppendErrorWithFormat ("Memory write to 0x%" PRIx64 " failed: %s.\n", addr, error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } + if (!buffer.GetString().empty()) { + Error error; + if (process->WriteMemory(addr, buffer.GetString().c_str(), + buffer.GetString().size(), + error) == buffer.GetString().size()) return true; + else { + result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 + " failed: %s.\n", + addr, error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } } + return true; + } - OptionGroupOptions m_option_group; - OptionGroupFormat m_format_options; - OptionGroupWriteMemory m_memory_options; + OptionGroupOptions m_option_group; + OptionGroupFormat m_format_options; + OptionGroupWriteMemory m_memory_options; }; //---------------------------------------------------------------------- // Get malloc/free history of a memory address. //---------------------------------------------------------------------- -class CommandObjectMemoryHistory : public CommandObjectParsed -{ +class CommandObjectMemoryHistory : public CommandObjectParsed { public: - CommandObjectMemoryHistory(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "memory history", - "Print recorded stack traces for allocation/deallocation events associated with an address.", nullptr, - eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBePaused | - eCommandProcessMustBeLaunched) - { - CommandArgumentEntry arg1; - CommandArgumentData addr_arg; - - // Define the first (and only) variant of this arg. - addr_arg.arg_type = eArgTypeAddress; - addr_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (addr_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); + CommandObjectMemoryHistory(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "memory history", "Print recorded stack traces for " + "allocation/deallocation events " + "associated with an address.", + nullptr, + eCommandRequiresTarget | eCommandRequiresProcess | + eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) { + CommandArgumentEntry arg1; + CommandArgumentData addr_arg; + + // Define the first (and only) variant of this arg. + addr_arg.arg_type = eArgTypeAddress; + addr_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(addr_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectMemoryHistory() override = default; + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + return m_cmd_name.c_str(); + } + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc == 0 || argc > 1) { + result.AppendErrorWithFormat("%s takes an address expression", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectMemoryHistory() override = default; + Error error; + lldb::addr_t addr = + Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), + LLDB_INVALID_ADDRESS, &error); - const char * - GetRepeatCommand (Args ¤t_command_args, uint32_t index) override - { - return m_cmd_name.c_str(); + if (addr == LLDB_INVALID_ADDRESS) { + result.AppendError("invalid address expression"); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } - -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc == 0 || argc > 1) - { - result.AppendErrorWithFormat ("%s takes an address expression", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - Error error; - lldb::addr_t addr = Args::StringToAddress (&m_exe_ctx, - command.GetArgumentAtIndex(0), - LLDB_INVALID_ADDRESS, - &error); - - if (addr == LLDB_INVALID_ADDRESS) - { - result.AppendError("invalid address expression"); - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - Stream *output_stream = &result.GetOutputStream(); - - const ProcessSP &process_sp = m_exe_ctx.GetProcessSP(); - const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(process_sp); - - if (!memory_history) - { - result.AppendError("no available memory history provider"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - HistoryThreads thread_list = memory_history->GetHistoryThreads(addr); - - for (auto thread : thread_list) { - thread->GetStatus(*output_stream, 0, UINT32_MAX, 0); - } - - result.SetStatus(eReturnStatusSuccessFinishResult); - - return true; + + Stream *output_stream = &result.GetOutputStream(); + + const ProcessSP &process_sp = m_exe_ctx.GetProcessSP(); + const MemoryHistorySP &memory_history = + MemoryHistory::FindPlugin(process_sp); + + if (!memory_history) { + result.AppendError("no available memory history provider"); + result.SetStatus(eReturnStatusFailed); + return false; } + + HistoryThreads thread_list = memory_history->GetHistoryThreads(addr); + + for (auto thread : thread_list) { + thread->GetStatus(*output_stream, 0, UINT32_MAX, 0); + } + + result.SetStatus(eReturnStatusSuccessFinishResult); + + return true; + } }; //------------------------------------------------------------------------- @@ -1827,102 +1693,90 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectMemoryRegion -class CommandObjectMemoryRegion : public CommandObjectParsed -{ +class CommandObjectMemoryRegion : public CommandObjectParsed { public: - CommandObjectMemoryRegion(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "memory region", - "Get information on the memory region containing an address in the current target process.", - "memory region ADDR", eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched), - m_prev_end_addr(LLDB_INVALID_ADDRESS) - { - } + CommandObjectMemoryRegion(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "memory region", + "Get information on the memory region containing " + "an address in the current target process.", + "memory region ADDR", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched), + m_prev_end_addr(LLDB_INVALID_ADDRESS) {} - ~CommandObjectMemoryRegion() override = default; + ~CommandObjectMemoryRegion() override = default; protected: - bool - DoExecute(Args &command, CommandReturnObject &result) override - { - ProcessSP process_sp = m_exe_ctx.GetProcessSP(); - if (process_sp) - { - Error error; - lldb::addr_t load_addr = m_prev_end_addr; - m_prev_end_addr = LLDB_INVALID_ADDRESS; - - const size_t argc = command.GetArgumentCount(); - if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) - { - result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n", m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus(eReturnStatusFailed); - } - else - { - const char *load_addr_cstr = command.GetArgumentAtIndex(0); - if (command.GetArgumentCount() == 1) - { - load_addr = Args::StringToAddress(&m_exe_ctx, load_addr_cstr, LLDB_INVALID_ADDRESS, &error); - if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) - { - result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n", load_addr_cstr, - error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } - } - - lldb_private::MemoryRegionInfo range_info; - error = process_sp->GetMemoryRegionInfo(load_addr, range_info); - if (error.Success()) - { - lldb_private::Address addr; - ConstString section_name; - if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) - { - SectionSP section_sp(addr.GetSection()); - if (section_sp) - { - // Got the top most section, not the deepest section - while (section_sp->GetParent()) - section_sp = section_sp->GetParent(); - section_name = section_sp->GetName(); - } - } - result.AppendMessageWithFormat( - "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s\n", range_info.GetRange().GetRangeBase(), - range_info.GetRange().GetRangeEnd(), range_info.GetReadable() ? 'r' : '-', - range_info.GetWritable() ? 'w' : '-', range_info.GetExecutable() ? 'x' : '-', - section_name ? " " : "", section_name ? section_name.AsCString() : ""); - m_prev_end_addr = range_info.GetRange().GetRangeEnd(); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else - { - result.SetStatus(eReturnStatusFailed); - result.AppendErrorWithFormat("%s\n", error.AsCString()); - } - } - } - else - { - m_prev_end_addr = LLDB_INVALID_ADDRESS; - result.AppendError("invalid process"); + bool DoExecute(Args &command, CommandReturnObject &result) override { + ProcessSP process_sp = m_exe_ctx.GetProcessSP(); + if (process_sp) { + Error error; + lldb::addr_t load_addr = m_prev_end_addr; + m_prev_end_addr = LLDB_INVALID_ADDRESS; + + const size_t argc = command.GetArgumentCount(); + if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) { + result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); + } else { + const char *load_addr_cstr = command.GetArgumentAtIndex(0); + if (command.GetArgumentCount() == 1) { + load_addr = Args::StringToAddress(&m_exe_ctx, load_addr_cstr, + LLDB_INVALID_ADDRESS, &error); + if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) { + result.AppendErrorWithFormat( + "invalid address argument \"%s\": %s\n", load_addr_cstr, + error.AsCString()); result.SetStatus(eReturnStatusFailed); + } } - return result.Succeeded(); - } - const char * - GetRepeatCommand(Args ¤t_command_args, uint32_t index) override - { - // If we repeat this command, repeat it without any arguments so we can - // show the next memory range - return m_cmd_name.c_str(); + lldb_private::MemoryRegionInfo range_info; + error = process_sp->GetMemoryRegionInfo(load_addr, range_info); + if (error.Success()) { + lldb_private::Address addr; + ConstString section_name; + if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) { + SectionSP section_sp(addr.GetSection()); + if (section_sp) { + // Got the top most section, not the deepest section + while (section_sp->GetParent()) + section_sp = section_sp->GetParent(); + section_name = section_sp->GetName(); + } + } + result.AppendMessageWithFormat( + "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s\n", + range_info.GetRange().GetRangeBase(), + range_info.GetRange().GetRangeEnd(), + range_info.GetReadable() ? 'r' : '-', + range_info.GetWritable() ? 'w' : '-', + range_info.GetExecutable() ? 'x' : '-', section_name ? " " : "", + section_name ? section_name.AsCString() : ""); + m_prev_end_addr = range_info.GetRange().GetRangeEnd(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.SetStatus(eReturnStatusFailed); + result.AppendErrorWithFormat("%s\n", error.AsCString()); + } + } + } else { + m_prev_end_addr = LLDB_INVALID_ADDRESS; + result.AppendError("invalid process"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + // If we repeat this command, repeat it without any arguments so we can + // show the next memory range + return m_cmd_name.c_str(); + } - lldb::addr_t m_prev_end_addr; + lldb::addr_t m_prev_end_addr; }; //------------------------------------------------------------------------- @@ -1930,14 +1784,20 @@ protected: //------------------------------------------------------------------------- CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "memory", "Commands for operating on memory in the current target process.", - "memory []") -{ - LoadSubCommand("find", CommandObjectSP(new CommandObjectMemoryFind(interpreter))); - LoadSubCommand("read", CommandObjectSP(new CommandObjectMemoryRead(interpreter))); - LoadSubCommand("write", CommandObjectSP(new CommandObjectMemoryWrite(interpreter))); - LoadSubCommand("history", CommandObjectSP(new CommandObjectMemoryHistory(interpreter))); - LoadSubCommand("region", CommandObjectSP(new CommandObjectMemoryRegion(interpreter))); + : CommandObjectMultiword( + interpreter, "memory", + "Commands for operating on memory in the current target process.", + "memory []") { + LoadSubCommand("find", + CommandObjectSP(new CommandObjectMemoryFind(interpreter))); + LoadSubCommand("read", + CommandObjectSP(new CommandObjectMemoryRead(interpreter))); + LoadSubCommand("write", + CommandObjectSP(new CommandObjectMemoryWrite(interpreter))); + LoadSubCommand("history", + CommandObjectSP(new CommandObjectMemoryHistory(interpreter))); + LoadSubCommand("region", + CommandObjectSP(new CommandObjectMemoryRegion(interpreter))); } CommandObjectMemory::~CommandObjectMemory() = default; diff --git a/lldb/source/Commands/CommandObjectMemory.h b/lldb/source/Commands/CommandObjectMemory.h index cf5b4419746..9f3978baf76 100644 --- a/lldb/source/Commands/CommandObjectMemory.h +++ b/lldb/source/Commands/CommandObjectMemory.h @@ -18,12 +18,11 @@ namespace lldb_private { -class CommandObjectMemory : public CommandObjectMultiword -{ +class CommandObjectMemory : public CommandObjectMultiword { public: - CommandObjectMemory (CommandInterpreter &interpreter); + CommandObjectMemory(CommandInterpreter &interpreter); - ~CommandObjectMemory() override; + ~CommandObjectMemory() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectMultiword.cpp b/lldb/source/Commands/CommandObjectMultiword.cpp index c951e0bbfa0..dd60af0fc79 100644 --- a/lldb/source/Commands/CommandObjectMultiword.cpp +++ b/lldb/source/Commands/CommandObjectMultiword.cpp @@ -14,8 +14,8 @@ #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Core/Debugger.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" using namespace lldb; using namespace lldb_private; @@ -28,496 +28,388 @@ CommandObjectMultiword::CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, - uint32_t flags) : - CommandObject (interpreter, name, help, syntax, flags), - m_can_be_removed(false) -{ -} + uint32_t flags) + : CommandObject(interpreter, name, help, syntax, flags), + m_can_be_removed(false) {} CommandObjectMultiword::~CommandObjectMultiword() = default; -CommandObjectSP -CommandObjectMultiword::GetSubcommandSP (const char *sub_cmd, StringList *matches) -{ - CommandObjectSP return_cmd_sp; - CommandObject::CommandMap::iterator pos; - - if (!m_subcommand_dict.empty()) - { - pos = m_subcommand_dict.find (sub_cmd); - if (pos != m_subcommand_dict.end()) { - // An exact match; append the sub_cmd to the 'matches' string list. - if (matches) - matches->AppendString(sub_cmd); - return_cmd_sp = pos->second; - } - else - { - StringList local_matches; - if (matches == nullptr) - matches = &local_matches; - int num_matches = AddNamesMatchingPartialString (m_subcommand_dict, sub_cmd, *matches); - - if (num_matches == 1) - { - // Cleaner, but slightly less efficient would be to call back into this function, since I now - // know I have an exact match... - - sub_cmd = matches->GetStringAtIndex(0); - pos = m_subcommand_dict.find(sub_cmd); - if (pos != m_subcommand_dict.end()) - return_cmd_sp = pos->second; - } - } +CommandObjectSP CommandObjectMultiword::GetSubcommandSP(const char *sub_cmd, + StringList *matches) { + CommandObjectSP return_cmd_sp; + CommandObject::CommandMap::iterator pos; + + if (!m_subcommand_dict.empty()) { + pos = m_subcommand_dict.find(sub_cmd); + if (pos != m_subcommand_dict.end()) { + // An exact match; append the sub_cmd to the 'matches' string list. + if (matches) + matches->AppendString(sub_cmd); + return_cmd_sp = pos->second; + } else { + StringList local_matches; + if (matches == nullptr) + matches = &local_matches; + int num_matches = + AddNamesMatchingPartialString(m_subcommand_dict, sub_cmd, *matches); + + if (num_matches == 1) { + // Cleaner, but slightly less efficient would be to call back into this + // function, since I now + // know I have an exact match... + + sub_cmd = matches->GetStringAtIndex(0); + pos = m_subcommand_dict.find(sub_cmd); + if (pos != m_subcommand_dict.end()) + return_cmd_sp = pos->second; + } } - return return_cmd_sp; + } + return return_cmd_sp; } CommandObject * -CommandObjectMultiword::GetSubcommandObject (const char *sub_cmd, StringList *matches) -{ - return GetSubcommandSP(sub_cmd, matches).get(); +CommandObjectMultiword::GetSubcommandObject(const char *sub_cmd, + StringList *matches) { + return GetSubcommandSP(sub_cmd, matches).get(); } -bool -CommandObjectMultiword::LoadSubCommand(const char *name, - const CommandObjectSP& cmd_obj) -{ - if (cmd_obj) - assert((&GetCommandInterpreter() == &cmd_obj->GetCommandInterpreter()) && "tried to add a CommandObject from a different interpreter"); - - CommandMap::iterator pos; - bool success = true; - - pos = m_subcommand_dict.find(name); - if (pos == m_subcommand_dict.end()) - { - m_subcommand_dict[name] = cmd_obj; - } - else - success = false; +bool CommandObjectMultiword::LoadSubCommand(const char *name, + const CommandObjectSP &cmd_obj) { + if (cmd_obj) + assert((&GetCommandInterpreter() == &cmd_obj->GetCommandInterpreter()) && + "tried to add a CommandObject from a different interpreter"); + + CommandMap::iterator pos; + bool success = true; + + pos = m_subcommand_dict.find(name); + if (pos == m_subcommand_dict.end()) { + m_subcommand_dict[name] = cmd_obj; + } else + success = false; - return success; + return success; } -bool -CommandObjectMultiword::Execute(const char *args_string, CommandReturnObject &result) -{ - Args args (args_string); - const size_t argc = args.GetArgumentCount(); - if (argc == 0) - { - this->CommandObject::GenerateHelpText (result); - } - else - { - const char *sub_command = args.GetArgumentAtIndex (0); - - if (sub_command) - { - if (::strcasecmp (sub_command, "help") == 0) - { - this->CommandObject::GenerateHelpText (result); - } - else if (!m_subcommand_dict.empty()) - { - StringList matches; - CommandObject *sub_cmd_obj = GetSubcommandObject(sub_command, &matches); - if (sub_cmd_obj != nullptr) - { - // Now call CommandObject::Execute to process and options in 'rest_of_line'. From there - // the command-specific version of Execute will be called, with the processed arguments. - - args.Shift(); - - sub_cmd_obj->Execute (args_string, result); - } - else - { - std::string error_msg; - const size_t num_subcmd_matches = matches.GetSize(); - if (num_subcmd_matches > 0) - error_msg.assign ("ambiguous command "); - else - error_msg.assign ("invalid command "); - - error_msg.append ("'"); - error_msg.append (GetCommandName()); - error_msg.append (" "); - error_msg.append (sub_command); - error_msg.append ("'."); - - if (num_subcmd_matches > 0) - { - error_msg.append (" Possible completions:"); - for (size_t i = 0; i < num_subcmd_matches; i++) - { - error_msg.append ("\n\t"); - error_msg.append (matches.GetStringAtIndex (i)); - } - } - error_msg.append ("\n"); - result.AppendRawError (error_msg.c_str()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("'%s' does not have any subcommands.\n", GetCommandName()); - result.SetStatus (eReturnStatusFailed); +bool CommandObjectMultiword::Execute(const char *args_string, + CommandReturnObject &result) { + Args args(args_string); + const size_t argc = args.GetArgumentCount(); + if (argc == 0) { + this->CommandObject::GenerateHelpText(result); + } else { + const char *sub_command = args.GetArgumentAtIndex(0); + + if (sub_command) { + if (::strcasecmp(sub_command, "help") == 0) { + this->CommandObject::GenerateHelpText(result); + } else if (!m_subcommand_dict.empty()) { + StringList matches; + CommandObject *sub_cmd_obj = GetSubcommandObject(sub_command, &matches); + if (sub_cmd_obj != nullptr) { + // Now call CommandObject::Execute to process and options in + // 'rest_of_line'. From there + // the command-specific version of Execute will be called, with the + // processed arguments. + + args.Shift(); + + sub_cmd_obj->Execute(args_string, result); + } else { + std::string error_msg; + const size_t num_subcmd_matches = matches.GetSize(); + if (num_subcmd_matches > 0) + error_msg.assign("ambiguous command "); + else + error_msg.assign("invalid command "); + + error_msg.append("'"); + error_msg.append(GetCommandName()); + error_msg.append(" "); + error_msg.append(sub_command); + error_msg.append("'."); + + if (num_subcmd_matches > 0) { + error_msg.append(" Possible completions:"); + for (size_t i = 0; i < num_subcmd_matches; i++) { + error_msg.append("\n\t"); + error_msg.append(matches.GetStringAtIndex(i)); } + } + error_msg.append("\n"); + result.AppendRawError(error_msg.c_str()); + result.SetStatus(eReturnStatusFailed); } + } else { + result.AppendErrorWithFormat("'%s' does not have any subcommands.\n", + GetCommandName()); + result.SetStatus(eReturnStatusFailed); + } } + } - return result.Succeeded(); + return result.Succeeded(); } -void -CommandObjectMultiword::GenerateHelpText (Stream &output_stream) -{ - // First time through here, generate the help text for the object and - // push it to the return result object as well - - CommandObject::GenerateHelpText(output_stream); - output_stream.PutCString("\nThe following subcommands are supported:\n\n"); - - CommandMap::iterator pos; - uint32_t max_len = FindLongestCommandWord (m_subcommand_dict); - - if (max_len) - max_len += 4; // Indent the output by 4 spaces. - - for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) - { - std::string indented_command (" "); - indented_command.append (pos->first); - if (pos->second->WantsRawCommandString ()) - { - std::string help_text (pos->second->GetHelp()); - help_text.append(" Expects 'raw' input (see 'help raw-input'.)"); - m_interpreter.OutputFormattedHelpText (output_stream, - indented_command.c_str(), - "--", - help_text.c_str(), - max_len); - } - else - m_interpreter.OutputFormattedHelpText (output_stream, - indented_command.c_str(), - "--", - pos->second->GetHelp(), - max_len); - } - - output_stream.PutCString ("\nFor more help on any particular subcommand, type 'help '.\n"); +void CommandObjectMultiword::GenerateHelpText(Stream &output_stream) { + // First time through here, generate the help text for the object and + // push it to the return result object as well + + CommandObject::GenerateHelpText(output_stream); + output_stream.PutCString("\nThe following subcommands are supported:\n\n"); + + CommandMap::iterator pos; + uint32_t max_len = FindLongestCommandWord(m_subcommand_dict); + + if (max_len) + max_len += 4; // Indent the output by 4 spaces. + + for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) { + std::string indented_command(" "); + indented_command.append(pos->first); + if (pos->second->WantsRawCommandString()) { + std::string help_text(pos->second->GetHelp()); + help_text.append(" Expects 'raw' input (see 'help raw-input'.)"); + m_interpreter.OutputFormattedHelpText(output_stream, + indented_command.c_str(), "--", + help_text.c_str(), max_len); + } else + m_interpreter.OutputFormattedHelpText(output_stream, + indented_command.c_str(), "--", + pos->second->GetHelp(), max_len); + } + + output_stream.PutCString("\nFor more help on any particular subcommand, type " + "'help '.\n"); } -int -CommandObjectMultiword::HandleCompletion(Args &input, - int &cursor_index, - int &cursor_char_position, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) -{ - // Any of the command matches will provide a complete word, otherwise the individual - // completers will override this. - word_complete = true; - - const char *arg0 = input.GetArgumentAtIndex(0); - if (cursor_index == 0) - { - AddNamesMatchingPartialString (m_subcommand_dict, - arg0, - matches); - - if (matches.GetSize() == 1 - && matches.GetStringAtIndex(0) != nullptr - && strcmp (arg0, matches.GetStringAtIndex(0)) == 0) - { - StringList temp_matches; - CommandObject *cmd_obj = GetSubcommandObject (arg0, - &temp_matches); - if (cmd_obj != nullptr) - { - if (input.GetArgumentCount() == 1) - { - word_complete = true; - } - else - { - matches.DeleteStringAtIndex (0); - input.Shift(); - cursor_char_position = 0; - input.AppendArgument (""); - return cmd_obj->HandleCompletion (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - } - } +int CommandObjectMultiword::HandleCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + int match_start_point, + int max_return_elements, + bool &word_complete, + StringList &matches) { + // Any of the command matches will provide a complete word, otherwise the + // individual + // completers will override this. + word_complete = true; + + const char *arg0 = input.GetArgumentAtIndex(0); + if (cursor_index == 0) { + AddNamesMatchingPartialString(m_subcommand_dict, arg0, matches); + + if (matches.GetSize() == 1 && matches.GetStringAtIndex(0) != nullptr && + strcmp(arg0, matches.GetStringAtIndex(0)) == 0) { + StringList temp_matches; + CommandObject *cmd_obj = GetSubcommandObject(arg0, &temp_matches); + if (cmd_obj != nullptr) { + if (input.GetArgumentCount() == 1) { + word_complete = true; + } else { + matches.DeleteStringAtIndex(0); + input.Shift(); + cursor_char_position = 0; + input.AppendArgument(""); + return cmd_obj->HandleCompletion( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); } - return matches.GetSize(); + } } - else - { - CommandObject *sub_command_object = GetSubcommandObject (arg0, - &matches); - if (sub_command_object == nullptr) - { - return matches.GetSize(); - } - else - { - // Remove the one match that we got from calling GetSubcommandObject. - matches.DeleteStringAtIndex(0); - input.Shift(); - cursor_index--; - return sub_command_object->HandleCompletion (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - } + return matches.GetSize(); + } else { + CommandObject *sub_command_object = GetSubcommandObject(arg0, &matches); + if (sub_command_object == nullptr) { + return matches.GetSize(); + } else { + // Remove the one match that we got from calling GetSubcommandObject. + matches.DeleteStringAtIndex(0); + input.Shift(); + cursor_index--; + return sub_command_object->HandleCompletion( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); } + } } -const char * -CommandObjectMultiword::GetRepeatCommand (Args ¤t_command_args, uint32_t index) -{ - index++; - if (current_command_args.GetArgumentCount() <= index) - return nullptr; - CommandObject *sub_command_object = GetSubcommandObject (current_command_args.GetArgumentAtIndex(index)); - if (sub_command_object == nullptr) - return nullptr; - return sub_command_object->GetRepeatCommand(current_command_args, index); +const char *CommandObjectMultiword::GetRepeatCommand(Args ¤t_command_args, + uint32_t index) { + index++; + if (current_command_args.GetArgumentCount() <= index) + return nullptr; + CommandObject *sub_command_object = + GetSubcommandObject(current_command_args.GetArgumentAtIndex(index)); + if (sub_command_object == nullptr) + return nullptr; + return sub_command_object->GetRepeatCommand(current_command_args, index); } -void -CommandObjectMultiword::AproposAllSubCommands (const char *prefix, - const char *search_word, - StringList &commands_found, - StringList &commands_help) -{ - CommandObject::CommandMap::const_iterator pos; - - for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) - { - const char * command_name = pos->first.c_str(); - CommandObject *sub_cmd_obj = pos->second.get(); - StreamString complete_command_name; - - complete_command_name.Printf ("%s %s", prefix, command_name); - - if (sub_cmd_obj->HelpTextContainsWord (search_word)) - { - commands_found.AppendString (complete_command_name.GetData()); - commands_help.AppendString (sub_cmd_obj->GetHelp()); - } - - if (sub_cmd_obj->IsMultiwordObject()) - sub_cmd_obj->AproposAllSubCommands (complete_command_name.GetData(), - search_word, - commands_found, - commands_help); +void CommandObjectMultiword::AproposAllSubCommands(const char *prefix, + const char *search_word, + StringList &commands_found, + StringList &commands_help) { + CommandObject::CommandMap::const_iterator pos; + + for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) { + const char *command_name = pos->first.c_str(); + CommandObject *sub_cmd_obj = pos->second.get(); + StreamString complete_command_name; + + complete_command_name.Printf("%s %s", prefix, command_name); + + if (sub_cmd_obj->HelpTextContainsWord(search_word)) { + commands_found.AppendString(complete_command_name.GetData()); + commands_help.AppendString(sub_cmd_obj->GetHelp()); } -} -CommandObjectProxy::CommandObjectProxy (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax, - uint32_t flags) : - CommandObject (interpreter, name, help, syntax, flags) -{ + if (sub_cmd_obj->IsMultiwordObject()) + sub_cmd_obj->AproposAllSubCommands(complete_command_name.GetData(), + search_word, commands_found, + commands_help); + } } +CommandObjectProxy::CommandObjectProxy(CommandInterpreter &interpreter, + const char *name, const char *help, + const char *syntax, uint32_t flags) + : CommandObject(interpreter, name, help, syntax, flags) {} + CommandObjectProxy::~CommandObjectProxy() = default; -const char * -CommandObjectProxy::GetHelpLong () -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetHelpLong(); - return nullptr; +const char *CommandObjectProxy::GetHelpLong() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetHelpLong(); + return nullptr; } -bool -CommandObjectProxy::IsRemovable() const -{ - const CommandObject *proxy_command = const_cast(this)->GetProxyCommandObject(); - if (proxy_command) - return proxy_command->IsRemovable(); - return false; +bool CommandObjectProxy::IsRemovable() const { + const CommandObject *proxy_command = + const_cast(this)->GetProxyCommandObject(); + if (proxy_command) + return proxy_command->IsRemovable(); + return false; } -bool -CommandObjectProxy::IsMultiwordObject () -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->IsMultiwordObject(); - return false; +bool CommandObjectProxy::IsMultiwordObject() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->IsMultiwordObject(); + return false; } -CommandObjectMultiword* -CommandObjectProxy::GetAsMultiwordCommand () -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetAsMultiwordCommand(); - return nullptr; +CommandObjectMultiword *CommandObjectProxy::GetAsMultiwordCommand() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetAsMultiwordCommand(); + return nullptr; } -void -CommandObjectProxy::GenerateHelpText (Stream &result) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GenerateHelpText(result); +void CommandObjectProxy::GenerateHelpText(Stream &result) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GenerateHelpText(result); } -lldb::CommandObjectSP -CommandObjectProxy::GetSubcommandSP (const char *sub_cmd, StringList *matches) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetSubcommandSP(sub_cmd, matches); - return lldb::CommandObjectSP(); +lldb::CommandObjectSP CommandObjectProxy::GetSubcommandSP(const char *sub_cmd, + StringList *matches) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetSubcommandSP(sub_cmd, matches); + return lldb::CommandObjectSP(); } -CommandObject * -CommandObjectProxy::GetSubcommandObject (const char *sub_cmd, StringList *matches) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetSubcommandObject(sub_cmd, matches); - return nullptr; +CommandObject *CommandObjectProxy::GetSubcommandObject(const char *sub_cmd, + StringList *matches) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetSubcommandObject(sub_cmd, matches); + return nullptr; } -void -CommandObjectProxy::AproposAllSubCommands (const char *prefix, - const char *search_word, - StringList &commands_found, - StringList &commands_help) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->AproposAllSubCommands (prefix, - search_word, - commands_found, - commands_help); +void CommandObjectProxy::AproposAllSubCommands(const char *prefix, + const char *search_word, + StringList &commands_found, + StringList &commands_help) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->AproposAllSubCommands(prefix, search_word, + commands_found, commands_help); } -bool -CommandObjectProxy::LoadSubCommand (const char *cmd_name, - const lldb::CommandObjectSP& command_sp) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->LoadSubCommand (cmd_name, command_sp); - return false; +bool CommandObjectProxy::LoadSubCommand( + const char *cmd_name, const lldb::CommandObjectSP &command_sp) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->LoadSubCommand(cmd_name, command_sp); + return false; } -bool -CommandObjectProxy::WantsRawCommandString() -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->WantsRawCommandString(); - return false; +bool CommandObjectProxy::WantsRawCommandString() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->WantsRawCommandString(); + return false; } -bool -CommandObjectProxy::WantsCompletion() -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->WantsCompletion(); - return false; +bool CommandObjectProxy::WantsCompletion() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->WantsCompletion(); + return false; } -Options * -CommandObjectProxy::GetOptions () -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetOptions (); - return nullptr; +Options *CommandObjectProxy::GetOptions() { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetOptions(); + return nullptr; } -int -CommandObjectProxy::HandleCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->HandleCompletion (input, - cursor_index, - cursor_char_position, - match_start_point, - max_return_elements, - word_complete, - matches); - matches.Clear(); - return 0; +int CommandObjectProxy::HandleCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + int match_start_point, + int max_return_elements, + bool &word_complete, + StringList &matches) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->HandleCompletion( + input, cursor_index, cursor_char_position, match_start_point, + max_return_elements, word_complete, matches); + matches.Clear(); + return 0; } -int -CommandObjectProxy::HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->HandleArgumentCompletion (input, - cursor_index, - cursor_char_position, - opt_element_vector, - match_start_point, - max_return_elements, - word_complete, - matches); - matches.Clear(); - return 0; +int CommandObjectProxy::HandleArgumentCompletion( + Args &input, int &cursor_index, int &cursor_char_position, + OptionElementVector &opt_element_vector, int match_start_point, + int max_return_elements, bool &word_complete, StringList &matches) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->HandleArgumentCompletion( + input, cursor_index, cursor_char_position, opt_element_vector, + match_start_point, max_return_elements, word_complete, matches); + matches.Clear(); + return 0; } -const char * -CommandObjectProxy::GetRepeatCommand (Args ¤t_command_args, - uint32_t index) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->GetRepeatCommand (current_command_args, index); - return nullptr; +const char *CommandObjectProxy::GetRepeatCommand(Args ¤t_command_args, + uint32_t index) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->GetRepeatCommand(current_command_args, index); + return nullptr; } -bool -CommandObjectProxy::Execute (const char *args_string, - CommandReturnObject &result) -{ - CommandObject *proxy_command = GetProxyCommandObject(); - if (proxy_command) - return proxy_command->Execute (args_string, result); - result.AppendError ("command is not implemented"); - result.SetStatus (eReturnStatusFailed); - return false; +bool CommandObjectProxy::Execute(const char *args_string, + CommandReturnObject &result) { + CommandObject *proxy_command = GetProxyCommandObject(); + if (proxy_command) + return proxy_command->Execute(args_string, result); + result.AppendError("command is not implemented"); + result.SetStatus(eReturnStatusFailed); + return false; } diff --git a/lldb/source/Commands/CommandObjectPlatform.cpp b/lldb/source/Commands/CommandObjectPlatform.cpp index 8cb7c7a2178..1a981ce49ea 100644 --- a/lldb/source/Commands/CommandObjectPlatform.cpp +++ b/lldb/source/Commands/CommandObjectPlatform.cpp @@ -32,39 +32,34 @@ using namespace lldb; using namespace lldb_private; -static mode_t -ParsePermissionString(const char* permissions) -{ - if (strlen(permissions) != 9) - return (mode_t)(-1); - bool user_r,user_w,user_x, - group_r,group_w,group_x, - world_r,world_w,world_x; - - user_r = (permissions[0] == 'r'); - user_w = (permissions[1] == 'w'); - user_x = (permissions[2] == 'x'); - - group_r = (permissions[3] == 'r'); - group_w = (permissions[4] == 'w'); - group_x = (permissions[5] == 'x'); - - world_r = (permissions[6] == 'r'); - world_w = (permissions[7] == 'w'); - world_x = (permissions[8] == 'x'); - - mode_t user,group,world; - user = (user_r ? 4 : 0) | (user_w ? 2 : 0) | (user_x ? 1 : 0); - group = (group_r ? 4 : 0) | (group_w ? 2 : 0) | (group_x ? 1 : 0); - world = (world_r ? 4 : 0) | (world_w ? 2 : 0) | (world_x ? 1 : 0); - - return user | group | world; +static mode_t ParsePermissionString(const char *permissions) { + if (strlen(permissions) != 9) + return (mode_t)(-1); + bool user_r, user_w, user_x, group_r, group_w, group_x, world_r, world_w, + world_x; + + user_r = (permissions[0] == 'r'); + user_w = (permissions[1] == 'w'); + user_x = (permissions[2] == 'x'); + + group_r = (permissions[3] == 'r'); + group_w = (permissions[4] == 'w'); + group_x = (permissions[5] == 'x'); + + world_r = (permissions[6] == 'r'); + world_w = (permissions[7] == 'w'); + world_x = (permissions[8] == 'x'); + + mode_t user, group, world; + user = (user_r ? 4 : 0) | (user_w ? 2 : 0) | (user_x ? 1 : 0); + group = (group_r ? 4 : 0) | (group_w ? 2 : 0) | (group_x ? 1 : 0); + world = (world_r ? 4 : 0) | (world_w ? 2 : 0) | (world_x ? 1 : 0); + + return user | group | world; } -static OptionDefinition -g_permissions_options[] = -{ - // clang-format off +static OptionDefinition g_permissions_options[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "permissions-value", 'v', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePermissionsNumber, "Give out the numeric value for permissions (e.g. 757)"}, {LLDB_OPT_SET_ALL, false, "permissions-string", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePermissionsString, "Give out the string value for permissions (e.g. rwxr-xr--)."}, {LLDB_OPT_SET_ALL, false, "user-read", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to read."}, @@ -76,1549 +71,1334 @@ g_permissions_options[] = {LLDB_OPT_SET_ALL, false, "world-read", 'd', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to read."}, {LLDB_OPT_SET_ALL, false, "world-write", 't', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to write."}, {LLDB_OPT_SET_ALL, false, "world-exec", 'e', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to execute."}, - // clang-format on + // clang-format on }; -class OptionPermissions : public lldb_private::OptionGroup -{ +class OptionPermissions : public lldb_private::OptionGroup { public: - OptionPermissions () - { + OptionPermissions() {} + + ~OptionPermissions() override = default; + + lldb_private::Error + SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + char short_option = (char)GetDefinitions()[option_idx].short_option; + switch (short_option) { + case 'v': { + bool ok; + uint32_t perms = StringConvert::ToUInt32(option_arg, 777, 8, &ok); + if (!ok) + error.SetErrorStringWithFormat("invalid value for permissions: %s", + option_arg); + else + m_permissions = perms; + } break; + case 's': { + mode_t perms = ParsePermissionString(option_arg); + if (perms == (mode_t)-1) + error.SetErrorStringWithFormat("invalid value for permissions: %s", + option_arg); + else + m_permissions = perms; + } break; + case 'r': + m_permissions |= lldb::eFilePermissionsUserRead; + break; + case 'w': + m_permissions |= lldb::eFilePermissionsUserWrite; + break; + case 'x': + m_permissions |= lldb::eFilePermissionsUserExecute; + break; + case 'R': + m_permissions |= lldb::eFilePermissionsGroupRead; + break; + case 'W': + m_permissions |= lldb::eFilePermissionsGroupWrite; + break; + case 'X': + m_permissions |= lldb::eFilePermissionsGroupExecute; + break; + case 'd': + m_permissions |= lldb::eFilePermissionsWorldRead; + break; + case 't': + m_permissions |= lldb::eFilePermissionsWorldWrite; + break; + case 'e': + m_permissions |= lldb::eFilePermissionsWorldExecute; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); + break; } - ~OptionPermissions() override = default; + return error; + } - lldb_private::Error - SetOptionValue(uint32_t option_idx, - const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - char short_option = (char) GetDefinitions()[option_idx].short_option; - switch (short_option) - { - case 'v': - { - bool ok; - uint32_t perms = StringConvert::ToUInt32(option_arg, 777, 8, &ok); - if (!ok) - error.SetErrorStringWithFormat("invalid value for permissions: %s", option_arg); - else - m_permissions = perms; - } - break; - case 's': - { - mode_t perms = ParsePermissionString(option_arg); - if (perms == (mode_t)-1) - error.SetErrorStringWithFormat("invalid value for permissions: %s", option_arg); - else - m_permissions = perms; - } - break; - case 'r': - m_permissions |= lldb::eFilePermissionsUserRead; - break; - case 'w': - m_permissions |= lldb::eFilePermissionsUserWrite; - break; - case 'x': - m_permissions |= lldb::eFilePermissionsUserExecute; - break; - case 'R': - m_permissions |= lldb::eFilePermissionsGroupRead; - break; - case 'W': - m_permissions |= lldb::eFilePermissionsGroupWrite; - break; - case 'X': - m_permissions |= lldb::eFilePermissionsGroupExecute; - break; - case 'd': - m_permissions |= lldb::eFilePermissionsWorldRead; - break; - case 't': - m_permissions |= lldb::eFilePermissionsWorldWrite; - break; - case 'e': - m_permissions |= lldb::eFilePermissionsWorldExecute; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_permissions = 0; - } - - uint32_t - GetNumDefinitions () override - { - return llvm::array_lengthof(g_permissions_options); - } - - const lldb_private::OptionDefinition* - GetDefinitions () override - { - return g_permissions_options; - } - - // Instance variables to hold the values for command options. - - uint32_t m_permissions; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_permissions = 0; + } + + uint32_t GetNumDefinitions() override { + return llvm::array_lengthof(g_permissions_options); + } + + const lldb_private::OptionDefinition *GetDefinitions() override { + return g_permissions_options; + } + + // Instance variables to hold the values for command options. + + uint32_t m_permissions; private: - DISALLOW_COPY_AND_ASSIGN(OptionPermissions); + DISALLOW_COPY_AND_ASSIGN(OptionPermissions); }; //---------------------------------------------------------------------- // "platform select " //---------------------------------------------------------------------- -class CommandObjectPlatformSelect : public CommandObjectParsed -{ +class CommandObjectPlatformSelect : public CommandObjectParsed { public: - CommandObjectPlatformSelect (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform select", - "Create a platform if needed and select it as the current platform.", - "platform select ", - 0), - m_option_group (), - m_platform_options (false) // Don't include the "--platform" option by passing false - { - m_option_group.Append (&m_platform_options, LLDB_OPT_SET_ALL, 1); - m_option_group.Finalize(); - } - - ~CommandObjectPlatformSelect() override = default; - - int - HandleCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::PlatformPluginNames(GetCommandInterpreter(), - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } - - Options * - GetOptions () override - { - return &m_option_group; - } + CommandObjectPlatformSelect(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform select", + "Create a platform if needed and select it as the " + "current platform.", + "platform select ", 0), + m_option_group(), + m_platform_options( + false) // Don't include the "--platform" option by passing false + { + m_option_group.Append(&m_platform_options, LLDB_OPT_SET_ALL, 1); + m_option_group.Finalize(); + } + + ~CommandObjectPlatformSelect() override = default; + + int HandleCompletion(Args &input, int &cursor_index, + int &cursor_char_position, int match_start_point, + int max_return_elements, bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::PlatformPluginNames( + GetCommandInterpreter(), completion_str.c_str(), match_start_point, + max_return_elements, nullptr, word_complete, matches); + return matches.GetSize(); + } + + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - if (args.GetArgumentCount() == 1) - { - const char *platform_name = args.GetArgumentAtIndex (0); - if (platform_name && platform_name[0]) - { - const bool select = true; - m_platform_options.SetPlatformName (platform_name); - Error error; - ArchSpec platform_arch; - PlatformSP platform_sp (m_platform_options.CreatePlatformWithOptions (m_interpreter, ArchSpec(), select, error, platform_arch)); - if (platform_sp) - { - m_interpreter.GetDebugger().GetPlatformList().SetSelectedPlatform(platform_sp); - - platform_sp->GetStatus (result.GetOutputStream()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("invalid platform name"); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("platform create takes a platform name as an argument\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + if (args.GetArgumentCount() == 1) { + const char *platform_name = args.GetArgumentAtIndex(0); + if (platform_name && platform_name[0]) { + const bool select = true; + m_platform_options.SetPlatformName(platform_name); + Error error; + ArchSpec platform_arch; + PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions( + m_interpreter, ArchSpec(), select, error, platform_arch)); + if (platform_sp) { + m_interpreter.GetDebugger().GetPlatformList().SetSelectedPlatform( + platform_sp); + + platform_sp->GetStatus(result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("invalid platform name"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError( + "platform create takes a platform name as an argument\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - OptionGroupOptions m_option_group; - OptionGroupPlatform m_platform_options; + OptionGroupOptions m_option_group; + OptionGroupPlatform m_platform_options; }; //---------------------------------------------------------------------- // "platform list" //---------------------------------------------------------------------- -class CommandObjectPlatformList : public CommandObjectParsed -{ +class CommandObjectPlatformList : public CommandObjectParsed { public: - CommandObjectPlatformList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform list", - "List all platforms that are available.", - nullptr, - 0) - { - } + CommandObjectPlatformList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform list", + "List all platforms that are available.", nullptr, + 0) {} - ~CommandObjectPlatformList() override = default; + ~CommandObjectPlatformList() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Stream &ostrm = result.GetOutputStream(); - ostrm.Printf("Available platforms:\n"); - - PlatformSP host_platform_sp (Platform::GetHostPlatform()); - ostrm.Printf ("%s: %s\n", - host_platform_sp->GetPluginName().GetCString(), - host_platform_sp->GetDescription()); - - uint32_t idx; - for (idx = 0; 1; ++idx) - { - const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (idx); - if (plugin_name == nullptr) - break; - const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (idx); - if (plugin_desc == nullptr) - break; - ostrm.Printf("%s: %s\n", plugin_name, plugin_desc); - } - - if (idx == 0) - { - result.AppendError ("no platforms are available\n"); - result.SetStatus (eReturnStatusFailed); - } - else - result.SetStatus (eReturnStatusSuccessFinishResult); - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + Stream &ostrm = result.GetOutputStream(); + ostrm.Printf("Available platforms:\n"); + + PlatformSP host_platform_sp(Platform::GetHostPlatform()); + ostrm.Printf("%s: %s\n", host_platform_sp->GetPluginName().GetCString(), + host_platform_sp->GetDescription()); + + uint32_t idx; + for (idx = 0; 1; ++idx) { + const char *plugin_name = + PluginManager::GetPlatformPluginNameAtIndex(idx); + if (plugin_name == nullptr) + break; + const char *plugin_desc = + PluginManager::GetPlatformPluginDescriptionAtIndex(idx); + if (plugin_desc == nullptr) + break; + ostrm.Printf("%s: %s\n", plugin_name, plugin_desc); } + + if (idx == 0) { + result.AppendError("no platforms are available\n"); + result.SetStatus(eReturnStatusFailed); + } else + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform status" //---------------------------------------------------------------------- -class CommandObjectPlatformStatus : public CommandObjectParsed -{ +class CommandObjectPlatformStatus : public CommandObjectParsed { public: - CommandObjectPlatformStatus(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "platform status", "Display status for the current platform.", nullptr, 0) - { - } + CommandObjectPlatformStatus(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform status", + "Display status for the current platform.", nullptr, + 0) {} - ~CommandObjectPlatformStatus() override = default; + ~CommandObjectPlatformStatus() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Stream &ostrm = result.GetOutputStream(); - - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - PlatformSP platform_sp; - if (target) - { - platform_sp = target->GetPlatform(); - } - if (!platform_sp) - { - platform_sp = m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); - } - if (platform_sp) - { - platform_sp->GetStatus (ostrm); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("no platform us currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + Stream &ostrm = result.GetOutputStream(); + + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + PlatformSP platform_sp; + if (target) { + platform_sp = target->GetPlatform(); } + if (!platform_sp) { + platform_sp = + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + } + if (platform_sp) { + platform_sp->GetStatus(ostrm); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("no platform us currently selected\n"); + result.SetStatus(eReturnStatusFailed); + } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform connect " //---------------------------------------------------------------------- -class CommandObjectPlatformConnect : public CommandObjectParsed -{ +class CommandObjectPlatformConnect : public CommandObjectParsed { public: - CommandObjectPlatformConnect(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "platform connect", - "Select the current platform by providing a connection URL.", - "platform connect ", 0) - { - } + CommandObjectPlatformConnect(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "platform connect", + "Select the current platform by providing a connection URL.", + "platform connect ", 0) {} - ~CommandObjectPlatformConnect() override = default; + ~CommandObjectPlatformConnect() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Stream &ostrm = result.GetOutputStream(); - - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - Error error (platform_sp->ConnectRemote (args)); - if (error.Success()) - { - platform_sp->GetStatus (ostrm); - result.SetStatus (eReturnStatusSuccessFinishResult); - - platform_sp->ConnectToWaitingProcesses(m_interpreter.GetDebugger(), error); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("%s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform is currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + Stream &ostrm = result.GetOutputStream(); + + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + Error error(platform_sp->ConnectRemote(args)); + if (error.Success()) { + platform_sp->GetStatus(ostrm); + result.SetStatus(eReturnStatusSuccessFinishResult); + + platform_sp->ConnectToWaitingProcesses(m_interpreter.GetDebugger(), + error); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("%s\n", error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform is currently selected\n"); + result.SetStatus(eReturnStatusFailed); } - - Options * - GetOptions () override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - OptionGroupOptions* m_platform_options = nullptr; - if (platform_sp) - { - m_platform_options = platform_sp->GetConnectionOptions(m_interpreter); - if (m_platform_options != nullptr && !m_platform_options->m_did_finalize) - m_platform_options->Finalize(); - } - return m_platform_options; + return result.Succeeded(); + } + + Options *GetOptions() override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + OptionGroupOptions *m_platform_options = nullptr; + if (platform_sp) { + m_platform_options = platform_sp->GetConnectionOptions(m_interpreter); + if (m_platform_options != nullptr && !m_platform_options->m_did_finalize) + m_platform_options->Finalize(); } + return m_platform_options; + } }; //---------------------------------------------------------------------- // "platform disconnect" //---------------------------------------------------------------------- -class CommandObjectPlatformDisconnect : public CommandObjectParsed -{ +class CommandObjectPlatformDisconnect : public CommandObjectParsed { public: - CommandObjectPlatformDisconnect(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "platform disconnect", "Disconnect from the current platform.", - "platform disconnect", 0) - { - } + CommandObjectPlatformDisconnect(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform disconnect", + "Disconnect from the current platform.", + "platform disconnect", 0) {} - ~CommandObjectPlatformDisconnect() override = default; + ~CommandObjectPlatformDisconnect() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - if (args.GetArgumentCount() == 0) - { - Error error; - - if (platform_sp->IsConnected()) - { - // Cache the instance name if there is one since we are - // about to disconnect and the name might go with it. - const char *hostname_cstr = platform_sp->GetHostname(); - std::string hostname; - if (hostname_cstr) - hostname.assign (hostname_cstr); - - error = platform_sp->DisconnectRemote (); - if (error.Success()) - { - Stream &ostrm = result.GetOutputStream(); - if (hostname.empty()) - ostrm.Printf ("Disconnected from \"%s\"\n", platform_sp->GetPluginName().GetCString()); - else - ostrm.Printf ("Disconnected from \"%s\"\n", hostname.c_str()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("%s", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - // Not connected... - result.AppendErrorWithFormat ("not connected to '%s'", platform_sp->GetPluginName().GetCString()); - result.SetStatus (eReturnStatusFailed); - } - } + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + if (args.GetArgumentCount() == 0) { + Error error; + + if (platform_sp->IsConnected()) { + // Cache the instance name if there is one since we are + // about to disconnect and the name might go with it. + const char *hostname_cstr = platform_sp->GetHostname(); + std::string hostname; + if (hostname_cstr) + hostname.assign(hostname_cstr); + + error = platform_sp->DisconnectRemote(); + if (error.Success()) { + Stream &ostrm = result.GetOutputStream(); + if (hostname.empty()) + ostrm.Printf("Disconnected from \"%s\"\n", + platform_sp->GetPluginName().GetCString()); else - { - // Bad args - result.AppendError ("\"platform disconnect\" doesn't take any arguments"); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform is currently selected"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + ostrm.Printf("Disconnected from \"%s\"\n", hostname.c_str()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("%s", error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + // Not connected... + result.AppendErrorWithFormat( + "not connected to '%s'", + platform_sp->GetPluginName().GetCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + // Bad args + result.AppendError( + "\"platform disconnect\" doesn't take any arguments"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform is currently selected"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform settings" //---------------------------------------------------------------------- -class CommandObjectPlatformSettings : public CommandObjectParsed -{ +class CommandObjectPlatformSettings : public CommandObjectParsed { public: - CommandObjectPlatformSettings (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform settings", - "Set settings for the current target's platform, or for a platform by name.", - "platform settings", - 0), + CommandObjectPlatformSettings(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform settings", + "Set settings for the current target's platform, " + "or for a platform by name.", + "platform settings", 0), m_options(), - m_option_working_dir (LLDB_OPT_SET_1, false, "working-dir", 'w', 0, eArgTypePath, "The working directory for the platform.") - { - m_options.Append (&m_option_working_dir, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - } + m_option_working_dir(LLDB_OPT_SET_1, false, "working-dir", 'w', 0, + eArgTypePath, + "The working directory for the platform.") { + m_options.Append(&m_option_working_dir, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + } - ~CommandObjectPlatformSettings() override = default; + ~CommandObjectPlatformSettings() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - if (m_option_working_dir.GetOptionValue().OptionWasSet()) - platform_sp->SetWorkingDirectory(m_option_working_dir.GetOptionValue().GetCurrentValue()); - } - else - { - result.AppendError ("no platform is currently selected"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); - } - - Options * - GetOptions () override - { - if (!m_options.DidFinalize()) - m_options.Finalize(); - return &m_options; + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + if (m_option_working_dir.GetOptionValue().OptionWasSet()) + platform_sp->SetWorkingDirectory( + m_option_working_dir.GetOptionValue().GetCurrentValue()); + } else { + result.AppendError("no platform is currently selected"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + + Options *GetOptions() override { + if (!m_options.DidFinalize()) + m_options.Finalize(); + return &m_options; + } protected: - OptionGroupOptions m_options; - OptionGroupFile m_option_working_dir; + OptionGroupOptions m_options; + OptionGroupFile m_option_working_dir; }; //---------------------------------------------------------------------- // "platform mkdir" //---------------------------------------------------------------------- -class CommandObjectPlatformMkDir : public CommandObjectParsed -{ +class CommandObjectPlatformMkDir : public CommandObjectParsed { public: - CommandObjectPlatformMkDir (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform mkdir", - "Make a new directory on the remote end.", - nullptr, + CommandObjectPlatformMkDir(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform mkdir", + "Make a new directory on the remote end.", nullptr, 0), - m_options() - { + m_options() {} + + ~CommandObjectPlatformMkDir() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + std::string cmd_line; + args.GetCommandString(cmd_line); + uint32_t mode; + const OptionPermissions *options_permissions = + (const OptionPermissions *)m_options.GetGroupWithOption('r'); + if (options_permissions) + mode = options_permissions->m_permissions; + else + mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX | + lldb::eFilePermissionsWorldRX; + Error error = platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - ~CommandObjectPlatformMkDir() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - std::string cmd_line; - args.GetCommandString(cmd_line); - uint32_t mode; - const OptionPermissions* options_permissions = (const OptionPermissions*)m_options.GetGroupWithOption('r'); - if (options_permissions) - mode = options_permissions->m_permissions; - else - mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX | lldb::eFilePermissionsWorldRX; - Error error = platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); - } - - Options * - GetOptions () override - { - if (!m_options.DidFinalize()) - { - m_options.Append(new OptionPermissions()); - m_options.Finalize(); - } - return &m_options; + Options *GetOptions() override { + if (!m_options.DidFinalize()) { + m_options.Append(new OptionPermissions()); + m_options.Finalize(); } + return &m_options; + } - OptionGroupOptions m_options; + OptionGroupOptions m_options; }; //---------------------------------------------------------------------- // "platform fopen" //---------------------------------------------------------------------- -class CommandObjectPlatformFOpen : public CommandObjectParsed -{ +class CommandObjectPlatformFOpen : public CommandObjectParsed { public: - CommandObjectPlatformFOpen (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform file open", - "Open a file on the remote end.", - nullptr, - 0), - m_options() - { - } - - ~CommandObjectPlatformFOpen() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - Error error; - std::string cmd_line; - args.GetCommandString(cmd_line); - mode_t perms; - const OptionPermissions* options_permissions = (const OptionPermissions*)m_options.GetGroupWithOption('r'); - if (options_permissions) - perms = options_permissions->m_permissions; - else - perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW | lldb::eFilePermissionsWorldRead; - lldb::user_id_t fd = platform_sp->OpenFile(FileSpec(cmd_line.c_str(),false), - File::eOpenOptionRead | File::eOpenOptionWrite | - File::eOpenOptionAppend | File::eOpenOptionCanCreate, - perms, - error); - if (error.Success()) - { - result.AppendMessageWithFormat("File Descriptor = %" PRIu64 "\n",fd); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + CommandObjectPlatformFOpen(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform file open", + "Open a file on the remote end.", nullptr, 0), + m_options() {} + + ~CommandObjectPlatformFOpen() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + Error error; + std::string cmd_line; + args.GetCommandString(cmd_line); + mode_t perms; + const OptionPermissions *options_permissions = + (const OptionPermissions *)m_options.GetGroupWithOption('r'); + if (options_permissions) + perms = options_permissions->m_permissions; + else + perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW | + lldb::eFilePermissionsWorldRead; + lldb::user_id_t fd = platform_sp->OpenFile( + FileSpec(cmd_line.c_str(), false), + File::eOpenOptionRead | File::eOpenOptionWrite | + File::eOpenOptionAppend | File::eOpenOptionCanCreate, + perms, error); + if (error.Success()) { + result.AppendMessageWithFormat("File Descriptor = %" PRIu64 "\n", fd); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - Options * - GetOptions () override - { - if (!m_options.DidFinalize()) - { - m_options.Append(new OptionPermissions()); - m_options.Finalize(); - } - return &m_options; + Options *GetOptions() override { + if (!m_options.DidFinalize()) { + m_options.Append(new OptionPermissions()); + m_options.Finalize(); } + return &m_options; + } - OptionGroupOptions m_options; + OptionGroupOptions m_options; }; //---------------------------------------------------------------------- // "platform fclose" //---------------------------------------------------------------------- -class CommandObjectPlatformFClose : public CommandObjectParsed -{ +class CommandObjectPlatformFClose : public CommandObjectParsed { public: - CommandObjectPlatformFClose (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform file close", - "Close a file on the remote end.", - nullptr, - 0) - { - } - - ~CommandObjectPlatformFClose() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - std::string cmd_line; - args.GetCommandString(cmd_line); - const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); - Error error; - bool success = platform_sp->CloseFile(fd, error); - if (success) - { - result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + CommandObjectPlatformFClose(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform file close", + "Close a file on the remote end.", nullptr, 0) {} + + ~CommandObjectPlatformFClose() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + std::string cmd_line; + args.GetCommandString(cmd_line); + const lldb::user_id_t fd = + StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); + Error error; + bool success = platform_sp->CloseFile(fd, error); + if (success) { + result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform fread" //---------------------------------------------------------------------- -class CommandObjectPlatformFRead : public CommandObjectParsed -{ +class CommandObjectPlatformFRead : public CommandObjectParsed { public: - CommandObjectPlatformFRead (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform file read", - "Read data from a file on the remote end.", - nullptr, + CommandObjectPlatformFRead(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform file read", + "Read data from a file on the remote end.", nullptr, 0), - m_options() - { + m_options() {} + + ~CommandObjectPlatformFRead() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + std::string cmd_line; + args.GetCommandString(cmd_line); + const lldb::user_id_t fd = + StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); + std::string buffer(m_options.m_count, 0); + Error error; + uint32_t retcode = platform_sp->ReadFile( + fd, m_options.m_offset, &buffer[0], m_options.m_count, error); + result.AppendMessageWithFormat("Return = %d\n", retcode); + result.AppendMessageWithFormat("Data = \"%s\"\n", buffer.c_str()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - ~CommandObjectPlatformFRead() override = default; + Options *GetOptions() override { return &m_options; } - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - std::string cmd_line; - args.GetCommandString(cmd_line); - const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); - std::string buffer(m_options.m_count,0); - Error error; - uint32_t retcode = platform_sp->ReadFile(fd, m_options.m_offset, &buffer[0], m_options.m_count, error); - result.AppendMessageWithFormat("Return = %d\n",retcode); - result.AppendMessageWithFormat("Data = \"%s\"\n",buffer.c_str()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); +protected: + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + char short_option = (char)m_getopt_table[option_idx].val; + bool success = false; + + switch (short_option) { + case 'o': + m_offset = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); + break; + case 'c': + m_count = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_offset = 0; + m_count = 1; } - -protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - char short_option = (char) m_getopt_table[option_idx].val; - bool success = false; - - switch (short_option) - { - case 'o': - m_offset = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); - break; - case 'c': - m_count = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_offset = 0; - m_count = 1; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - uint32_t m_offset; - uint32_t m_count; - }; - - CommandOptions m_options; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + uint32_t m_offset; + uint32_t m_count; + }; + + CommandOptions m_options; }; -OptionDefinition -CommandObjectPlatformFRead::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectPlatformFRead::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading."}, {LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Number of bytes to read from the file."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // "platform fwrite" //---------------------------------------------------------------------- -class CommandObjectPlatformFWrite : public CommandObjectParsed -{ +class CommandObjectPlatformFWrite : public CommandObjectParsed { public: - CommandObjectPlatformFWrite (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform file write", - "Write data to a file on the remote end.", - nullptr, + CommandObjectPlatformFWrite(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform file write", + "Write data to a file on the remote end.", nullptr, 0), - m_options() - { + m_options() {} + + ~CommandObjectPlatformFWrite() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + std::string cmd_line; + args.GetCommandString(cmd_line); + Error error; + const lldb::user_id_t fd = + StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); + uint32_t retcode = + platform_sp->WriteFile(fd, m_options.m_offset, &m_options.m_data[0], + m_options.m_data.size(), error); + result.AppendMessageWithFormat("Return = %d\n", retcode); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - ~CommandObjectPlatformFWrite() override = default; + Options *GetOptions() override { return &m_options; } - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - std::string cmd_line; - args.GetCommandString(cmd_line); - Error error; - const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); - uint32_t retcode = platform_sp->WriteFile (fd, - m_options.m_offset, - &m_options.m_data[0], - m_options.m_data.size(), - error); - result.AppendMessageWithFormat("Return = %d\n",retcode); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); +protected: + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + char short_option = (char)m_getopt_table[option_idx].val; + bool success = false; + + switch (short_option) { + case 'o': + m_offset = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); + break; + case 'd': + m_data.assign(option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_offset = 0; + m_data.clear(); } - -protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - char short_option = (char) m_getopt_table[option_idx].val; - bool success = false; - - switch (short_option) - { - case 'o': - m_offset = StringConvert::ToUInt32(option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid offset: '%s'", option_arg); - break; - case 'd': - m_data.assign(option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_offset = 0; - m_data.clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - uint32_t m_offset; - std::string m_data; - }; - - CommandOptions m_options; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + uint32_t m_offset; + std::string m_data; + }; + + CommandOptions m_options; }; -OptionDefinition -CommandObjectPlatformFWrite::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectPlatformFWrite::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading."}, {LLDB_OPT_SET_1, false, "data", 'd', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue, "Text to write to the file."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectPlatformFile : public CommandObjectMultiword -{ +class CommandObjectPlatformFile : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectPlatformFile(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "platform file", "Commands to access files on the current platform.", - "platform file [open|close|read|write] ...") - { - LoadSubCommand ("open", CommandObjectSP (new CommandObjectPlatformFOpen (interpreter))); - LoadSubCommand ("close", CommandObjectSP (new CommandObjectPlatformFClose (interpreter))); - LoadSubCommand ("read", CommandObjectSP (new CommandObjectPlatformFRead (interpreter))); - LoadSubCommand ("write", CommandObjectSP (new CommandObjectPlatformFWrite (interpreter))); - } - - ~CommandObjectPlatformFile() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectPlatformFile(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "platform file", + "Commands to access files on the current platform.", + "platform file [open|close|read|write] ...") { + LoadSubCommand( + "open", CommandObjectSP(new CommandObjectPlatformFOpen(interpreter))); + LoadSubCommand( + "close", CommandObjectSP(new CommandObjectPlatformFClose(interpreter))); + LoadSubCommand( + "read", CommandObjectSP(new CommandObjectPlatformFRead(interpreter))); + LoadSubCommand( + "write", CommandObjectSP(new CommandObjectPlatformFWrite(interpreter))); + } + + ~CommandObjectPlatformFile() override = default; private: - //------------------------------------------------------------------ - // For CommandObjectPlatform only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectPlatformFile); + //------------------------------------------------------------------ + // For CommandObjectPlatform only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformFile); }; //---------------------------------------------------------------------- // "platform get-file remote-file-path host-file-path" //---------------------------------------------------------------------- -class CommandObjectPlatformGetFile : public CommandObjectParsed -{ +class CommandObjectPlatformGetFile : public CommandObjectParsed { public: - CommandObjectPlatformGetFile (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform get-file", - "Transfer a file from the remote end to the local host.", - "platform get-file ", - 0) - { - SetHelpLong( -R"(Examples: + CommandObjectPlatformGetFile(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "platform get-file", + "Transfer a file from the remote end to the local host.", + "platform get-file ", 0) { + SetHelpLong( + R"(Examples: (lldb) platform get-file /the/remote/file/path /the/local/file/path - Transfer a file from the remote end with file path /the/remote/file/path to the local host.)" - ); - - CommandArgumentEntry arg1, arg2; - CommandArgumentData file_arg_remote, file_arg_host; - - // Define the first (and only) variant of this arg. - file_arg_remote.arg_type = eArgTypeFilename; - file_arg_remote.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (file_arg_remote); - - // Define the second (and only) variant of this arg. - file_arg_host.arg_type = eArgTypeFilename; - file_arg_host.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (file_arg_host); - - // Push the data for the first and the second arguments into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); + Transfer a file from the remote end with file path /the/remote/file/path to the local host.)"); + + CommandArgumentEntry arg1, arg2; + CommandArgumentData file_arg_remote, file_arg_host; + + // Define the first (and only) variant of this arg. + file_arg_remote.arg_type = eArgTypeFilename; + file_arg_remote.arg_repetition = eArgRepeatPlain; + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(file_arg_remote); + + // Define the second (and only) variant of this arg. + file_arg_host.arg_type = eArgTypeFilename; + file_arg_host.arg_repetition = eArgRepeatPlain; + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(file_arg_host); + + // Push the data for the first and the second arguments into the m_arguments + // vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectPlatformGetFile() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + // If the number of arguments is incorrect, issue an error message. + if (args.GetArgumentCount() != 2) { + result.GetErrorStream().Printf("error: required arguments missing; " + "specify both the source and destination " + "file paths\n"); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectPlatformGetFile() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - // If the number of arguments is incorrect, issue an error message. - if (args.GetArgumentCount() != 2) - { - result.GetErrorStream().Printf("error: required arguments missing; specify both the source and destination file paths\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - const char *remote_file_path = args.GetArgumentAtIndex(0); - const char *local_file_path = args.GetArgumentAtIndex(1); - Error error = platform_sp->GetFile(FileSpec(remote_file_path, false), - FileSpec(local_file_path, false)); - if (error.Success()) - { - result.AppendMessageWithFormat("successfully get-file from %s (remote) to %s (host)\n", - remote_file_path, local_file_path); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendMessageWithFormat("get-file failed: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + const char *remote_file_path = args.GetArgumentAtIndex(0); + const char *local_file_path = args.GetArgumentAtIndex(1); + Error error = platform_sp->GetFile(FileSpec(remote_file_path, false), + FileSpec(local_file_path, false)); + if (error.Success()) { + result.AppendMessageWithFormat( + "successfully get-file from %s (remote) to %s (host)\n", + remote_file_path, local_file_path); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendMessageWithFormat("get-file failed: %s\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform get-size remote-file-path" //---------------------------------------------------------------------- -class CommandObjectPlatformGetSize : public CommandObjectParsed -{ +class CommandObjectPlatformGetSize : public CommandObjectParsed { public: - CommandObjectPlatformGetSize (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform get-size", - "Get the file size from the remote end.", - "platform get-size ", - 0) - { - SetHelpLong( -R"(Examples: + CommandObjectPlatformGetSize(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform get-size", + "Get the file size from the remote end.", + "platform get-size ", 0) { + SetHelpLong( + R"(Examples: (lldb) platform get-size /the/remote/file/path - Get the file size from the remote end with path /the/remote/file/path.)" - ); - - CommandArgumentEntry arg1; - CommandArgumentData file_arg_remote; - - // Define the first (and only) variant of this arg. - file_arg_remote.arg_type = eArgTypeFilename; - file_arg_remote.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (file_arg_remote); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - } + Get the file size from the remote end with path /the/remote/file/path.)"); - ~CommandObjectPlatformGetSize() override = default; + CommandArgumentEntry arg1; + CommandArgumentData file_arg_remote; - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - // If the number of arguments is incorrect, issue an error message. - if (args.GetArgumentCount() != 1) - { - result.GetErrorStream().Printf("error: required argument missing; specify the source file path as the only argument\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } + // Define the first (and only) variant of this arg. + file_arg_remote.arg_type = eArgTypeFilename; + file_arg_remote.arg_repetition = eArgRepeatPlain; + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(file_arg_remote); - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - std::string remote_file_path(args.GetArgumentAtIndex(0)); - user_id_t size = platform_sp->GetFileSize(FileSpec(remote_file_path.c_str(), false)); - if (size != UINT64_MAX) - { - result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64 "\n", remote_file_path.c_str(), size); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendMessageWithFormat("Error getting file size of %s (remote)\n", remote_file_path.c_str()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectPlatformGetSize() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + // If the number of arguments is incorrect, issue an error message. + if (args.GetArgumentCount() != 1) { + result.GetErrorStream().Printf("error: required argument missing; " + "specify the source file path as the only " + "argument\n"); + result.SetStatus(eReturnStatusFailed); + return false; } + + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + std::string remote_file_path(args.GetArgumentAtIndex(0)); + user_id_t size = + platform_sp->GetFileSize(FileSpec(remote_file_path.c_str(), false)); + if (size != UINT64_MAX) { + result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64 + "\n", + remote_file_path.c_str(), size); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendMessageWithFormat( + "Error getting file size of %s (remote)\n", + remote_file_path.c_str()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); + } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform put-file" //---------------------------------------------------------------------- -class CommandObjectPlatformPutFile : public CommandObjectParsed -{ +class CommandObjectPlatformPutFile : public CommandObjectParsed { public: - CommandObjectPlatformPutFile (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "platform put-file", - "Transfer a file from this system to the remote end.", - nullptr, - 0) - { - } - - ~CommandObjectPlatformPutFile() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - const char* src = args.GetArgumentAtIndex(0); - const char* dst = args.GetArgumentAtIndex(1); - - FileSpec src_fs(src, true); - FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString(), false); - - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - Error error (platform_sp->PutFile(src_fs, dst_fs)); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("no platform currently selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + CommandObjectPlatformPutFile(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "platform put-file", + "Transfer a file from this system to the remote end.", nullptr, 0) { + } + + ~CommandObjectPlatformPutFile() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + const char *src = args.GetArgumentAtIndex(0); + const char *dst = args.GetArgumentAtIndex(1); + + FileSpec src_fs(src, true); + FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString(), false); + + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + Error error(platform_sp->PutFile(src_fs, dst_fs)); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform currently selected\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // "platform process launch" //---------------------------------------------------------------------- -class CommandObjectPlatformProcessLaunch : public CommandObjectParsed -{ +class CommandObjectPlatformProcessLaunch : public CommandObjectParsed { public: - CommandObjectPlatformProcessLaunch (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform process launch", - "Launch a new process on a remote platform.", - "platform process launch program", - eCommandRequiresTarget | eCommandTryTargetAPILock), - m_options() - { - } + CommandObjectPlatformProcessLaunch(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform process launch", + "Launch a new process on a remote platform.", + "platform process launch program", + eCommandRequiresTarget | eCommandTryTargetAPILock), + m_options() {} - ~CommandObjectPlatformProcessLaunch() override = default; + ~CommandObjectPlatformProcessLaunch() override = default; + + Options *GetOptions() override { return &m_options; } - Options * - GetOptions () override - { - return &m_options; - } - protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - PlatformSP platform_sp; - if (target) - { - platform_sp = target->GetPlatform(); - } - if (!platform_sp) - { - platform_sp = m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); - } - - if (platform_sp) - { - Error error; - const size_t argc = args.GetArgumentCount(); - Target *target = m_exe_ctx.GetTargetPtr(); - Module *exe_module = target->GetExecutableModulePointer(); - if (exe_module) - { - m_options.launch_info.GetExecutableFile () = exe_module->GetFileSpec(); - char exe_path[PATH_MAX]; - if (m_options.launch_info.GetExecutableFile ().GetPath (exe_path, sizeof(exe_path))) - m_options.launch_info.GetArguments().AppendArgument (exe_path); - m_options.launch_info.GetArchitecture() = exe_module->GetArchitecture(); - } + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + PlatformSP platform_sp; + if (target) { + platform_sp = target->GetPlatform(); + } + if (!platform_sp) { + platform_sp = + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + } - if (argc > 0) - { - if (m_options.launch_info.GetExecutableFile ()) - { - // We already have an executable file, so we will use this - // and all arguments to this function are extra arguments - m_options.launch_info.GetArguments().AppendArguments (args); - } - else - { - // We don't have any file yet, so the first argument is our - // executable, and the rest are program arguments - const bool first_arg_is_executable = true; - m_options.launch_info.SetArguments (args, first_arg_is_executable); - } - } - - if (m_options.launch_info.GetExecutableFile ()) - { - Debugger &debugger = m_interpreter.GetDebugger(); - - if (argc == 0) - target->GetRunArguments(m_options.launch_info.GetArguments()); - - ProcessSP process_sp (platform_sp->DebugProcess (m_options.launch_info, - debugger, - target, - error)); - if (process_sp && process_sp->IsAlive()) - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - return true; - } - - if (error.Success()) - result.AppendError ("process launch failed"); - else - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - else - { - result.AppendError ("'platform process launch' uses the current target file and arguments, or the executable and its arguments can be specified in this command"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (platform_sp) { + Error error; + const size_t argc = args.GetArgumentCount(); + Target *target = m_exe_ctx.GetTargetPtr(); + Module *exe_module = target->GetExecutableModulePointer(); + if (exe_module) { + m_options.launch_info.GetExecutableFile() = exe_module->GetFileSpec(); + char exe_path[PATH_MAX]; + if (m_options.launch_info.GetExecutableFile().GetPath(exe_path, + sizeof(exe_path))) + m_options.launch_info.GetArguments().AppendArgument(exe_path); + m_options.launch_info.GetArchitecture() = exe_module->GetArchitecture(); + } + + if (argc > 0) { + if (m_options.launch_info.GetExecutableFile()) { + // We already have an executable file, so we will use this + // and all arguments to this function are extra arguments + m_options.launch_info.GetArguments().AppendArguments(args); + } else { + // We don't have any file yet, so the first argument is our + // executable, and the rest are program arguments + const bool first_arg_is_executable = true; + m_options.launch_info.SetArguments(args, first_arg_is_executable); + } + } + + if (m_options.launch_info.GetExecutableFile()) { + Debugger &debugger = m_interpreter.GetDebugger(); + + if (argc == 0) + target->GetRunArguments(m_options.launch_info.GetArguments()); + + ProcessSP process_sp(platform_sp->DebugProcess( + m_options.launch_info, debugger, target, error)); + if (process_sp && process_sp->IsAlive()) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; } + + if (error.Success()) + result.AppendError("process launch failed"); else - { - result.AppendError ("no platform is selected\n"); - } - return result.Succeeded(); + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else { + result.AppendError("'platform process launch' uses the current target " + "file and arguments, or the executable and its " + "arguments can be specified in this command"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + result.AppendError("no platform is selected\n"); } - + return result.Succeeded(); + } + protected: - ProcessLaunchCommandOptions m_options; + ProcessLaunchCommandOptions m_options; }; //---------------------------------------------------------------------- // "platform process list" //---------------------------------------------------------------------- -class CommandObjectPlatformProcessList : public CommandObjectParsed -{ +class CommandObjectPlatformProcessList : public CommandObjectParsed { public: - CommandObjectPlatformProcessList (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform process list", - "List processes on a remote platform by name, pid, or many other matching attributes.", - "platform process list", - 0), - m_options() - { - } + CommandObjectPlatformProcessList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform process list", + "List processes on a remote platform by name, pid, " + "or many other matching attributes.", + "platform process list", 0), + m_options() {} - ~CommandObjectPlatformProcessList() override = default; + ~CommandObjectPlatformProcessList() override = default; + + Options *GetOptions() override { return &m_options; } - Options * - GetOptions () override - { - return &m_options; - } - protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - PlatformSP platform_sp; - if (target) - { - platform_sp = target->GetPlatform(); - } - if (!platform_sp) - { - platform_sp = m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); - } - - if (platform_sp) - { - Error error; - if (args.GetArgumentCount() == 0) - { - if (platform_sp) - { - Stream &ostrm = result.GetOutputStream(); - - lldb::pid_t pid = m_options.match_info.GetProcessInfo().GetProcessID(); - if (pid != LLDB_INVALID_PROCESS_ID) - { - ProcessInstanceInfo proc_info; - if (platform_sp->GetProcessInfo (pid, proc_info)) - { - ProcessInstanceInfo::DumpTableHeader (ostrm, platform_sp.get(), m_options.show_args, m_options.verbose); - proc_info.DumpAsTableRow(ostrm, platform_sp.get(), m_options.show_args, m_options.verbose); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("no process found with pid = %" PRIu64 "\n", pid); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - ProcessInstanceInfoList proc_infos; - const uint32_t matches = platform_sp->FindProcesses (m_options.match_info, proc_infos); - const char *match_desc = nullptr; - const char *match_name = m_options.match_info.GetProcessInfo().GetName(); - if (match_name && match_name[0]) - { - switch (m_options.match_info.GetNameMatchType()) - { - case eNameMatchIgnore: break; - case eNameMatchEquals: match_desc = "matched"; break; - case eNameMatchContains: match_desc = "contained"; break; - case eNameMatchStartsWith: match_desc = "started with"; break; - case eNameMatchEndsWith: match_desc = "ended with"; break; - case eNameMatchRegularExpression: match_desc = "matched the regular expression"; break; - } - } - - if (matches == 0) - { - if (match_desc) - result.AppendErrorWithFormat ("no processes were found that %s \"%s\" on the \"%s\" platform\n", - match_desc, - match_name, - platform_sp->GetPluginName().GetCString()); - else - result.AppendErrorWithFormat ("no processes were found on the \"%s\" platform\n", platform_sp->GetPluginName().GetCString()); - result.SetStatus (eReturnStatusFailed); - } - else - { - result.AppendMessageWithFormat ("%u matching process%s found on \"%s\"", - matches, - matches > 1 ? "es were" : " was", - platform_sp->GetName().GetCString()); - if (match_desc) - result.AppendMessageWithFormat (" whose name %s \"%s\"", - match_desc, - match_name); - result.AppendMessageWithFormat ("\n"); - ProcessInstanceInfo::DumpTableHeader (ostrm, platform_sp.get(), m_options.show_args, m_options.verbose); - for (uint32_t i=0; iGetPlatform(); + } + if (!platform_sp) { + platform_sp = + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + } + + if (platform_sp) { + Error error; + if (args.GetArgumentCount() == 0) { + if (platform_sp) { + Stream &ostrm = result.GetOutputStream(); + + lldb::pid_t pid = + m_options.match_info.GetProcessInfo().GetProcessID(); + if (pid != LLDB_INVALID_PROCESS_ID) { + ProcessInstanceInfo proc_info; + if (platform_sp->GetProcessInfo(pid, proc_info)) { + ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(), + m_options.show_args, + m_options.verbose); + proc_info.DumpAsTableRow(ostrm, platform_sp.get(), + m_options.show_args, m_options.verbose); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "no process found with pid = %" PRIu64 "\n", pid); + result.SetStatus(eReturnStatusFailed); } - else - { - result.AppendError ("invalid args: process list takes only options\n"); - result.SetStatus (eReturnStatusFailed); + } else { + ProcessInstanceInfoList proc_infos; + const uint32_t matches = + platform_sp->FindProcesses(m_options.match_info, proc_infos); + const char *match_desc = nullptr; + const char *match_name = + m_options.match_info.GetProcessInfo().GetName(); + if (match_name && match_name[0]) { + switch (m_options.match_info.GetNameMatchType()) { + case eNameMatchIgnore: + break; + case eNameMatchEquals: + match_desc = "matched"; + break; + case eNameMatchContains: + match_desc = "contained"; + break; + case eNameMatchStartsWith: + match_desc = "started with"; + break; + case eNameMatchEndsWith: + match_desc = "ended with"; + break; + case eNameMatchRegularExpression: + match_desc = "matched the regular expression"; + break; + } } - } - else - { - result.AppendError ("no platform is selected\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); - } - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - match_info(), - show_args(false), - verbose(false) - { - static std::once_flag g_once_flag; - std::call_once(g_once_flag, []() { - PosixPlatformCommandOptionValidator *posix_validator = new PosixPlatformCommandOptionValidator(); - for (size_t i=0; g_option_table[i].short_option != 0; ++i) - { - switch (g_option_table[i].short_option) - { - case 'u': - case 'U': - case 'g': - case 'G': - g_option_table[i].validator = posix_validator; - break; - default: - break; - } - } - }); - } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success = false; - - switch (short_option) - { - case 'p': - match_info.GetProcessInfo().SetProcessID (StringConvert::ToUInt32 (option_arg, LLDB_INVALID_PROCESS_ID, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid process ID string: '%s'", option_arg); - break; - - case 'P': - match_info.GetProcessInfo().SetParentProcessID (StringConvert::ToUInt32 (option_arg, LLDB_INVALID_PROCESS_ID, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid parent process ID string: '%s'", option_arg); - break; - - case 'u': - match_info.GetProcessInfo().SetUserID (StringConvert::ToUInt32 (option_arg, UINT32_MAX, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid user ID string: '%s'", option_arg); - break; - - case 'U': - match_info.GetProcessInfo().SetEffectiveUserID (StringConvert::ToUInt32 (option_arg, UINT32_MAX, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid effective user ID string: '%s'", option_arg); - break; - - case 'g': - match_info.GetProcessInfo().SetGroupID (StringConvert::ToUInt32 (option_arg, UINT32_MAX, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid group ID string: '%s'", option_arg); - break; - - case 'G': - match_info.GetProcessInfo().SetEffectiveGroupID (StringConvert::ToUInt32 (option_arg, UINT32_MAX, 0, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid effective group ID string: '%s'", option_arg); - break; - - case 'a': - { - TargetSP target_sp = execution_context ? - execution_context->GetTargetSP() : TargetSP(); - DebuggerSP debugger_sp = target_sp ? - target_sp->GetDebugger().shared_from_this() : - DebuggerSP(); - PlatformSP platform_sp = debugger_sp ? - debugger_sp->GetPlatformList().GetSelectedPlatform() : - PlatformSP(); - match_info.GetProcessInfo().GetArchitecture().SetTriple( - option_arg, platform_sp.get()); - } - break; - - case 'n': - match_info.GetProcessInfo().GetExecutableFile().SetFile (option_arg, false); - match_info.SetNameMatchType (eNameMatchEquals); - break; - - case 'e': - match_info.GetProcessInfo().GetExecutableFile().SetFile (option_arg, false); - match_info.SetNameMatchType (eNameMatchEndsWith); - break; - - case 's': - match_info.GetProcessInfo().GetExecutableFile().SetFile (option_arg, false); - match_info.SetNameMatchType (eNameMatchStartsWith); - break; - - case 'c': - match_info.GetProcessInfo().GetExecutableFile().SetFile (option_arg, false); - match_info.SetNameMatchType (eNameMatchContains); - break; - - case 'r': - match_info.GetProcessInfo().GetExecutableFile().SetFile (option_arg, false); - match_info.SetNameMatchType (eNameMatchRegularExpression); - break; - - case 'A': - show_args = true; - break; - - case 'v': - verbose = true; - break; - - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; + if (matches == 0) { + if (match_desc) + result.AppendErrorWithFormat( + "no processes were found that %s \"%s\" on the \"%s\" " + "platform\n", + match_desc, match_name, + platform_sp->GetPluginName().GetCString()); + else + result.AppendErrorWithFormat( + "no processes were found on the \"%s\" platform\n", + platform_sp->GetPluginName().GetCString()); + result.SetStatus(eReturnStatusFailed); + } else { + result.AppendMessageWithFormat( + "%u matching process%s found on \"%s\"", matches, + matches > 1 ? "es were" : " was", + platform_sp->GetName().GetCString()); + if (match_desc) + result.AppendMessageWithFormat(" whose name %s \"%s\"", + match_desc, match_name); + result.AppendMessageWithFormat("\n"); + ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(), + m_options.show_args, + m_options.verbose); + for (uint32_t i = 0; i < matches; ++i) { + proc_infos.GetProcessInfoAtIndex(i).DumpAsTableRow( + ostrm, platform_sp.get(), m_options.show_args, + m_options.verbose); + } } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - match_info.Clear(); - show_args = false; - verbose = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - ProcessInstanceInfoMatch match_info; - bool show_args; - bool verbose; - }; - - CommandOptions m_options; + } + } + } else { + result.AppendError("invalid args: process list takes only options\n"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform is selected\n"); + result.SetStatus(eReturnStatusFailed); + } + return result.Succeeded(); + } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), match_info(), show_args(false), verbose(false) { + static std::once_flag g_once_flag; + std::call_once(g_once_flag, []() { + PosixPlatformCommandOptionValidator *posix_validator = + new PosixPlatformCommandOptionValidator(); + for (size_t i = 0; g_option_table[i].short_option != 0; ++i) { + switch (g_option_table[i].short_option) { + case 'u': + case 'U': + case 'g': + case 'G': + g_option_table[i].validator = posix_validator; + break; + default: + break; + } + } + }); + } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success = false; + + switch (short_option) { + case 'p': + match_info.GetProcessInfo().SetProcessID(StringConvert::ToUInt32( + option_arg, LLDB_INVALID_PROCESS_ID, 0, &success)); + if (!success) + error.SetErrorStringWithFormat("invalid process ID string: '%s'", + option_arg); + break; + + case 'P': + match_info.GetProcessInfo().SetParentProcessID(StringConvert::ToUInt32( + option_arg, LLDB_INVALID_PROCESS_ID, 0, &success)); + if (!success) + error.SetErrorStringWithFormat( + "invalid parent process ID string: '%s'", option_arg); + break; + + case 'u': + match_info.GetProcessInfo().SetUserID( + StringConvert::ToUInt32(option_arg, UINT32_MAX, 0, &success)); + if (!success) + error.SetErrorStringWithFormat("invalid user ID string: '%s'", + option_arg); + break; + + case 'U': + match_info.GetProcessInfo().SetEffectiveUserID( + StringConvert::ToUInt32(option_arg, UINT32_MAX, 0, &success)); + if (!success) + error.SetErrorStringWithFormat( + "invalid effective user ID string: '%s'", option_arg); + break; + + case 'g': + match_info.GetProcessInfo().SetGroupID( + StringConvert::ToUInt32(option_arg, UINT32_MAX, 0, &success)); + if (!success) + error.SetErrorStringWithFormat("invalid group ID string: '%s'", + option_arg); + break; + + case 'G': + match_info.GetProcessInfo().SetEffectiveGroupID( + StringConvert::ToUInt32(option_arg, UINT32_MAX, 0, &success)); + if (!success) + error.SetErrorStringWithFormat( + "invalid effective group ID string: '%s'", option_arg); + break; + + case 'a': { + TargetSP target_sp = + execution_context ? execution_context->GetTargetSP() : TargetSP(); + DebuggerSP debugger_sp = + target_sp ? target_sp->GetDebugger().shared_from_this() + : DebuggerSP(); + PlatformSP platform_sp = + debugger_sp ? debugger_sp->GetPlatformList().GetSelectedPlatform() + : PlatformSP(); + match_info.GetProcessInfo().GetArchitecture().SetTriple( + option_arg, platform_sp.get()); + } break; + + case 'n': + match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, + false); + match_info.SetNameMatchType(eNameMatchEquals); + break; + + case 'e': + match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, + false); + match_info.SetNameMatchType(eNameMatchEndsWith); + break; + + case 's': + match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, + false); + match_info.SetNameMatchType(eNameMatchStartsWith); + break; + + case 'c': + match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, + false); + match_info.SetNameMatchType(eNameMatchContains); + break; + + case 'r': + match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, + false); + match_info.SetNameMatchType(eNameMatchRegularExpression); + break; + + case 'A': + show_args = true; + break; + + case 'v': + verbose = true; + break; + + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + match_info.Clear(); + show_args = false; + verbose = false; + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + ProcessInstanceInfoMatch match_info; + bool show_args; + bool verbose; + }; + + CommandOptions m_options; }; OptionDefinition -CommandObjectPlatformProcessList::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectPlatformProcessList::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "List the process info for a specific process ID."}, {LLDB_OPT_SET_2, true, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that match a string."}, {LLDB_OPT_SET_3, true, "ends-with", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that end with a string."}, @@ -1634,596 +1414,519 @@ CommandObjectPlatformProcessList::CommandOptions::g_option_table[] = {LLDB_OPT_SET_FROM_TO(1, 6), false, "show-args", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show process arguments instead of the process executable basename."}, {LLDB_OPT_SET_FROM_TO(1, 6), false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose output."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // "platform process info" //---------------------------------------------------------------------- -class CommandObjectPlatformProcessInfo : public CommandObjectParsed -{ +class CommandObjectPlatformProcessInfo : public CommandObjectParsed { public: - CommandObjectPlatformProcessInfo (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform process info", - "Get detailed information for one or more process by process ID.", - "platform process info [ ...]", - 0) - { - CommandArgumentEntry arg; - CommandArgumentData pid_args; - - // Define the first (and only) variant of this arg. - pid_args.arg_type = eArgTypePid; - pid_args.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (pid_args); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectPlatformProcessInfo(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "platform process info", + "Get detailed information for one or more process by process ID.", + "platform process info [ ...]", 0) { + CommandArgumentEntry arg; + CommandArgumentData pid_args; + + // Define the first (and only) variant of this arg. + pid_args.arg_type = eArgTypePid; + pid_args.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(pid_args); - ~CommandObjectPlatformProcessInfo() override = default; + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectPlatformProcessInfo() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - PlatformSP platform_sp; - if (target) - { - platform_sp = target->GetPlatform(); - } - if (!platform_sp) - { - platform_sp = m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); - } - - if (platform_sp) - { - const size_t argc = args.GetArgumentCount(); - if (argc > 0) - { - Error error; - - if (platform_sp->IsConnected()) - { - Stream &ostrm = result.GetOutputStream(); - bool success; - for (size_t i=0; iGetProcessInfo (pid, proc_info)) - { - ostrm.Printf ("Process information for process %" PRIu64 ":\n", pid); - proc_info.Dump (ostrm, platform_sp.get()); - } - else - { - ostrm.Printf ("error: no process information is available for process %" PRIu64 "\n", pid); - } - ostrm.EOL(); - } - else - { - result.AppendErrorWithFormat ("invalid process ID argument '%s'", arg); - result.SetStatus (eReturnStatusFailed); - break; - } - } - } - else - { - // Not connected... - result.AppendErrorWithFormat ("not connected to '%s'", platform_sp->GetPluginName().GetCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - // No args - result.AppendError ("one or more process id(s) must be specified"); - result.SetStatus (eReturnStatusFailed); + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + PlatformSP platform_sp; + if (target) { + platform_sp = target->GetPlatform(); + } + if (!platform_sp) { + platform_sp = + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform(); + } + + if (platform_sp) { + const size_t argc = args.GetArgumentCount(); + if (argc > 0) { + Error error; + + if (platform_sp->IsConnected()) { + Stream &ostrm = result.GetOutputStream(); + bool success; + for (size_t i = 0; i < argc; ++i) { + const char *arg = args.GetArgumentAtIndex(i); + lldb::pid_t pid = StringConvert::ToUInt32( + arg, LLDB_INVALID_PROCESS_ID, 0, &success); + if (success) { + ProcessInstanceInfo proc_info; + if (platform_sp->GetProcessInfo(pid, proc_info)) { + ostrm.Printf("Process information for process %" PRIu64 ":\n", + pid); + proc_info.Dump(ostrm, platform_sp.get()); + } else { + ostrm.Printf("error: no process information is available for " + "process %" PRIu64 "\n", + pid); + } + ostrm.EOL(); + } else { + result.AppendErrorWithFormat("invalid process ID argument '%s'", + arg); + result.SetStatus(eReturnStatusFailed); + break; } - } - else - { - result.AppendError ("no platform is currently selected"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + } + } else { + // Not connected... + result.AppendErrorWithFormat( + "not connected to '%s'", + platform_sp->GetPluginName().GetCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + // No args + result.AppendError("one or more process id(s) must be specified"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("no platform is currently selected"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; -class CommandObjectPlatformProcessAttach : public CommandObjectParsed -{ +class CommandObjectPlatformProcessAttach : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - char short_option = (char) m_getopt_table[option_idx].val; - bool success = false; - switch (short_option) - { - case 'p': - { - lldb::pid_t pid = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_PROCESS_ID, 0, &success); - if (!success || pid == LLDB_INVALID_PROCESS_ID) - { - error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg); - } - else - { - attach_info.SetProcessID (pid); - } - } - break; - - case 'P': - attach_info.SetProcessPluginName (option_arg); - break; - - case 'n': - attach_info.GetExecutableFile().SetFile(option_arg, false); - break; - - case 'w': - attach_info.SetWaitForLaunch(true); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - attach_info.Clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - bool - HandleOptionArgumentCompletion (Args &input, - int cursor_index, - int char_pos, - OptionElementVector &opt_element_vector, - int opt_element_index, - int match_start_point, - int max_return_elements, - CommandInterpreter &interpreter, - bool &word_complete, - StringList &matches) override - { - int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; - int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; - - // We are only completing the name option for now... - - const OptionDefinition *opt_defs = GetDefinitions(); - if (opt_defs[opt_defs_index].short_option == 'n') - { - // Are we in the name? - - // Look to see if there is a -P argument provided, and if so use that plugin, otherwise - // use the default plugin. - - const char *partial_name = nullptr; - partial_name = input.GetArgumentAtIndex(opt_arg_pos); - - PlatformSP platform_sp(interpreter.GetPlatform(true)); - if (platform_sp) - { - ProcessInstanceInfoList process_infos; - ProcessInstanceInfoMatch match_info; - if (partial_name) - { - match_info.GetProcessInfo().GetExecutableFile().SetFile(partial_name, false); - match_info.SetNameMatchType(eNameMatchStartsWith); - } - platform_sp->FindProcesses (match_info, process_infos); - const uint32_t num_matches = process_infos.GetSize(); - if (num_matches > 0) - { - for (uint32_t i=0; i"), - m_options() - { + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + char short_option = (char)m_getopt_table[option_idx].val; + bool success = false; + switch (short_option) { + case 'p': { + lldb::pid_t pid = StringConvert::ToUInt32( + option_arg, LLDB_INVALID_PROCESS_ID, 0, &success); + if (!success || pid == LLDB_INVALID_PROCESS_ID) { + error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg); + } else { + attach_info.SetProcessID(pid); + } + } break; + + case 'P': + attach_info.SetProcessPluginName(option_arg); + break; + + case 'n': + attach_info.GetExecutableFile().SetFile(option_arg, false); + break; + + case 'w': + attach_info.SetWaitForLaunch(true); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; } - ~CommandObjectPlatformProcessAttach() override = default; + void OptionParsingStarting(ExecutionContext *execution_context) override { + attach_info.Clear(); + } - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (platform_sp) - { - Error err; - ProcessSP remote_process_sp = - platform_sp->Attach(m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err); - if (err.Fail()) - { - result.AppendError(err.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - else if (!remote_process_sp) - { - result.AppendError("could not attach: unknown reason"); - result.SetStatus (eReturnStatusFailed); + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + bool HandleOptionArgumentCompletion( + Args &input, int cursor_index, int char_pos, + OptionElementVector &opt_element_vector, int opt_element_index, + int match_start_point, int max_return_elements, + CommandInterpreter &interpreter, bool &word_complete, + StringList &matches) override { + int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; + int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; + + // We are only completing the name option for now... + + const OptionDefinition *opt_defs = GetDefinitions(); + if (opt_defs[opt_defs_index].short_option == 'n') { + // Are we in the name? + + // Look to see if there is a -P argument provided, and if so use that + // plugin, otherwise + // use the default plugin. + + const char *partial_name = nullptr; + partial_name = input.GetArgumentAtIndex(opt_arg_pos); + + PlatformSP platform_sp(interpreter.GetPlatform(true)); + if (platform_sp) { + ProcessInstanceInfoList process_infos; + ProcessInstanceInfoMatch match_info; + if (partial_name) { + match_info.GetProcessInfo().GetExecutableFile().SetFile( + partial_name, false); + match_info.SetNameMatchType(eNameMatchStartsWith); + } + platform_sp->FindProcesses(match_info, process_infos); + const uint32_t num_matches = process_infos.GetSize(); + if (num_matches > 0) { + for (uint32_t i = 0; i < num_matches; ++i) { + matches.AppendString( + process_infos.GetProcessNameAtIndex(i), + process_infos.GetProcessNameLengthAtIndex(i)); } - else - result.SetStatus (eReturnStatusSuccessFinishResult); + } } - else - { - result.AppendError ("no platform is currently selected"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + } + + return false; } - - Options * - GetOptions () override - { - return &m_options; + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + ProcessAttachInfo attach_info; + }; + + CommandObjectPlatformProcessAttach(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "platform process attach", + "Attach to a process.", + "platform process attach "), + m_options() {} + + ~CommandObjectPlatformProcessAttach() override = default; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (platform_sp) { + Error err; + ProcessSP remote_process_sp = platform_sp->Attach( + m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err); + if (err.Fail()) { + result.AppendError(err.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else if (!remote_process_sp) { + result.AppendError("could not attach: unknown reason"); + result.SetStatus(eReturnStatusFailed); + } else + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("no platform is currently selected"); + result.SetStatus(eReturnStatusFailed); } - + return result.Succeeded(); + } + + Options *GetOptions() override { return &m_options; } + protected: - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectPlatformProcessAttach::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectPlatformProcessAttach::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, {LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "The process ID of an existing process to attach to."}, {LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "The name of the process to attach to."}, {LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Wait for the process with to launch."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectPlatformProcess : public CommandObjectMultiword -{ +class CommandObjectPlatformProcess : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectPlatformProcess(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "platform process", - "Commands to query, launch and attach to processes on the current platform.", - "platform process [attach|launch|list] ...") - { - LoadSubCommand ("attach", CommandObjectSP (new CommandObjectPlatformProcessAttach (interpreter))); - LoadSubCommand ("launch", CommandObjectSP (new CommandObjectPlatformProcessLaunch (interpreter))); - LoadSubCommand ("info" , CommandObjectSP (new CommandObjectPlatformProcessInfo (interpreter))); - LoadSubCommand ("list" , CommandObjectSP (new CommandObjectPlatformProcessList (interpreter))); - } - - ~CommandObjectPlatformProcess() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectPlatformProcess(CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "platform process", + "Commands to query, launch and attach to " + "processes on the current platform.", + "platform process [attach|launch|list] ...") { + LoadSubCommand( + "attach", + CommandObjectSP(new CommandObjectPlatformProcessAttach(interpreter))); + LoadSubCommand( + "launch", + CommandObjectSP(new CommandObjectPlatformProcessLaunch(interpreter))); + LoadSubCommand("info", CommandObjectSP(new CommandObjectPlatformProcessInfo( + interpreter))); + LoadSubCommand("list", CommandObjectSP(new CommandObjectPlatformProcessList( + interpreter))); + } + + ~CommandObjectPlatformProcess() override = default; private: - //------------------------------------------------------------------ - // For CommandObjectPlatform only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectPlatformProcess); + //------------------------------------------------------------------ + // For CommandObjectPlatform only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformProcess); }; //---------------------------------------------------------------------- // "platform shell" //---------------------------------------------------------------------- -class CommandObjectPlatformShell : public CommandObjectRaw -{ +class CommandObjectPlatformShell : public CommandObjectRaw { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - timeout(10) - { - } + class CommandOptions : public Options { + public: + CommandOptions() : Options(), timeout(10) {} + + ~CommandOptions() override = default; + + virtual uint32_t GetNumDefinitions() { return 1; } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + + const char short_option = (char)g_option_table[option_idx].short_option; + + switch (short_option) { + case 't': { + bool success; + timeout = StringConvert::ToUInt32(option_value, 10, 10, &success); + if (!success) + error.SetErrorStringWithFormat( + "could not convert \"%s\" to a numeric value.", option_value); + break; + } + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; + } - ~CommandOptions() override = default; + void OptionParsingStarting(ExecutionContext *execution_context) override {} - virtual uint32_t - GetNumDefinitions () - { - return 1; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - - const char short_option = (char) g_option_table[option_idx].short_option; - - switch (short_option) - { - case 't': - { - bool success; - timeout = StringConvert::ToUInt32(option_value, 10, 10, &success); - if (!success) - error.SetErrorStringWithFormat("could not convert \"%s\" to a numeric value.", option_value); - break; - } - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - uint32_t timeout; - }; - - CommandObjectPlatformShell(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "platform shell", "Run a shell command on the current platform.", - "platform shell ", 0), - m_options() - { - } + // Options table: Required for subclasses of Options. - ~CommandObjectPlatformShell() override = default; + static OptionDefinition g_option_table[]; + uint32_t timeout; + }; - Options * - GetOptions () override - { - return &m_options; + CommandObjectPlatformShell(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "platform shell", + "Run a shell command on the current platform.", + "platform shell ", 0), + m_options() {} + + ~CommandObjectPlatformShell() override = default; + + Options *GetOptions() override { return &m_options; } + + bool DoExecute(const char *raw_command_line, + CommandReturnObject &result) override { + ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext(); + m_options.NotifyOptionParsingStarting(&exe_ctx); + + const char *expr = nullptr; + + // Print out an usage syntax on an empty command line. + if (raw_command_line[0] == '\0') { + result.GetOutputStream().Printf("%s\n", this->GetSyntax()); + return true; } - - bool - DoExecute (const char *raw_command_line, CommandReturnObject &result) override - { - ExecutionContext exe_ctx = - GetCommandInterpreter().GetExecutionContext(); - m_options.NotifyOptionParsingStarting(&exe_ctx); - - const char* expr = nullptr; - - // Print out an usage syntax on an empty command line. - if (raw_command_line[0] == '\0') - { - result.GetOutputStream().Printf("%s\n", this->GetSyntax()); - return true; - } - if (raw_command_line[0] == '-') - { - // We have some options and these options MUST end with --. - const char *end_options = nullptr; - const char *s = raw_command_line; - while (s && s[0]) - { - end_options = ::strstr (s, "--"); - if (end_options) - { - end_options += 2; // Get past the "--" - if (::isspace (end_options[0])) - { - expr = end_options; - while (::isspace (*expr)) - ++expr; - break; - } - } - s = end_options; - } - - if (end_options) - { - Args args (llvm::StringRef(raw_command_line, end_options - raw_command_line)); - if (!ParseOptions (args, result)) - return false; - } - } - - if (expr == nullptr) - expr = raw_command_line; - - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - Error error; - if (platform_sp) - { - FileSpec working_dir{}; - std::string output; - int status = -1; - int signo = -1; - error = (platform_sp->RunShellCommand (expr, working_dir, &status, &signo, &output, m_options.timeout)); - if (!output.empty()) - result.GetOutputStream().PutCString(output.c_str()); - if (status > 0) - { - if (signo > 0) - { - const char *signo_cstr = Host::GetSignalAsCString(signo); - if (signo_cstr) - result.GetOutputStream().Printf("error: command returned with status %i and signal %s\n", status, signo_cstr); - else - result.GetOutputStream().Printf("error: command returned with status %i and signal %i\n", status, signo); - } - else - result.GetOutputStream().Printf("error: command returned with status %i\n", status); - } - } - else - { - result.GetOutputStream().Printf("error: cannot run remote shell commands without a platform\n"); - error.SetErrorString("error: cannot run remote shell commands without a platform"); - } + if (raw_command_line[0] == '-') { + // We have some options and these options MUST end with --. + const char *end_options = nullptr; + const char *s = raw_command_line; + while (s && s[0]) { + end_options = ::strstr(s, "--"); + if (end_options) { + end_options += 2; // Get past the "--" + if (::isspace(end_options[0])) { + expr = end_options; + while (::isspace(*expr)) + ++expr; + break; + } + } + s = end_options; + } + + if (end_options) { + Args args( + llvm::StringRef(raw_command_line, end_options - raw_command_line)); + if (!ParseOptions(args, result)) + return false; + } + } - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - else - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - return true; + if (expr == nullptr) + expr = raw_command_line; + + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + Error error; + if (platform_sp) { + FileSpec working_dir{}; + std::string output; + int status = -1; + int signo = -1; + error = (platform_sp->RunShellCommand(expr, working_dir, &status, &signo, + &output, m_options.timeout)); + if (!output.empty()) + result.GetOutputStream().PutCString(output.c_str()); + if (status > 0) { + if (signo > 0) { + const char *signo_cstr = Host::GetSignalAsCString(signo); + if (signo_cstr) + result.GetOutputStream().Printf( + "error: command returned with status %i and signal %s\n", + status, signo_cstr); + else + result.GetOutputStream().Printf( + "error: command returned with status %i and signal %i\n", + status, signo); + } else + result.GetOutputStream().Printf( + "error: command returned with status %i\n", status); + } + } else { + result.GetOutputStream().Printf( + "error: cannot run remote shell commands without a platform\n"); + error.SetErrorString( + "error: cannot run remote shell commands without a platform"); + } + + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else { + result.SetStatus(eReturnStatusSuccessFinishResult); } + return true; + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectPlatformShell::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectPlatformShell::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue, "Seconds to wait for the remote host to finish running the command."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // "platform install" - install a target to a remote end //---------------------------------------------------------------------- -class CommandObjectPlatformInstall : public CommandObjectParsed -{ +class CommandObjectPlatformInstall : public CommandObjectParsed { public: - CommandObjectPlatformInstall (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "platform target-install", - "Install a target (bundle or executable file) to the remote end.", - "platform target-install ", - 0) - { + CommandObjectPlatformInstall(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "platform target-install", + "Install a target (bundle or executable file) to the remote end.", + "platform target-install ", 0) {} + + ~CommandObjectPlatformInstall() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + if (args.GetArgumentCount() != 2) { + result.AppendError("platform target-install takes two arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } + // TODO: move the bulk of this code over to the platform itself + FileSpec src(args.GetArgumentAtIndex(0), true); + FileSpec dst(args.GetArgumentAtIndex(1), false); + if (!src.Exists()) { + result.AppendError("source location does not exist or is not accessible"); + result.SetStatus(eReturnStatusFailed); + return false; + } + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + if (!platform_sp) { + result.AppendError("no platform currently selected"); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectPlatformInstall() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - if (args.GetArgumentCount() != 2) - { - result.AppendError("platform target-install takes two arguments"); - result.SetStatus(eReturnStatusFailed); - return false; - } - // TODO: move the bulk of this code over to the platform itself - FileSpec src(args.GetArgumentAtIndex(0), true); - FileSpec dst(args.GetArgumentAtIndex(1), false); - if (!src.Exists()) - { - result.AppendError("source location does not exist or is not accessible"); - result.SetStatus(eReturnStatusFailed); - return false; - } - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - if (!platform_sp) - { - result.AppendError ("no platform currently selected"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - Error error = platform_sp->Install(src, dst); - if (error.Success()) - { - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendErrorWithFormat("install failed: %s", error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } - return result.Succeeded(); + Error error = platform_sp->Install(src, dst); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendErrorWithFormat("install failed: %s", error.AsCString()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; CommandObjectPlatform::CommandObjectPlatform(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "platform", "Commands to manage and create platforms.", - "platform [connect|disconnect|info|list|status|select] ...") -{ - LoadSubCommand ("select", CommandObjectSP (new CommandObjectPlatformSelect (interpreter))); - LoadSubCommand ("list" , CommandObjectSP (new CommandObjectPlatformList (interpreter))); - LoadSubCommand ("status", CommandObjectSP (new CommandObjectPlatformStatus (interpreter))); - LoadSubCommand ("connect", CommandObjectSP (new CommandObjectPlatformConnect (interpreter))); - LoadSubCommand ("disconnect", CommandObjectSP (new CommandObjectPlatformDisconnect (interpreter))); - LoadSubCommand ("settings", CommandObjectSP (new CommandObjectPlatformSettings (interpreter))); - LoadSubCommand ("mkdir", CommandObjectSP (new CommandObjectPlatformMkDir (interpreter))); - LoadSubCommand ("file", CommandObjectSP (new CommandObjectPlatformFile (interpreter))); - LoadSubCommand ("get-file", CommandObjectSP (new CommandObjectPlatformGetFile (interpreter))); - LoadSubCommand ("get-size", CommandObjectSP (new CommandObjectPlatformGetSize (interpreter))); - LoadSubCommand ("put-file", CommandObjectSP (new CommandObjectPlatformPutFile (interpreter))); - LoadSubCommand ("process", CommandObjectSP (new CommandObjectPlatformProcess (interpreter))); - LoadSubCommand ("shell", CommandObjectSP (new CommandObjectPlatformShell (interpreter))); - LoadSubCommand ("target-install", CommandObjectSP (new CommandObjectPlatformInstall (interpreter))); + : CommandObjectMultiword( + interpreter, "platform", "Commands to manage and create platforms.", + "platform [connect|disconnect|info|list|status|select] ...") { + LoadSubCommand("select", + CommandObjectSP(new CommandObjectPlatformSelect(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectPlatformList(interpreter))); + LoadSubCommand("status", + CommandObjectSP(new CommandObjectPlatformStatus(interpreter))); + LoadSubCommand("connect", CommandObjectSP( + new CommandObjectPlatformConnect(interpreter))); + LoadSubCommand( + "disconnect", + CommandObjectSP(new CommandObjectPlatformDisconnect(interpreter))); + LoadSubCommand("settings", CommandObjectSP(new CommandObjectPlatformSettings( + interpreter))); + LoadSubCommand("mkdir", + CommandObjectSP(new CommandObjectPlatformMkDir(interpreter))); + LoadSubCommand("file", + CommandObjectSP(new CommandObjectPlatformFile(interpreter))); + LoadSubCommand("get-file", CommandObjectSP(new CommandObjectPlatformGetFile( + interpreter))); + LoadSubCommand("get-size", CommandObjectSP(new CommandObjectPlatformGetSize( + interpreter))); + LoadSubCommand("put-file", CommandObjectSP(new CommandObjectPlatformPutFile( + interpreter))); + LoadSubCommand("process", CommandObjectSP( + new CommandObjectPlatformProcess(interpreter))); + LoadSubCommand("shell", + CommandObjectSP(new CommandObjectPlatformShell(interpreter))); + LoadSubCommand( + "target-install", + CommandObjectSP(new CommandObjectPlatformInstall(interpreter))); } CommandObjectPlatform::~CommandObjectPlatform() = default; diff --git a/lldb/source/Commands/CommandObjectPlatform.h b/lldb/source/Commands/CommandObjectPlatform.h index 023dff9f982..03b8ca00c81 100644 --- a/lldb/source/Commands/CommandObjectPlatform.h +++ b/lldb/source/Commands/CommandObjectPlatform.h @@ -23,15 +23,14 @@ namespace lldb_private { // CommandObjectPlatform //------------------------------------------------------------------------- -class CommandObjectPlatform : public CommandObjectMultiword -{ +class CommandObjectPlatform : public CommandObjectMultiword { public: - CommandObjectPlatform(CommandInterpreter &interpreter); + CommandObjectPlatform(CommandInterpreter &interpreter); - ~CommandObjectPlatform() override; + ~CommandObjectPlatform() override; private: - DISALLOW_COPY_AND_ASSIGN (CommandObjectPlatform); + DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatform); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectPlugin.cpp b/lldb/source/Commands/CommandObjectPlugin.cpp index 8d1a5a5d462..598b5da4a53 100644 --- a/lldb/source/Commands/CommandObjectPlugin.cpp +++ b/lldb/source/Commands/CommandObjectPlugin.cpp @@ -19,91 +19,78 @@ using namespace lldb; using namespace lldb_private; -class CommandObjectPluginLoad : public CommandObjectParsed -{ +class CommandObjectPluginLoad : public CommandObjectParsed { public: - CommandObjectPluginLoad (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "plugin load", + CommandObjectPluginLoad(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "plugin load", "Import a dylib that implements an LLDB plugin.", - nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentData cmd_arg; - - // Define the first (and only) variant of this arg. - cmd_arg.arg_type = eArgTypeFilename; - cmd_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (cmd_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - } + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentData cmd_arg; - ~CommandObjectPluginLoad() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + // Define the first (and only) variant of this arg. + cmd_arg.arg_type = eArgTypeFilename; + cmd_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(cmd_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectPluginLoad() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - size_t argc = command.GetArgumentCount(); - - if (argc != 1) - { - result.AppendError ("'plugin load' requires one argument"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const char* path = command.GetArgumentAtIndex(0); - - Error error; - - FileSpec dylib_fspec(path,true); - - if (m_interpreter.GetDebugger().LoadPlugin(dylib_fspec, error)) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } - - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + size_t argc = command.GetArgumentCount(); + + if (argc != 1) { + result.AppendError("'plugin load' requires one argument"); + result.SetStatus(eReturnStatusFailed); + return false; } + + const char *path = command.GetArgumentAtIndex(0); + + Error error; + + FileSpec dylib_fspec(path, true); + + if (m_interpreter.GetDebugger().LoadPlugin(dylib_fspec, error)) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + + return result.Succeeded(); + } }; CommandObjectPlugin::CommandObjectPlugin(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "plugin", "Commands for managing LLDB plugins.", - "plugin []") -{ - LoadSubCommand ("load", CommandObjectSP (new CommandObjectPluginLoad (interpreter))); + : CommandObjectMultiword(interpreter, "plugin", + "Commands for managing LLDB plugins.", + "plugin []") { + LoadSubCommand("load", + CommandObjectSP(new CommandObjectPluginLoad(interpreter))); } - + CommandObjectPlugin::~CommandObjectPlugin() = default; diff --git a/lldb/source/Commands/CommandObjectPlugin.h b/lldb/source/Commands/CommandObjectPlugin.h index 0a96041d2d3..d67aa43365d 100644 --- a/lldb/source/Commands/CommandObjectPlugin.h +++ b/lldb/source/Commands/CommandObjectPlugin.h @@ -16,19 +16,18 @@ // Other libraries and framework includes // Project includes -#include "lldb/lldb-types.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/lldb-types.h" namespace lldb_private { - - class CommandObjectPlugin : public CommandObjectMultiword - { - public: - CommandObjectPlugin (CommandInterpreter &interpreter); - - ~CommandObjectPlugin() override; - }; - + +class CommandObjectPlugin : public CommandObjectMultiword { +public: + CommandObjectPlugin(CommandInterpreter &interpreter); + + ~CommandObjectPlugin() override; +}; + } // namespace lldb_private #endif // liblldb_CommandObjectPlugin_h_ diff --git a/lldb/source/Commands/CommandObjectProcess.cpp b/lldb/source/Commands/CommandObjectProcess.cpp index 6d97dbf4426..77305fcef1a 100644 --- a/lldb/source/Commands/CommandObjectProcess.cpp +++ b/lldb/source/Commands/CommandObjectProcess.cpp @@ -15,15 +15,15 @@ #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointSite.h" -#include "lldb/Core/State.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" +#include "lldb/Core/State.h" #include "lldb/Host/Host.h" #include "lldb/Host/StringConvert.h" #include "lldb/Interpreter/Args.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/StopInfo.h" @@ -34,284 +34,273 @@ using namespace lldb; using namespace lldb_private; -class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed -{ +class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed { public: - CommandObjectProcessLaunchOrAttach (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax, - uint32_t flags, - const char *new_process_action) : - CommandObjectParsed (interpreter, name, help, syntax, flags), - m_new_process_action (new_process_action) {} + CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter, + const char *name, const char *help, + const char *syntax, uint32_t flags, + const char *new_process_action) + : CommandObjectParsed(interpreter, name, help, syntax, flags), + m_new_process_action(new_process_action) {} - ~CommandObjectProcessLaunchOrAttach() override = default; + ~CommandObjectProcessLaunchOrAttach() override = default; protected: - bool - StopProcessIfNecessary (Process *process, StateType &state, CommandReturnObject &result) - { - state = eStateInvalid; - if (process) - { - state = process->GetState(); - - if (process->IsAlive() && state != eStateConnected) - { - char message[1024]; - if (process->GetState() == eStateAttaching) - ::snprintf (message, sizeof(message), "There is a pending attach, abort it and %s?", m_new_process_action.c_str()); - else if (process->GetShouldDetach()) - ::snprintf (message, sizeof(message), "There is a running process, detach from it and %s?", m_new_process_action.c_str()); - else - ::snprintf (message, sizeof(message), "There is a running process, kill it and %s?", m_new_process_action.c_str()); - - if (!m_interpreter.Confirm (message, true)) - { - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - if (process->GetShouldDetach()) - { - bool keep_stopped = false; - Error detach_error (process->Detach(keep_stopped)); - if (detach_error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - process = nullptr; - } - else - { - result.AppendErrorWithFormat ("Failed to detach from process: %s\n", detach_error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - Error destroy_error (process->Destroy(false)); - if (destroy_error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - process = nullptr; - } - else - { - result.AppendErrorWithFormat ("Failed to kill process: %s\n", destroy_error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - } + bool StopProcessIfNecessary(Process *process, StateType &state, + CommandReturnObject &result) { + state = eStateInvalid; + if (process) { + state = process->GetState(); + + if (process->IsAlive() && state != eStateConnected) { + char message[1024]; + if (process->GetState() == eStateAttaching) + ::snprintf(message, sizeof(message), + "There is a pending attach, abort it and %s?", + m_new_process_action.c_str()); + else if (process->GetShouldDetach()) + ::snprintf(message, sizeof(message), + "There is a running process, detach from it and %s?", + m_new_process_action.c_str()); + else + ::snprintf(message, sizeof(message), + "There is a running process, kill it and %s?", + m_new_process_action.c_str()); + + if (!m_interpreter.Confirm(message, true)) { + result.SetStatus(eReturnStatusFailed); + return false; + } else { + if (process->GetShouldDetach()) { + bool keep_stopped = false; + Error detach_error(process->Detach(keep_stopped)); + if (detach_error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + process = nullptr; + } else { + result.AppendErrorWithFormat( + "Failed to detach from process: %s\n", + detach_error.AsCString()); + result.SetStatus(eReturnStatusFailed); } + } else { + Error destroy_error(process->Destroy(false)); + if (destroy_error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + process = nullptr; + } else { + result.AppendErrorWithFormat("Failed to kill process: %s\n", + destroy_error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } } - return result.Succeeded(); + } } + return result.Succeeded(); + } - std::string m_new_process_action; + std::string m_new_process_action; }; //------------------------------------------------------------------------- // CommandObjectProcessLaunch //------------------------------------------------------------------------- #pragma mark CommandObjectProcessLaunch -class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach -{ +class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach { public: - CommandObjectProcessLaunch (CommandInterpreter &interpreter) : - CommandObjectProcessLaunchOrAttach(interpreter, - "process launch", - "Launch the executable in the debugger.", - nullptr, - eCommandRequiresTarget, - "restart"), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData run_args_arg; - - // Define the first (and only) variant of this arg. - run_args_arg.arg_type = eArgTypeRunArgs; - run_args_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (run_args_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectProcessLaunch(CommandInterpreter &interpreter) + : CommandObjectProcessLaunchOrAttach( + interpreter, "process launch", + "Launch the executable in the debugger.", nullptr, + eCommandRequiresTarget, "restart"), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData run_args_arg; + + // Define the first (and only) variant of this arg. + run_args_arg.arg_type = eArgTypeRunArgs; + run_args_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(run_args_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectProcessLaunch() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } + + Options *GetOptions() override { return &m_options; } + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + // No repeat for "process launch"... + return ""; + } - ~CommandObjectProcessLaunch() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); +protected: + bool DoExecute(Args &launch_args, CommandReturnObject &result) override { + Debugger &debugger = m_interpreter.GetDebugger(); + Target *target = debugger.GetSelectedTarget().get(); + // If our listener is nullptr, users aren't allows to launch + ModuleSP exe_module_sp = target->GetExecutableModule(); + + if (exe_module_sp == nullptr) { + result.AppendError("no file in target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; } - Options * - GetOptions () override - { - return &m_options; + StateType state = eStateInvalid; + + if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result)) + return false; + + const char *target_settings_argv0 = target->GetArg0(); + + // Determine whether we will disable ASLR or leave it in the default state + // (i.e. enabled if the platform supports it). + // First check if the process launch options explicitly turn on/off + // disabling ASLR. If so, use that setting; + // otherwise, use the 'settings target.disable-aslr' setting. + bool disable_aslr = false; + if (m_options.disable_aslr != eLazyBoolCalculate) { + // The user specified an explicit setting on the process launch line. Use + // it. + disable_aslr = (m_options.disable_aslr == eLazyBoolYes); + } else { + // The user did not explicitly specify whether to disable ASLR. Fall back + // to the target.disable-aslr setting. + disable_aslr = target->GetDisableASLR(); } - const char * - GetRepeatCommand (Args ¤t_command_args, uint32_t index) override - { - // No repeat for "process launch"... - return ""; + if (disable_aslr) + m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR); + else + m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); + + if (target->GetDetachOnError()) + m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError); + + if (target->GetDisableSTDIO()) + m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO); + + Args environment; + target->GetEnvironmentAsArgs(environment); + if (environment.GetArgumentCount() > 0) + m_options.launch_info.GetEnvironmentEntries().AppendArguments( + environment); + + if (target_settings_argv0) { + m_options.launch_info.GetArguments().AppendArgument( + target_settings_argv0); + m_options.launch_info.SetExecutableFile( + exe_module_sp->GetPlatformFileSpec(), false); + } else { + m_options.launch_info.SetExecutableFile( + exe_module_sp->GetPlatformFileSpec(), true); } -protected: - bool - DoExecute (Args& launch_args, CommandReturnObject &result) override - { - Debugger &debugger = m_interpreter.GetDebugger(); - Target *target = debugger.GetSelectedTarget().get(); - // If our listener is nullptr, users aren't allows to launch - ModuleSP exe_module_sp = target->GetExecutableModule(); - - if (exe_module_sp == nullptr) - { - result.AppendError ("no file in target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - StateType state = eStateInvalid; - - if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result)) - return false; - - const char *target_settings_argv0 = target->GetArg0(); - - // Determine whether we will disable ASLR or leave it in the default state (i.e. enabled if the platform supports it). - // First check if the process launch options explicitly turn on/off disabling ASLR. If so, use that setting; - // otherwise, use the 'settings target.disable-aslr' setting. - bool disable_aslr = false; - if (m_options.disable_aslr != eLazyBoolCalculate) - { - // The user specified an explicit setting on the process launch line. Use it. - disable_aslr = (m_options.disable_aslr == eLazyBoolYes); - } - else - { - // The user did not explicitly specify whether to disable ASLR. Fall back to the target.disable-aslr setting. - disable_aslr = target->GetDisableASLR (); - } - - if (disable_aslr) - m_options.launch_info.GetFlags().Set (eLaunchFlagDisableASLR); - else - m_options.launch_info.GetFlags().Clear (eLaunchFlagDisableASLR); - - if (target->GetDetachOnError()) - m_options.launch_info.GetFlags().Set (eLaunchFlagDetachOnError); - - if (target->GetDisableSTDIO()) - m_options.launch_info.GetFlags().Set (eLaunchFlagDisableSTDIO); - - Args environment; - target->GetEnvironmentAsArgs (environment); - if (environment.GetArgumentCount() > 0) - m_options.launch_info.GetEnvironmentEntries ().AppendArguments (environment); - - if (target_settings_argv0) - { - m_options.launch_info.GetArguments().AppendArgument (target_settings_argv0); - m_options.launch_info.SetExecutableFile(exe_module_sp->GetPlatformFileSpec(), false); - } - else - { - m_options.launch_info.SetExecutableFile(exe_module_sp->GetPlatformFileSpec(), true); - } - - if (launch_args.GetArgumentCount() == 0) - { - m_options.launch_info.GetArguments().AppendArguments (target->GetProcessLaunchInfo().GetArguments()); - } - else - { - m_options.launch_info.GetArguments().AppendArguments (launch_args); - // Save the arguments for subsequent runs in the current target. - target->SetRunArguments (launch_args); - } + if (launch_args.GetArgumentCount() == 0) { + m_options.launch_info.GetArguments().AppendArguments( + target->GetProcessLaunchInfo().GetArguments()); + } else { + m_options.launch_info.GetArguments().AppendArguments(launch_args); + // Save the arguments for subsequent runs in the current target. + target->SetRunArguments(launch_args); + } - StreamString stream; - Error error = target->Launch(m_options.launch_info, &stream); - - if (error.Success()) - { - ProcessSP process_sp (target->GetProcessSP()); - if (process_sp) - { - // There is a race condition where this thread will return up the call stack to the main command - // handler and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has - // a chance to call PushProcessIOHandler(). - process_sp->SyncIOHandler (0, 2000); - - const char *data = stream.GetData(); - if (data && strlen(data) > 0) - result.AppendMessage(stream.GetData()); - const char *archname = exe_module_sp->GetArchitecture().GetArchitectureName(); - result.AppendMessageWithFormat ("Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(), exe_module_sp->GetFileSpec().GetPath().c_str(), archname); - result.SetStatus (eReturnStatusSuccessFinishResult); - result.SetDidChangeProcessState (true); - } - else - { - result.AppendError("no error returned from Target::Launch, and target has no process"); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + StreamString stream; + Error error = target->Launch(m_options.launch_info, &stream); + + if (error.Success()) { + ProcessSP process_sp(target->GetProcessSP()); + if (process_sp) { + // There is a race condition where this thread will return up the call + // stack to the main command + // handler and show an (lldb) prompt before HandlePrivateEvent (from + // PrivateStateThread) has + // a chance to call PushProcessIOHandler(). + process_sp->SyncIOHandler(0, 2000); + + const char *data = stream.GetData(); + if (data && strlen(data) > 0) + result.AppendMessage(stream.GetData()); + const char *archname = + exe_module_sp->GetArchitecture().GetArchitectureName(); + result.AppendMessageWithFormat( + "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(), + exe_module_sp->GetFileSpec().GetPath().c_str(), archname); + result.SetStatus(eReturnStatusSuccessFinishResult); + result.SetDidChangeProcessState(true); + } else { + result.AppendError( + "no error returned from Target::Launch, and target has no process"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } protected: - ProcessLaunchCommandOptions m_options; + ProcessLaunchCommandOptions m_options; }; - //#define SET1 LLDB_OPT_SET_1 //#define SET2 LLDB_OPT_SET_2 //#define SET3 LLDB_OPT_SET_3 // -//OptionDefinition -//CommandObjectProcessLaunch::CommandOptions::g_option_table[] = +// OptionDefinition +// CommandObjectProcessLaunch::CommandOptions::g_option_table[] = //{ // // clang-format off -// {SET1 | SET2 | SET3, false, "stop-at-entry", 's', OptionParser::eNoArgument, nullptr, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, -// {SET1, false, "stdin", 'i', OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Redirect stdin for the process to ."}, -// {SET1, false, "stdout", 'o', OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Redirect stdout for the process to ."}, -// {SET1, false, "stderr", 'e', OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Redirect stderr for the process to ."}, -// {SET1 | SET2 | SET3, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, -// { SET2, false, "tty", 't', OptionParser::eOptionalArgument, nullptr, 0, eArgTypeDirectoryName, "Start the process in a terminal. If is specified, look for a terminal whose name contains , else start the process in a new terminal."}, -// { SET3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."}, -// {SET1 | SET2 | SET3, false, "working-dir", 'w', OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Set the current working directory to when running the inferior."}, +// {SET1 | SET2 | SET3, false, "stop-at-entry", 's', OptionParser::eNoArgument, +// nullptr, 0, eArgTypeNone, "Stop at the entry point of the program +// when launching a process."}, +// {SET1, false, "stdin", 'i', +// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, +// "Redirect stdin for the process to ."}, +// {SET1, false, "stdout", 'o', +// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, +// "Redirect stdout for the process to ."}, +// {SET1, false, "stderr", 'e', +// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, +// "Redirect stderr for the process to ."}, +// {SET1 | SET2 | SET3, false, "plugin", 'p', +// OptionParser::eRequiredArgument, nullptr, 0, eArgTypePlugin, "Name of +// the process plugin you want to use."}, +// { SET2, false, "tty", 't', +// OptionParser::eOptionalArgument, nullptr, 0, eArgTypeDirectoryName, "Start +// the process in a terminal. If is specified, look for a terminal whose +// name contains , else start the process in a new terminal."}, +// { SET3, false, "no-stdio", 'n', OptionParser::eNoArgument, +// nullptr, 0, eArgTypeNone, "Do not set up for terminal I/O to go to +// running process."}, +// {SET1 | SET2 | SET3, false, "working-dir", 'w', +// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Set the +// current working directory to when running the inferior."}, // {0, false, nullptr, 0, 0, nullptr, 0, eArgTypeNone, nullptr} // // clang-format on //}; @@ -324,293 +313,255 @@ protected: // CommandObjectProcessAttach //------------------------------------------------------------------------- #pragma mark CommandObjectProcessAttach -class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach -{ +class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success = false; - switch (short_option) - { - case 'c': - attach_info.SetContinueOnceAttached(true); - break; - - case 'p': - { - lldb::pid_t pid = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_PROCESS_ID, 0, &success); - if (!success || pid == LLDB_INVALID_PROCESS_ID) - { - error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg); - } - else - { - attach_info.SetProcessID (pid); - } - } - break; - - case 'P': - attach_info.SetProcessPluginName (option_arg); - break; - - case 'n': - attach_info.GetExecutableFile().SetFile(option_arg, false); - break; - - case 'w': - attach_info.SetWaitForLaunch(true); - break; - - case 'i': - attach_info.SetIgnoreExisting(false); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - attach_info.Clear(); - } + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success = false; + switch (short_option) { + case 'c': + attach_info.SetContinueOnceAttached(true); + break; + + case 'p': { + lldb::pid_t pid = StringConvert::ToUInt32( + option_arg, LLDB_INVALID_PROCESS_ID, 0, &success); + if (!success || pid == LLDB_INVALID_PROCESS_ID) { + error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg); + } else { + attach_info.SetProcessID(pid); + } + } break; + + case 'P': + attach_info.SetProcessPluginName(option_arg); + break; + + case 'n': + attach_info.GetExecutableFile().SetFile(option_arg, false); + break; + + case 'w': + attach_info.SetWaitForLaunch(true); + break; + + case 'i': + attach_info.SetIgnoreExisting(false); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + attach_info.Clear(); + } - bool - HandleOptionArgumentCompletion (Args &input, - int cursor_index, - int char_pos, - OptionElementVector &opt_element_vector, - int opt_element_index, - int match_start_point, - int max_return_elements, - CommandInterpreter &interpreter, - bool &word_complete, - StringList &matches) override - { - int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; - int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; - - // We are only completing the name option for now... - - const OptionDefinition *opt_defs = GetDefinitions(); - if (opt_defs[opt_defs_index].short_option == 'n') - { - // Are we in the name? - - // Look to see if there is a -P argument provided, and if so use that plugin, otherwise - // use the default plugin. - - const char *partial_name = nullptr; - partial_name = input.GetArgumentAtIndex(opt_arg_pos); - - PlatformSP platform_sp(interpreter.GetPlatform(true)); - if (platform_sp) - { - ProcessInstanceInfoList process_infos; - ProcessInstanceInfoMatch match_info; - if (partial_name) - { - match_info.GetProcessInfo().GetExecutableFile().SetFile(partial_name, false); - match_info.SetNameMatchType(eNameMatchStartsWith); - } - platform_sp->FindProcesses (match_info, process_infos); - const size_t num_matches = process_infos.GetSize(); - if (num_matches > 0) - { - for (size_t i = 0; i < num_matches; ++i) - { - matches.AppendString (process_infos.GetProcessNameAtIndex(i), - process_infos.GetProcessNameLengthAtIndex(i)); - } - } - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + bool HandleOptionArgumentCompletion( + Args &input, int cursor_index, int char_pos, + OptionElementVector &opt_element_vector, int opt_element_index, + int match_start_point, int max_return_elements, + CommandInterpreter &interpreter, bool &word_complete, + StringList &matches) override { + int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; + int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; + + // We are only completing the name option for now... + + const OptionDefinition *opt_defs = GetDefinitions(); + if (opt_defs[opt_defs_index].short_option == 'n') { + // Are we in the name? + + // Look to see if there is a -P argument provided, and if so use that + // plugin, otherwise + // use the default plugin. + + const char *partial_name = nullptr; + partial_name = input.GetArgumentAtIndex(opt_arg_pos); + + PlatformSP platform_sp(interpreter.GetPlatform(true)); + if (platform_sp) { + ProcessInstanceInfoList process_infos; + ProcessInstanceInfoMatch match_info; + if (partial_name) { + match_info.GetProcessInfo().GetExecutableFile().SetFile( + partial_name, false); + match_info.SetNameMatchType(eNameMatchStartsWith); + } + platform_sp->FindProcesses(match_info, process_infos); + const size_t num_matches = process_infos.GetSize(); + if (num_matches > 0) { + for (size_t i = 0; i < num_matches; ++i) { + matches.AppendString( + process_infos.GetProcessNameAtIndex(i), + process_infos.GetProcessNameLengthAtIndex(i)); } - - return false; + } } + } - // Options table: Required for subclasses of Options. + return false; + } - static OptionDefinition g_option_table[]; + // Options table: Required for subclasses of Options. - // Instance variables to hold the values for command options. + static OptionDefinition g_option_table[]; - ProcessAttachInfo attach_info; - }; + // Instance variables to hold the values for command options. - CommandObjectProcessAttach (CommandInterpreter &interpreter) : - CommandObjectProcessLaunchOrAttach (interpreter, - "process attach", - "Attach to a process.", - "process attach ", - 0, - "attach"), - m_options() - { - } + ProcessAttachInfo attach_info; + }; - ~CommandObjectProcessAttach() override = default; + CommandObjectProcessAttach(CommandInterpreter &interpreter) + : CommandObjectProcessLaunchOrAttach( + interpreter, "process attach", "Attach to a process.", + "process attach ", 0, "attach"), + m_options() {} - Options * - GetOptions () override - { - return &m_options; - } + ~CommandObjectProcessAttach() override = default; -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - PlatformSP platform_sp (m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - // N.B. The attach should be synchronous. It doesn't help much to get the prompt back between initiating the attach - // and the target actually stopping. So even if the interpreter is set to be asynchronous, we wait for the stop - // ourselves here. - - StateType state = eStateInvalid; - Process *process = m_exe_ctx.GetProcessPtr(); - - if (!StopProcessIfNecessary (process, state, result)) - return false; - - if (target == nullptr) - { - // If there isn't a current target create one. - TargetSP new_target_sp; - Error error; - - error = m_interpreter.GetDebugger().GetTargetList().CreateTarget(m_interpreter.GetDebugger(), - nullptr, - nullptr, - false, - nullptr, // No platform options - new_target_sp); - target = new_target_sp.get(); - if (target == nullptr || error.Fail()) - { - result.AppendError(error.AsCString("Error creating target")); - return false; - } - m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target); - } - - // Record the old executable module, we want to issue a warning if the process of attaching changed the - // current executable (like somebody said "file foo" then attached to a PID whose executable was bar.) - - ModuleSP old_exec_module_sp = target->GetExecutableModule(); - ArchSpec old_arch_spec = target->GetArchitecture(); - - if (command.GetArgumentCount()) - { - result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + Options *GetOptions() override { return &m_options; } - m_interpreter.UpdateExecutionContext(nullptr); - StreamString stream; - const auto error = target->Attach(m_options.attach_info, &stream); - if (error.Success()) - { - ProcessSP process_sp (target->GetProcessSP()); - if (process_sp) - { - if (stream.GetData()) - result.AppendMessage(stream.GetData()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - result.SetDidChangeProcessState (true); - result.SetAbnormalStopWasExpected(true); - } - else - { - result.AppendError("no error returned from Target::Attach, and target has no process"); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("attach failed: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + PlatformSP platform_sp( + m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); + + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + // N.B. The attach should be synchronous. It doesn't help much to get the + // prompt back between initiating the attach + // and the target actually stopping. So even if the interpreter is set to + // be asynchronous, we wait for the stop + // ourselves here. + + StateType state = eStateInvalid; + Process *process = m_exe_ctx.GetProcessPtr(); + + if (!StopProcessIfNecessary(process, state, result)) + return false; + + if (target == nullptr) { + // If there isn't a current target create one. + TargetSP new_target_sp; + Error error; + + error = m_interpreter.GetDebugger().GetTargetList().CreateTarget( + m_interpreter.GetDebugger(), nullptr, nullptr, false, + nullptr, // No platform options + new_target_sp); + target = new_target_sp.get(); + if (target == nullptr || error.Fail()) { + result.AppendError(error.AsCString("Error creating target")); + return false; + } + m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target); + } - if (!result.Succeeded()) - return false; - - // Okay, we're done. Last step is to warn if the executable module has changed: - char new_path[PATH_MAX]; - ModuleSP new_exec_module_sp (target->GetExecutableModule()); - if (!old_exec_module_sp) - { - // We might not have a module if we attached to a raw pid... - if (new_exec_module_sp) - { - new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); - result.AppendMessageWithFormat("Executable module set to \"%s\".\n", new_path); - } - } - else if (old_exec_module_sp->GetFileSpec() != new_exec_module_sp->GetFileSpec()) - { - char old_path[PATH_MAX]; + // Record the old executable module, we want to issue a warning if the + // process of attaching changed the + // current executable (like somebody said "file foo" then attached to a PID + // whose executable was bar.) - old_exec_module_sp->GetFileSpec().GetPath (old_path, PATH_MAX); - new_exec_module_sp->GetFileSpec().GetPath (new_path, PATH_MAX); + ModuleSP old_exec_module_sp = target->GetExecutableModule(); + ArchSpec old_arch_spec = target->GetArchitecture(); - result.AppendWarningWithFormat("Executable module changed from \"%s\" to \"%s\".\n", - old_path, new_path); - } + if (command.GetArgumentCount()) { + result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (!old_arch_spec.IsValid()) - { - result.AppendMessageWithFormat ("Architecture set to: %s.\n", target->GetArchitecture().GetTriple().getTriple().c_str()); - } - else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) - { - result.AppendWarningWithFormat("Architecture changed from %s to %s.\n", - old_arch_spec.GetTriple().getTriple().c_str(), - target->GetArchitecture().GetTriple().getTriple().c_str()); - } + m_interpreter.UpdateExecutionContext(nullptr); + StreamString stream; + const auto error = target->Attach(m_options.attach_info, &stream); + if (error.Success()) { + ProcessSP process_sp(target->GetProcessSP()); + if (process_sp) { + if (stream.GetData()) + result.AppendMessage(stream.GetData()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + result.SetDidChangeProcessState(true); + result.SetAbnormalStopWasExpected(true); + } else { + result.AppendError( + "no error returned from Target::Attach, and target has no process"); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } - // This supports the use-case scenario of immediately continuing the process once attached. - if (m_options.attach_info.GetContinueOnceAttached()) - m_interpreter.HandleCommand("process continue", eLazyBoolNo, result); + if (!result.Succeeded()) + return false; + + // Okay, we're done. Last step is to warn if the executable module has + // changed: + char new_path[PATH_MAX]; + ModuleSP new_exec_module_sp(target->GetExecutableModule()); + if (!old_exec_module_sp) { + // We might not have a module if we attached to a raw pid... + if (new_exec_module_sp) { + new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); + result.AppendMessageWithFormat("Executable module set to \"%s\".\n", + new_path); + } + } else if (old_exec_module_sp->GetFileSpec() != + new_exec_module_sp->GetFileSpec()) { + char old_path[PATH_MAX]; + + old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX); + new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); + + result.AppendWarningWithFormat( + "Executable module changed from \"%s\" to \"%s\".\n", old_path, + new_path); + } - return result.Succeeded(); + if (!old_arch_spec.IsValid()) { + result.AppendMessageWithFormat( + "Architecture set to: %s.\n", + target->GetArchitecture().GetTriple().getTriple().c_str()); + } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) { + result.AppendWarningWithFormat( + "Architecture changed from %s to %s.\n", + old_arch_spec.GetTriple().getTriple().c_str(), + target->GetArchitecture().GetTriple().getTriple().c_str()); } - - CommandOptions m_options; + + // This supports the use-case scenario of immediately continuing the process + // once attached. + if (m_options.attach_info.GetContinueOnceAttached()) + m_interpreter.HandleCommand("process continue", eLazyBoolNo, result); + + return result.Succeeded(); + } + + CommandOptions m_options; }; -OptionDefinition -CommandObjectProcessAttach::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectProcessAttach::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "continue", 'c', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Immediately continue the process once attached."}, {LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, {LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "The process ID of an existing process to attach to."}, @@ -618,7 +569,7 @@ CommandObjectProcessAttach::CommandOptions::g_option_table[] = {LLDB_OPT_SET_2, false, "include-existing", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Include existing processes when doing attach -w."}, {LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Wait for the process with to launch."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -626,193 +577,170 @@ CommandObjectProcessAttach::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark CommandObjectProcessContinue -class CommandObjectProcessContinue : public CommandObjectParsed -{ +class CommandObjectProcessContinue : public CommandObjectParsed { public: - CommandObjectProcessContinue (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "process continue", - "Continue execution of all threads in the current process.", - "process continue", - eCommandRequiresProcess | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_options() - { - } + CommandObjectProcessContinue(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "process continue", + "Continue execution of all threads in the current process.", + "process continue", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() {} - ~CommandObjectProcessContinue() override = default; + ~CommandObjectProcessContinue() override = default; protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success = false; - switch (short_option) - { - case 'i': - m_ignore = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat ("invalid value for ignore option: \"%s\", should be a number.", option_arg); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_ignore = 0; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - uint32_t m_ignore; - }; - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - bool synchronous_execution = m_interpreter.GetSynchronous (); - StateType state = process->GetState(); - if (state == eStateStopped) - { - if (command.GetArgumentCount() != 0) - { - result.AppendErrorWithFormat ("The '%s' command does not take any arguments.\n", m_cmd_name.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success = false; + switch (short_option) { + case 'i': + m_ignore = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid value for ignore option: \"%s\", should be a number.", + option_arg); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - if (m_options.m_ignore > 0) - { - ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this()); - if (sel_thread_sp) - { - StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo(); - if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint) - { - lldb::break_id_t bp_site_id = (lldb::break_id_t)stop_info_sp->GetValue(); - BreakpointSiteSP bp_site_sp(process->GetBreakpointSiteList().FindByID(bp_site_id)); - if (bp_site_sp) - { - const size_t num_owners = bp_site_sp->GetNumberOfOwners(); - for (size_t i = 0; i < num_owners; i++) - { - Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); - if (!bp_ref.IsInternal()) - { - bp_ref.SetIgnoreCount(m_options.m_ignore); - } - } - } - } - } - } - - { // Scope for thread list mutex: - std::lock_guard guard(process->GetThreadList().GetMutex()); - const uint32_t num_threads = process->GetThreadList().GetSize(); - - // Set the actions that the threads should each take when resuming - for (uint32_t idx=0; idxGetThreadList().GetThreadAtIndex(idx)->SetResumeState (eStateRunning, override_suspend); - } - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_ignore = 0; + } - const uint32_t iohandler_id = process->GetIOHandlerID(); - - StreamString stream; - Error error; - if (synchronous_execution) - error = process->ResumeSynchronous (&stream); - else - error = process->Resume (); - - if (error.Success()) - { - // There is a race condition where this thread will return up the call stack to the main command - // handler and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has - // a chance to call PushProcessIOHandler(). - process->SyncIOHandler(iohandler_id, 2000); - - result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID()); - if (synchronous_execution) - { - // If any state changed events had anything to say, add that to the result - if (stream.GetData()) - result.AppendMessage(stream.GetData()); - - result.SetDidChangeProcessState (true); - result.SetStatus (eReturnStatusSuccessFinishNoResult); + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + uint32_t m_ignore; + }; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + bool synchronous_execution = m_interpreter.GetSynchronous(); + StateType state = process->GetState(); + if (state == eStateStopped) { + if (command.GetArgumentCount() != 0) { + result.AppendErrorWithFormat( + "The '%s' command does not take any arguments.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_options.m_ignore > 0) { + ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this()); + if (sel_thread_sp) { + StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo(); + if (stop_info_sp && + stop_info_sp->GetStopReason() == eStopReasonBreakpoint) { + lldb::break_id_t bp_site_id = + (lldb::break_id_t)stop_info_sp->GetValue(); + BreakpointSiteSP bp_site_sp( + process->GetBreakpointSiteList().FindByID(bp_site_id)); + if (bp_site_sp) { + const size_t num_owners = bp_site_sp->GetNumberOfOwners(); + for (size_t i = 0; i < num_owners; i++) { + Breakpoint &bp_ref = + bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); + if (!bp_ref.IsInternal()) { + bp_ref.SetIgnoreCount(m_options.m_ignore); } - else - { - result.SetStatus (eReturnStatusSuccessContinuingNoResult); - } - } - else - { - result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); + } } - } - else - { - result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n", - StateAsCString(state)); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + } + } + } + + { // Scope for thread list mutex: + std::lock_guard guard( + process->GetThreadList().GetMutex()); + const uint32_t num_threads = process->GetThreadList().GetSize(); + + // Set the actions that the threads should each take when resuming + for (uint32_t idx = 0; idx < num_threads; ++idx) { + const bool override_suspend = false; + process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState( + eStateRunning, override_suspend); + } + } + + const uint32_t iohandler_id = process->GetIOHandlerID(); + + StreamString stream; + Error error; + if (synchronous_execution) + error = process->ResumeSynchronous(&stream); + else + error = process->Resume(); + + if (error.Success()) { + // There is a race condition where this thread will return up the call + // stack to the main command + // handler and show an (lldb) prompt before HandlePrivateEvent (from + // PrivateStateThread) has + // a chance to call PushProcessIOHandler(). + process->SyncIOHandler(iohandler_id, 2000); + + result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n", + process->GetID()); + if (synchronous_execution) { + // If any state changed events had anything to say, add that to the + // result + if (stream.GetData()) + result.AppendMessage(stream.GetData()); + + result.SetDidChangeProcessState(true); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.SetStatus(eReturnStatusSuccessContinuingNoResult); + } + } else { + result.AppendErrorWithFormat("Failed to resume process: %s.\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat( + "Process cannot be continued from its current state (%s).\n", + StateAsCString(state)); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - Options * - GetOptions () override - { - return &m_options; - } - - CommandOptions m_options; + Options *GetOptions() override { return &m_options; } + + CommandOptions m_options; }; OptionDefinition -CommandObjectProcessContinue::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectProcessContinue::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "ignore-count",'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Ignore crossings of the breakpoint (if it exists) for the currently selected thread."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -820,127 +748,101 @@ CommandObjectProcessContinue::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark CommandObjectProcessDetach -class CommandObjectProcessDetach : public CommandObjectParsed -{ +class CommandObjectProcessDetach : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 's': - bool tmp_result; - bool success; - tmp_result = Args::StringToBoolean(option_arg, false, &success); - if (!success) - error.SetErrorStringWithFormat("invalid boolean option: \"%s\"", option_arg); - else - { - if (tmp_result) - m_keep_stopped = eLazyBoolYes; - else - m_keep_stopped = eLazyBoolNo; - } - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 's': + bool tmp_result; + bool success; + tmp_result = Args::StringToBoolean(option_arg, false, &success); + if (!success) + error.SetErrorStringWithFormat("invalid boolean option: \"%s\"", + option_arg); + else { + if (tmp_result) + m_keep_stopped = eLazyBoolYes; + else + m_keep_stopped = eLazyBoolNo; + } + break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_keep_stopped = eLazyBoolCalculate; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_keep_stopped = eLazyBoolCalculate; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. - LazyBool m_keep_stopped; - }; + // Instance variables to hold the values for command options. + LazyBool m_keep_stopped; + }; - CommandObjectProcessDetach(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "process detach", "Detach from the current target process.", - "process detach", - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched), - m_options() - { - } + CommandObjectProcessDetach(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process detach", + "Detach from the current target process.", + "process detach", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched), + m_options() {} - ~CommandObjectProcessDetach() override = default; + ~CommandObjectProcessDetach() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - // FIXME: This will be a Command Option: - bool keep_stopped; - if (m_options.m_keep_stopped == eLazyBoolCalculate) - { - // Check the process default: - keep_stopped = process->GetDetachKeepsStopped(); - } - else if (m_options.m_keep_stopped == eLazyBoolYes) - keep_stopped = true; - else - keep_stopped = false; - - Error error (process->Detach(keep_stopped)); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Detach failed: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + // FIXME: This will be a Command Option: + bool keep_stopped; + if (m_options.m_keep_stopped == eLazyBoolCalculate) { + // Check the process default: + keep_stopped = process->GetDetachKeepsStopped(); + } else if (m_options.m_keep_stopped == eLazyBoolYes) + keep_stopped = true; + else + keep_stopped = false; + + Error error(process->Detach(keep_stopped)); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectProcessDetach::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectProcessDetach::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "keep-stopped", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the process should be kept stopped on detach (if possible)."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -948,133 +850,108 @@ CommandObjectProcessDetach::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark CommandObjectProcessConnect -class CommandObjectProcessConnect : public CommandObjectParsed -{ +class CommandObjectProcessConnect : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'p': - plugin_name.assign (option_arg); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - plugin_name.clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - std::string plugin_name; - }; - - CommandObjectProcessConnect (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "process connect", - "Connect to a remote debug service.", - "process connect ", - 0), - m_options() - { + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); } - ~CommandObjectProcessConnect() override = default; + ~CommandOptions() override = default; - Options * - GetOptions () override - { - return &m_options; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'p': + plugin_name.assign(option_arg); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + plugin_name.clear(); } - + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + std::string plugin_name; + }; + + CommandObjectProcessConnect(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process connect", + "Connect to a remote debug service.", + "process connect ", 0), + m_options() {} + + ~CommandObjectProcessConnect() override = default; + + Options *GetOptions() override { return &m_options; } + protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (command.GetArgumentCount() != 1) - { - result.AppendErrorWithFormat ("'%s' takes exactly one argument:\nUsage: %s\n", - m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (command.GetArgumentCount() != 1) { + result.AppendErrorWithFormat( + "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(), + m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } - Process *process = m_exe_ctx.GetProcessPtr(); - if (process && process->IsAlive()) - { - result.AppendErrorWithFormat ("Process %" PRIu64 " is currently being debugged, kill the process before connecting.\n", - process->GetID()); - result.SetStatus (eReturnStatusFailed); - return false; - } + Process *process = m_exe_ctx.GetProcessPtr(); + if (process && process->IsAlive()) { + result.AppendErrorWithFormat( + "Process %" PRIu64 + " is currently being debugged, kill the process before connecting.\n", + process->GetID()); + result.SetStatus(eReturnStatusFailed); + return false; + } - const char *plugin_name = nullptr; - if (!m_options.plugin_name.empty()) - plugin_name = m_options.plugin_name.c_str(); - - Error error; - Debugger& debugger = m_interpreter.GetDebugger(); - PlatformSP platform_sp = m_interpreter.GetPlatform(true); - ProcessSP process_sp = platform_sp->ConnectProcess(command.GetArgumentAtIndex(0), - plugin_name, - debugger, - debugger.GetSelectedTarget().get(), - error); - if (error.Fail() || process_sp == nullptr) - { - result.AppendError(error.AsCString("Error connecting to the process")); - result.SetStatus (eReturnStatusFailed); - return false; - } - return true; + const char *plugin_name = nullptr; + if (!m_options.plugin_name.empty()) + plugin_name = m_options.plugin_name.c_str(); + + Error error; + Debugger &debugger = m_interpreter.GetDebugger(); + PlatformSP platform_sp = m_interpreter.GetPlatform(true); + ProcessSP process_sp = platform_sp->ConnectProcess( + command.GetArgumentAtIndex(0), plugin_name, debugger, + debugger.GetSelectedTarget().get(), error); + if (error.Fail() || process_sp == nullptr) { + result.AppendError(error.AsCString("Error connecting to the process")); + result.SetStatus(eReturnStatusFailed); + return false; } + return true; + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectProcessConnect::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectProcessConnect::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1082,25 +959,22 @@ CommandObjectProcessConnect::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark CommandObjectProcessPlugin -class CommandObjectProcessPlugin : public CommandObjectProxy -{ +class CommandObjectProcessPlugin : public CommandObjectProxy { public: - CommandObjectProcessPlugin(CommandInterpreter &interpreter) - : CommandObjectProxy(interpreter, "process plugin", - "Send a custom command to the current target process plug-in.", "process plugin ", 0) - { - } - - ~CommandObjectProcessPlugin() override = default; - - CommandObject * - GetProxyCommandObject() override - { - Process *process = m_interpreter.GetExecutionContext().GetProcessPtr(); - if (process) - return process->GetPluginCommandObject(); - return nullptr; - } + CommandObjectProcessPlugin(CommandInterpreter &interpreter) + : CommandObjectProxy( + interpreter, "process plugin", + "Send a custom command to the current target process plug-in.", + "process plugin ", 0) {} + + ~CommandObjectProcessPlugin() override = default; + + CommandObject *GetProxyCommandObject() override { + Process *process = m_interpreter.GetExecutionContext().GetProcessPtr(); + if (process) + return process->GetPluginCommandObject(); + return nullptr; + } }; //------------------------------------------------------------------------- @@ -1108,139 +982,113 @@ public: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessLoad -class CommandObjectProcessLoad : public CommandObjectParsed -{ +class CommandObjectProcessLoad : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - switch (short_option) - { - case 'i': - do_install = true; - if (option_arg && option_arg[0]) - install_path.SetFile(option_arg, false); - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + switch (short_option) { + case 'i': + do_install = true; + if (option_arg && option_arg[0]) + install_path.SetFile(option_arg, false); + break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - do_install = false; - install_path.Clear(); - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + do_install = false; + install_path.Clear(); + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - bool do_install; - FileSpec install_path; - }; - - CommandObjectProcessLoad (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "process load", - "Load a shared library into the current process.", - "process load [ ...]", - eCommandRequiresProcess | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_options() - { - } + // Options table: Required for subclasses of Options. + static OptionDefinition g_option_table[]; - ~CommandObjectProcessLoad() override = default; + // Instance variables to hold the values for command options. + bool do_install; + FileSpec install_path; + }; - Options * - GetOptions () override - { - return &m_options; - } + CommandObjectProcessLoad(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process load", + "Load a shared library into the current process.", + "process load [ ...]", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_options() {} -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - - const size_t argc = command.GetArgumentCount(); - for (uint32_t i = 0; i < argc; ++i) - { - Error error; - PlatformSP platform = process->GetTarget().GetPlatform(); - const char *image_path = command.GetArgumentAtIndex(i); - uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; - - if (!m_options.do_install) - { - FileSpec image_spec (image_path, false); - platform->ResolveRemotePath(image_spec, image_spec); - image_token = platform->LoadImage(process, FileSpec(), image_spec, error); - } - else if (m_options.install_path) - { - FileSpec image_spec (image_path, true); - platform->ResolveRemotePath(m_options.install_path, m_options.install_path); - image_token = platform->LoadImage(process, image_spec, m_options.install_path, error); - } - else - { - FileSpec image_spec (image_path, true); - image_token = platform->LoadImage(process, image_spec, FileSpec(), error); - } + ~CommandObjectProcessLoad() override = default; - if (image_token != LLDB_INVALID_IMAGE_TOKEN) - { - result.AppendMessageWithFormat ("Loading \"%s\"...ok\nImage %u loaded.\n", image_path, image_token); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("failed to load '%s': %s", image_path, error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - return result.Succeeded(); + Options *GetOptions() override { return &m_options; } + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + + const size_t argc = command.GetArgumentCount(); + for (uint32_t i = 0; i < argc; ++i) { + Error error; + PlatformSP platform = process->GetTarget().GetPlatform(); + const char *image_path = command.GetArgumentAtIndex(i); + uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; + + if (!m_options.do_install) { + FileSpec image_spec(image_path, false); + platform->ResolveRemotePath(image_spec, image_spec); + image_token = + platform->LoadImage(process, FileSpec(), image_spec, error); + } else if (m_options.install_path) { + FileSpec image_spec(image_path, true); + platform->ResolveRemotePath(m_options.install_path, + m_options.install_path); + image_token = platform->LoadImage(process, image_spec, + m_options.install_path, error); + } else { + FileSpec image_spec(image_path, true); + image_token = + platform->LoadImage(process, image_spec, FileSpec(), error); + } + + if (image_token != LLDB_INVALID_IMAGE_TOKEN) { + result.AppendMessageWithFormat( + "Loading \"%s\"...ok\nImage %u loaded.\n", image_path, image_token); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("failed to load '%s': %s", image_path, + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } } - - CommandOptions m_options; + return result.Succeeded(); + } + + CommandOptions m_options; }; -OptionDefinition -CommandObjectProcessLoad::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectProcessLoad::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "install", 'i', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypePath, "Install the shared library to the target. If specified without an argument then the library will installed in the current working directory."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1248,60 +1096,51 @@ CommandObjectProcessLoad::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark CommandObjectProcessUnload -class CommandObjectProcessUnload : public CommandObjectParsed -{ +class CommandObjectProcessUnload : public CommandObjectParsed { public: + CommandObjectProcessUnload(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "process unload", + "Unload a shared library from the current process using the index " + "returned by a previous call to \"process load\".", + "process unload ", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} - CommandObjectProcessUnload (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "process unload", - "Unload a shared library from the current process using the index returned by a previous call to \"process load\".", - "process unload ", - eCommandRequiresProcess | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ) - { - } - - ~CommandObjectProcessUnload() override = default; + ~CommandObjectProcessUnload() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - - const size_t argc = command.GetArgumentCount(); - - for (uint32_t i = 0; i < argc; ++i) - { - const char *image_token_cstr = command.GetArgumentAtIndex(i); - uint32_t image_token = StringConvert::ToUInt32(image_token_cstr, LLDB_INVALID_IMAGE_TOKEN, 0); - if (image_token == LLDB_INVALID_IMAGE_TOKEN) - { - result.AppendErrorWithFormat ("invalid image index argument '%s'", image_token_cstr); - result.SetStatus (eReturnStatusFailed); - break; - } - else - { - Error error (process->GetTarget().GetPlatform()->UnloadImage(process, image_token)); - if (error.Success()) - { - result.AppendMessageWithFormat ("Unloading shared library with index %u...ok\n", image_token); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("failed to unload image: %s", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - break; - } - } - } - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + + const size_t argc = command.GetArgumentCount(); + + for (uint32_t i = 0; i < argc; ++i) { + const char *image_token_cstr = command.GetArgumentAtIndex(i); + uint32_t image_token = StringConvert::ToUInt32( + image_token_cstr, LLDB_INVALID_IMAGE_TOKEN, 0); + if (image_token == LLDB_INVALID_IMAGE_TOKEN) { + result.AppendErrorWithFormat("invalid image index argument '%s'", + image_token_cstr); + result.SetStatus(eReturnStatusFailed); + break; + } else { + Error error(process->GetTarget().GetPlatform()->UnloadImage( + process, image_token)); + if (error.Success()) { + result.AppendMessageWithFormat( + "Unloading shared library with index %u...ok\n", image_token); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("failed to unload image: %s", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + break; + } + } } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1309,72 +1148,66 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessSignal -class CommandObjectProcessSignal : public CommandObjectParsed -{ +class CommandObjectProcessSignal : public CommandObjectParsed { public: - CommandObjectProcessSignal(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "process signal", "Send a UNIX signal to the current target process.", - nullptr, eCommandRequiresProcess | eCommandTryTargetAPILock) - { - CommandArgumentEntry arg; - CommandArgumentData signal_arg; - - // Define the first (and only) variant of this arg. - signal_arg.arg_type = eArgTypeUnixSignal; - signal_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (signal_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectProcessSignal(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process signal", + "Send a UNIX signal to the current target process.", + nullptr, eCommandRequiresProcess | + eCommandTryTargetAPILock) { + CommandArgumentEntry arg; + CommandArgumentData signal_arg; + + // Define the first (and only) variant of this arg. + signal_arg.arg_type = eArgTypeUnixSignal; + signal_arg.arg_repetition = eArgRepeatPlain; - ~CommandObjectProcessSignal() override = default; + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(signal_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectProcessSignal() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - - if (command.GetArgumentCount() == 1) - { - int signo = LLDB_INVALID_SIGNAL_NUMBER; - - const char *signal_name = command.GetArgumentAtIndex(0); - if (::isxdigit (signal_name[0])) - signo = StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); - else - signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); - - if (signo == LLDB_INVALID_SIGNAL_NUMBER) - { - result.AppendErrorWithFormat ("Invalid signal argument '%s'.\n", command.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - } - else - { - Error error (process->Signal (signo)); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Failed to send signal %i: %s\n", signo, error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - } - else - { - result.AppendErrorWithFormat("'%s' takes exactly one signal number argument:\nUsage: %s\n", m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + + if (command.GetArgumentCount() == 1) { + int signo = LLDB_INVALID_SIGNAL_NUMBER; + + const char *signal_name = command.GetArgumentAtIndex(0); + if (::isxdigit(signal_name[0])) + signo = + StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); + else + signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); + + if (signo == LLDB_INVALID_SIGNAL_NUMBER) { + result.AppendErrorWithFormat("Invalid signal argument '%s'.\n", + command.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + } else { + Error error(process->Signal(signo)); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo, + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } + } else { + result.AppendErrorWithFormat( + "'%s' takes exactly one signal number argument:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1382,53 +1215,43 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessInterrupt -class CommandObjectProcessInterrupt : public CommandObjectParsed -{ +class CommandObjectProcessInterrupt : public CommandObjectParsed { public: - CommandObjectProcessInterrupt(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "process interrupt", "Interrupt the current target process.", - "process interrupt", - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched) - { - } + CommandObjectProcessInterrupt(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process interrupt", + "Interrupt the current target process.", + "process interrupt", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched) {} - ~CommandObjectProcessInterrupt() override = default; + ~CommandObjectProcessInterrupt() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - if (process == nullptr) - { - result.AppendError ("no process to halt"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + if (process == nullptr) { + result.AppendError("no process to halt"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - bool clear_thread_plans = true; - Error error(process->Halt (clear_thread_plans)); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Failed to halt process: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", - m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + bool clear_thread_plans = true; + Error error(process->Halt(clear_thread_plans)); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Failed to halt process: %s\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1436,51 +1259,42 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessKill -class CommandObjectProcessKill : public CommandObjectParsed -{ +class CommandObjectProcessKill : public CommandObjectParsed { public: - CommandObjectProcessKill(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "process kill", "Terminate the current target process.", "process kill", - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched) - { - } + CommandObjectProcessKill(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process kill", + "Terminate the current target process.", + "process kill", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched) {} - ~CommandObjectProcessKill() override = default; + ~CommandObjectProcessKill() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - if (process == nullptr) - { - result.AppendError ("no process to kill"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + if (process == nullptr) { + result.AppendError("no process to kill"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - Error error (process->Destroy(true)); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Failed to kill process: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", - m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + Error error(process->Destroy(true)); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Failed to kill process: %s\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1488,61 +1302,45 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessSaveCore -class CommandObjectProcessSaveCore : public CommandObjectParsed -{ +class CommandObjectProcessSaveCore : public CommandObjectParsed { public: - CommandObjectProcessSaveCore (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "process save-core", - "Save the current process as a core file using an appropriate file type.", - "process save-core FILE", - eCommandRequiresProcess | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched) - { - } + CommandObjectProcessSaveCore(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process save-core", + "Save the current process as a core file using an " + "appropriate file type.", + "process save-core FILE", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched) {} - ~CommandObjectProcessSaveCore() override = default; + ~CommandObjectProcessSaveCore() override = default; protected: - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - ProcessSP process_sp = m_exe_ctx.GetProcessSP(); - if (process_sp) - { - if (command.GetArgumentCount() == 1) - { - FileSpec output_file(command.GetArgumentAtIndex(0), false); - Error error = PluginManager::SaveCore(process_sp, output_file); - if (error.Success()) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Failed to save core file for process: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("'%s' takes one arguments:\nUsage: %s\n", - m_cmd_name.c_str(), - m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("invalid process"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + ProcessSP process_sp = m_exe_ctx.GetProcessSP(); + if (process_sp) { + if (command.GetArgumentCount() == 1) { + FileSpec output_file(command.GetArgumentAtIndex(0), false); + Error error = PluginManager::SaveCore(process_sp, output_file); + if (error.Success()) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "Failed to save core file for process: %s\n", error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError("invalid process"); + result.SetStatus(eReturnStatusFailed); + return false; } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1550,37 +1348,32 @@ protected: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessStatus -class CommandObjectProcessStatus : public CommandObjectParsed -{ +class CommandObjectProcessStatus : public CommandObjectParsed { public: - CommandObjectProcessStatus(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "process status", - "Show status and stop location for the current target process.", "process status", - eCommandRequiresProcess | eCommandTryTargetAPILock) - { - } - - ~CommandObjectProcessStatus() override = default; - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Stream &strm = result.GetOutputStream(); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - // No need to check "process" for validity as eCommandRequiresProcess ensures it is valid - Process *process = m_exe_ctx.GetProcessPtr(); - const bool only_threads_with_stop_reason = true; - const uint32_t start_frame = 0; - const uint32_t num_frames = 1; - const uint32_t num_frames_with_source = 1; - process->GetStatus(strm); - process->GetThreadStatus (strm, - only_threads_with_stop_reason, - start_frame, - num_frames, - num_frames_with_source); - return result.Succeeded(); - } + CommandObjectProcessStatus(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "process status", + "Show status and stop location for the current target process.", + "process status", + eCommandRequiresProcess | eCommandTryTargetAPILock) {} + + ~CommandObjectProcessStatus() override = default; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + Stream &strm = result.GetOutputStream(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + // No need to check "process" for validity as eCommandRequiresProcess + // ensures it is valid + Process *process = m_exe_ctx.GetProcessPtr(); + const bool only_threads_with_stop_reason = true; + const uint32_t start_frame = 0; + const uint32_t num_frames = 1; + const uint32_t num_frames_with_source = 1; + process->GetStatus(strm); + process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame, + num_frames, num_frames_with_source); + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -1588,324 +1381,303 @@ public: //------------------------------------------------------------------------- #pragma mark CommandObjectProcessHandle -class CommandObjectProcessHandle : public CommandObjectParsed -{ +class CommandObjectProcessHandle : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 's': - stop = option_arg; - break; - case 'n': - notify = option_arg; - break; - case 'p': - pass = option_arg; - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 's': + stop = option_arg; + break; + case 'n': + notify = option_arg; + break; + case 'p': + pass = option_arg; + break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - stop.clear(); - notify.clear(); - pass.clear(); - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + stop.clear(); + notify.clear(); + pass.clear(); + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - std::string stop; - std::string notify; - std::string pass; - }; + std::string stop; + std::string notify; + std::string pass; + }; - CommandObjectProcessHandle(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "process handle", - "Manage LLDB handling of OS signals for the current target process. Defaults to showing current policy.", - nullptr), - m_options() - { - SetHelpLong ("\nIf no signals are specified, update them all. If no update " - "option is specified, list the current values."); - CommandArgumentEntry arg; - CommandArgumentData signal_arg; + CommandObjectProcessHandle(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "process handle", + "Manage LLDB handling of OS signals for the " + "current target process. Defaults to showing " + "current policy.", + nullptr), + m_options() { + SetHelpLong("\nIf no signals are specified, update them all. If no update " + "option is specified, list the current values."); + CommandArgumentEntry arg; + CommandArgumentData signal_arg; - signal_arg.arg_type = eArgTypeUnixSignal; - signal_arg.arg_repetition = eArgRepeatStar; + signal_arg.arg_type = eArgTypeUnixSignal; + signal_arg.arg_repetition = eArgRepeatStar; - arg.push_back (signal_arg); - - m_arguments.push_back (arg); - } + arg.push_back(signal_arg); - ~CommandObjectProcessHandle() override = default; + m_arguments.push_back(arg); + } - Options * - GetOptions () override - { - return &m_options; - } + ~CommandObjectProcessHandle() override = default; - bool - VerifyCommandOptionValue (const std::string &option, int &real_value) - { - bool okay = true; - bool success = false; - bool tmp_value = Args::StringToBoolean (option.c_str(), false, &success); - - if (success && tmp_value) - real_value = 1; - else if (success && !tmp_value) - real_value = 0; - else - { - // If the value isn't 'true' or 'false', it had better be 0 or 1. - real_value = StringConvert::ToUInt32 (option.c_str(), 3); - if (real_value != 0 && real_value != 1) - okay = false; - } - - return okay; - } + Options *GetOptions() override { return &m_options; } - void - PrintSignalHeader (Stream &str) - { - str.Printf ("NAME PASS STOP NOTIFY\n"); - str.Printf ("=========== ===== ===== ======\n"); - } + bool VerifyCommandOptionValue(const std::string &option, int &real_value) { + bool okay = true; + bool success = false; + bool tmp_value = Args::StringToBoolean(option.c_str(), false, &success); - void - PrintSignal(Stream &str, int32_t signo, const char *sig_name, const UnixSignalsSP &signals_sp) - { - bool stop; - bool suppress; - bool notify; - - str.Printf ("%-11s ", sig_name); - if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) - { - bool pass = !suppress; - str.Printf ("%s %s %s", - (pass ? "true " : "false"), - (stop ? "true " : "false"), - (notify ? "true " : "false")); - } - str.Printf ("\n"); + if (success && tmp_value) + real_value = 1; + else if (success && !tmp_value) + real_value = 0; + else { + // If the value isn't 'true' or 'false', it had better be 0 or 1. + real_value = StringConvert::ToUInt32(option.c_str(), 3); + if (real_value != 0 && real_value != 1) + okay = false; } - void - PrintSignalInformation(Stream &str, Args &signal_args, int num_valid_signals, const UnixSignalsSP &signals_sp) + return okay; + } + + void PrintSignalHeader(Stream &str) { + str.Printf("NAME PASS STOP NOTIFY\n"); + str.Printf("=========== ===== ===== ======\n"); + } + + void PrintSignal(Stream &str, int32_t signo, const char *sig_name, + const UnixSignalsSP &signals_sp) { + bool stop; + bool suppress; + bool notify; + + str.Printf("%-11s ", sig_name); + if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) { + bool pass = !suppress; + str.Printf("%s %s %s", (pass ? "true " : "false"), + (stop ? "true " : "false"), (notify ? "true " : "false")); + } + str.Printf("\n"); + } + + void PrintSignalInformation(Stream &str, Args &signal_args, + int num_valid_signals, + const UnixSignalsSP &signals_sp) { + PrintSignalHeader(str); + + if (num_valid_signals > 0) { + size_t num_args = signal_args.GetArgumentCount(); + for (size_t i = 0; i < num_args; ++i) { + int32_t signo = signals_sp->GetSignalNumberFromName( + signal_args.GetArgumentAtIndex(i)); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) + PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i), + signals_sp); + } + } else // Print info for ALL signals { - PrintSignalHeader (str); - - if (num_valid_signals > 0) - { - size_t num_args = signal_args.GetArgumentCount(); - for (size_t i = 0; i < num_args; ++i) - { - int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); - if (signo != LLDB_INVALID_SIGNAL_NUMBER) - PrintSignal (str, signo, signal_args.GetArgumentAtIndex (i), signals_sp); - } - } - else // Print info for ALL signals - { - int32_t signo = signals_sp->GetFirstSignalNumber(); - while (signo != LLDB_INVALID_SIGNAL_NUMBER) - { - PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), signals_sp); - signo = signals_sp->GetNextSignalNumber(signo); - } - } + int32_t signo = signals_sp->GetFirstSignalNumber(); + while (signo != LLDB_INVALID_SIGNAL_NUMBER) { + PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), + signals_sp); + signo = signals_sp->GetNextSignalNumber(signo); + } } + } protected: - bool - DoExecute (Args &signal_args, CommandReturnObject &result) override - { - TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); - - if (!target_sp) - { - result.AppendError ("No current target;" - " cannot handle signals until you have a valid target and process.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - ProcessSP process_sp = target_sp->GetProcessSP(); - - if (!process_sp) - { - result.AppendError ("No current process; cannot handle signals until you have a valid process.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &signal_args, CommandReturnObject &result) override { + TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); + + if (!target_sp) { + result.AppendError("No current target;" + " cannot handle signals until you have a valid target " + "and process.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } - int stop_action = -1; // -1 means leave the current setting alone - int pass_action = -1; // -1 means leave the current setting alone - int notify_action = -1; // -1 means leave the current setting alone + ProcessSP process_sp = target_sp->GetProcessSP(); - if (! m_options.stop.empty() - && ! VerifyCommandOptionValue (m_options.stop, stop_action)) - { - result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (!process_sp) { + result.AppendError("No current process; cannot handle signals until you " + "have a valid process.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (! m_options.notify.empty() - && ! VerifyCommandOptionValue (m_options.notify, notify_action)) - { - result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } + int stop_action = -1; // -1 means leave the current setting alone + int pass_action = -1; // -1 means leave the current setting alone + int notify_action = -1; // -1 means leave the current setting alone - if (! m_options.pass.empty() - && ! VerifyCommandOptionValue (m_options.pass, pass_action)) - { - result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (!m_options.stop.empty() && + !VerifyCommandOptionValue(m_options.stop, stop_action)) { + result.AppendError("Invalid argument for command option --stop; must be " + "true or false.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } - size_t num_args = signal_args.GetArgumentCount(); - UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); - int num_signals_set = 0; - - if (num_args > 0) - { - for (size_t i = 0; i < num_args; ++i) - { - int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); - if (signo != LLDB_INVALID_SIGNAL_NUMBER) - { - // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees - // the value is either 0 or 1. - if (stop_action != -1) - signals_sp->SetShouldStop(signo, stop_action); - if (pass_action != -1) - { - bool suppress = !pass_action; - signals_sp->SetShouldSuppress(signo, suppress); - } - if (notify_action != -1) - signals_sp->SetShouldNotify(signo, notify_action); - ++num_signals_set; - } - else - { - result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); - } - } - } - else - { - // No signal specified, if any command options were specified, update ALL signals. - if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) - { - if (m_interpreter.Confirm ("Do you really want to update all the signals?", false)) - { - int32_t signo = signals_sp->GetFirstSignalNumber(); - while (signo != LLDB_INVALID_SIGNAL_NUMBER) - { - if (notify_action != -1) - signals_sp->SetShouldNotify(signo, notify_action); - if (stop_action != -1) - signals_sp->SetShouldStop(signo, stop_action); - if (pass_action != -1) - { - bool suppress = !pass_action; - signals_sp->SetShouldSuppress(signo, suppress); - } - signo = signals_sp->GetNextSignalNumber(signo); - } - } + if (!m_options.notify.empty() && + !VerifyCommandOptionValue(m_options.notify, notify_action)) { + result.AppendError("Invalid argument for command option --notify; must " + "be true or false.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (!m_options.pass.empty() && + !VerifyCommandOptionValue(m_options.pass, pass_action)) { + result.AppendError("Invalid argument for command option --pass; must be " + "true or false.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + size_t num_args = signal_args.GetArgumentCount(); + UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); + int num_signals_set = 0; + + if (num_args > 0) { + for (size_t i = 0; i < num_args; ++i) { + int32_t signo = signals_sp->GetSignalNumberFromName( + signal_args.GetArgumentAtIndex(i)); + if (signo != LLDB_INVALID_SIGNAL_NUMBER) { + // Casting the actions as bools here should be okay, because + // VerifyCommandOptionValue guarantees + // the value is either 0 or 1. + if (stop_action != -1) + signals_sp->SetShouldStop(signo, stop_action); + if (pass_action != -1) { + bool suppress = !pass_action; + signals_sp->SetShouldSuppress(signo, suppress); + } + if (notify_action != -1) + signals_sp->SetShouldNotify(signo, notify_action); + ++num_signals_set; + } else { + result.AppendErrorWithFormat("Invalid signal name '%s'\n", + signal_args.GetArgumentAtIndex(i)); + } + } + } else { + // No signal specified, if any command options were specified, update ALL + // signals. + if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) { + if (m_interpreter.Confirm( + "Do you really want to update all the signals?", false)) { + int32_t signo = signals_sp->GetFirstSignalNumber(); + while (signo != LLDB_INVALID_SIGNAL_NUMBER) { + if (notify_action != -1) + signals_sp->SetShouldNotify(signo, notify_action); + if (stop_action != -1) + signals_sp->SetShouldStop(signo, stop_action); + if (pass_action != -1) { + bool suppress = !pass_action; + signals_sp->SetShouldSuppress(signo, suppress); } + signo = signals_sp->GetNextSignalNumber(signo); + } } + } + } - PrintSignalInformation (result.GetOutputStream(), signal_args, num_signals_set, signals_sp); + PrintSignalInformation(result.GetOutputStream(), signal_args, + num_signals_set, signals_sp); - if (num_signals_set > 0) - result.SetStatus (eReturnStatusSuccessFinishNoResult); - else - result.SetStatus (eReturnStatusFailed); + if (num_signals_set > 0) + result.SetStatus(eReturnStatusSuccessFinishNoResult); + else + result.SetStatus(eReturnStatusFailed); - return result.Succeeded(); - } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectProcessHandle::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectProcessHandle::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "stop", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the process should be stopped if the signal is received."}, {LLDB_OPT_SET_1, false, "notify", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the debugger should notify the user if the signal is received."}, {LLDB_OPT_SET_1, false, "pass", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectMultiwordProcess //------------------------------------------------------------------------- -CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "process", "Commands for interacting with processes on the current platform.", - "process []") -{ - LoadSubCommand ("attach", CommandObjectSP (new CommandObjectProcessAttach (interpreter))); - LoadSubCommand ("launch", CommandObjectSP (new CommandObjectProcessLaunch (interpreter))); - LoadSubCommand ("continue", CommandObjectSP (new CommandObjectProcessContinue (interpreter))); - LoadSubCommand ("connect", CommandObjectSP (new CommandObjectProcessConnect (interpreter))); - LoadSubCommand ("detach", CommandObjectSP (new CommandObjectProcessDetach (interpreter))); - LoadSubCommand ("load", CommandObjectSP (new CommandObjectProcessLoad (interpreter))); - LoadSubCommand ("unload", CommandObjectSP (new CommandObjectProcessUnload (interpreter))); - LoadSubCommand ("signal", CommandObjectSP (new CommandObjectProcessSignal (interpreter))); - LoadSubCommand ("handle", CommandObjectSP (new CommandObjectProcessHandle (interpreter))); - LoadSubCommand ("status", CommandObjectSP (new CommandObjectProcessStatus (interpreter))); - LoadSubCommand ("interrupt", CommandObjectSP (new CommandObjectProcessInterrupt (interpreter))); - LoadSubCommand ("kill", CommandObjectSP (new CommandObjectProcessKill (interpreter))); - LoadSubCommand ("plugin", CommandObjectSP (new CommandObjectProcessPlugin (interpreter))); - LoadSubCommand ("save-core", CommandObjectSP (new CommandObjectProcessSaveCore (interpreter))); +CommandObjectMultiwordProcess::CommandObjectMultiwordProcess( + CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "process", + "Commands for interacting with processes on the current platform.", + "process []") { + LoadSubCommand("attach", + CommandObjectSP(new CommandObjectProcessAttach(interpreter))); + LoadSubCommand("launch", + CommandObjectSP(new CommandObjectProcessLaunch(interpreter))); + LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue( + interpreter))); + LoadSubCommand("connect", + CommandObjectSP(new CommandObjectProcessConnect(interpreter))); + LoadSubCommand("detach", + CommandObjectSP(new CommandObjectProcessDetach(interpreter))); + LoadSubCommand("load", + CommandObjectSP(new CommandObjectProcessLoad(interpreter))); + LoadSubCommand("unload", + CommandObjectSP(new CommandObjectProcessUnload(interpreter))); + LoadSubCommand("signal", + CommandObjectSP(new CommandObjectProcessSignal(interpreter))); + LoadSubCommand("handle", + CommandObjectSP(new CommandObjectProcessHandle(interpreter))); + LoadSubCommand("status", + CommandObjectSP(new CommandObjectProcessStatus(interpreter))); + LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt( + interpreter))); + LoadSubCommand("kill", + CommandObjectSP(new CommandObjectProcessKill(interpreter))); + LoadSubCommand("plugin", + CommandObjectSP(new CommandObjectProcessPlugin(interpreter))); + LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore( + interpreter))); } CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default; diff --git a/lldb/source/Commands/CommandObjectProcess.h b/lldb/source/Commands/CommandObjectProcess.h index 804c34261ba..0f520f63e1d 100644 --- a/lldb/source/Commands/CommandObjectProcess.h +++ b/lldb/source/Commands/CommandObjectProcess.h @@ -22,12 +22,11 @@ namespace lldb_private { // CommandObjectMultiwordProcess //------------------------------------------------------------------------- -class CommandObjectMultiwordProcess : public CommandObjectMultiword -{ +class CommandObjectMultiwordProcess : public CommandObjectMultiword { public: - CommandObjectMultiwordProcess (CommandInterpreter &interpreter); + CommandObjectMultiwordProcess(CommandInterpreter &interpreter); - ~CommandObjectMultiwordProcess() override; + ~CommandObjectMultiwordProcess() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectQuit.cpp b/lldb/source/Commands/CommandObjectQuit.cpp index a650398724f..2f258b71d14 100644 --- a/lldb/source/Commands/CommandObjectQuit.cpp +++ b/lldb/source/Commands/CommandObjectQuit.cpp @@ -25,75 +25,62 @@ using namespace lldb_private; //------------------------------------------------------------------------- CommandObjectQuit::CommandObjectQuit(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "quit", "Quit the LLDB debugger.", "quit") -{ -} + : CommandObjectParsed(interpreter, "quit", "Quit the LLDB debugger.", + "quit") {} -CommandObjectQuit::~CommandObjectQuit () -{ -} +CommandObjectQuit::~CommandObjectQuit() {} // returns true if there is at least one alive process -// is_a_detach will be true if all alive processes will be detached when you quit +// is_a_detach will be true if all alive processes will be detached when you +// quit // and false if at least one process will be killed instead -bool -CommandObjectQuit::ShouldAskForConfirmation (bool& is_a_detach) -{ - if (m_interpreter.GetPromptOnQuit() == false) - return false; - bool should_prompt = false; - is_a_detach = true; - for (uint32_t debugger_idx = 0; - debugger_idx < Debugger::GetNumDebuggers(); - debugger_idx++) - { - DebuggerSP debugger_sp(Debugger::GetDebuggerAtIndex(debugger_idx)); - if (!debugger_sp) - continue; - const TargetList& target_list(debugger_sp->GetTargetList()); - for (uint32_t target_idx = 0; - target_idx < static_cast(target_list.GetNumTargets()); - target_idx++) - { - TargetSP target_sp(target_list.GetTargetAtIndex(target_idx)); - if (!target_sp) - continue; - ProcessSP process_sp(target_sp->GetProcessSP()); - if (process_sp - && process_sp->IsValid() - && process_sp->IsAlive() - && process_sp->WarnBeforeDetach()) - { - should_prompt = true; - if (process_sp->GetShouldDetach() == false) - { - // if we need to kill at least one process, just say so and return - is_a_detach = false; - return should_prompt; - } - } +bool CommandObjectQuit::ShouldAskForConfirmation(bool &is_a_detach) { + if (m_interpreter.GetPromptOnQuit() == false) + return false; + bool should_prompt = false; + is_a_detach = true; + for (uint32_t debugger_idx = 0; debugger_idx < Debugger::GetNumDebuggers(); + debugger_idx++) { + DebuggerSP debugger_sp(Debugger::GetDebuggerAtIndex(debugger_idx)); + if (!debugger_sp) + continue; + const TargetList &target_list(debugger_sp->GetTargetList()); + for (uint32_t target_idx = 0; + target_idx < static_cast(target_list.GetNumTargets()); + target_idx++) { + TargetSP target_sp(target_list.GetTargetAtIndex(target_idx)); + if (!target_sp) + continue; + ProcessSP process_sp(target_sp->GetProcessSP()); + if (process_sp && process_sp->IsValid() && process_sp->IsAlive() && + process_sp->WarnBeforeDetach()) { + should_prompt = true; + if (process_sp->GetShouldDetach() == false) { + // if we need to kill at least one process, just say so and return + is_a_detach = false; + return should_prompt; } + } } - return should_prompt; + } + return should_prompt; } -bool -CommandObjectQuit::DoExecute (Args& command, CommandReturnObject &result) -{ - bool is_a_detach = true; - if (ShouldAskForConfirmation (is_a_detach)) - { - StreamString message; - message.Printf("Quitting LLDB will %s one or more processes. Do you really want to proceed", (is_a_detach ? "detach from" : "kill")); - if (!m_interpreter.Confirm(message.GetData(), true)) - { - result.SetStatus(eReturnStatusFailed); - return false; - } +bool CommandObjectQuit::DoExecute(Args &command, CommandReturnObject &result) { + bool is_a_detach = true; + if (ShouldAskForConfirmation(is_a_detach)) { + StreamString message; + message.Printf("Quitting LLDB will %s one or more processes. Do you really " + "want to proceed", + (is_a_detach ? "detach from" : "kill")); + if (!m_interpreter.Confirm(message.GetData(), true)) { + result.SetStatus(eReturnStatusFailed); + return false; } - const uint32_t event_type = CommandInterpreter::eBroadcastBitQuitCommandReceived; - m_interpreter.BroadcastEvent (event_type); - result.SetStatus (eReturnStatusQuit); - return true; + } + const uint32_t event_type = + CommandInterpreter::eBroadcastBitQuitCommandReceived; + m_interpreter.BroadcastEvent(event_type); + result.SetStatus(eReturnStatusQuit); + return true; } - diff --git a/lldb/source/Commands/CommandObjectQuit.h b/lldb/source/Commands/CommandObjectQuit.h index df9216b7e7e..f2998f8690f 100644 --- a/lldb/source/Commands/CommandObjectQuit.h +++ b/lldb/source/Commands/CommandObjectQuit.h @@ -22,21 +22,16 @@ namespace lldb_private { // CommandObjectQuit //------------------------------------------------------------------------- -class CommandObjectQuit : public CommandObjectParsed -{ +class CommandObjectQuit : public CommandObjectParsed { public: + CommandObjectQuit(CommandInterpreter &interpreter); - CommandObjectQuit (CommandInterpreter &interpreter); - - ~CommandObjectQuit() override; + ~CommandObjectQuit() override; protected: - bool - DoExecute(Args& args, - CommandReturnObject &result) override; - - bool - ShouldAskForConfirmation (bool& is_a_detach); + bool DoExecute(Args &args, CommandReturnObject &result) override; + + bool ShouldAskForConfirmation(bool &is_a_detach); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectRegister.cpp b/lldb/source/Commands/CommandObjectRegister.cpp index cc5c161c693..47a079d52be 100644 --- a/lldb/source/Commands/CommandObjectRegister.cpp +++ b/lldb/source/Commands/CommandObjectRegister.cpp @@ -15,17 +15,17 @@ // Project includes #include "CommandObjectRegister.h" #include "lldb/Core/DataExtractor.h" +#include "lldb/Core/Debugger.h" #include "lldb/Core/RegisterValue.h" #include "lldb/Core/Scalar.h" -#include "lldb/Core/Debugger.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionGroupFormat.h" #include "lldb/Interpreter/OptionValueArray.h" #include "lldb/Interpreter/OptionValueBoolean.h" #include "lldb/Interpreter/OptionValueUInt64.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" @@ -38,432 +38,377 @@ using namespace lldb_private; //---------------------------------------------------------------------- // "register read" //---------------------------------------------------------------------- -class CommandObjectRegisterRead : public CommandObjectParsed -{ +class CommandObjectRegisterRead : public CommandObjectParsed { public: - CommandObjectRegisterRead (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "register read", - "Dump the contents of one or more register values from the current frame. If no register is specified, dumps them all.", - nullptr, - eCommandRequiresFrame | - eCommandRequiresRegContext | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_option_group(), - m_format_options (eFormatDefault), - m_command_options () - { - CommandArgumentEntry arg; - CommandArgumentData register_arg; - - // Define the first (and only) variant of this arg. - register_arg.arg_type = eArgTypeRegisterName; - register_arg.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (register_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - - // Add the "--format" - m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_ALL); - m_option_group.Append (&m_command_options); - m_option_group.Finalize(); - } - - ~CommandObjectRegisterRead() override = default; - - Options * - GetOptions () override - { - return &m_option_group; - } - - bool - DumpRegister (const ExecutionContext &exe_ctx, - Stream &strm, - RegisterContext *reg_ctx, - const RegisterInfo *reg_info) - { - if (reg_info) - { - RegisterValue reg_value; - - if (reg_ctx->ReadRegister (reg_info, reg_value)) - { - strm.Indent (); - - bool prefix_with_altname = (bool)m_command_options.alternate_name; - bool prefix_with_name = !prefix_with_altname; - reg_value.Dump(&strm, reg_info, prefix_with_name, prefix_with_altname, m_format_options.GetFormat(), 8); - if ((reg_info->encoding == eEncodingUint) || (reg_info->encoding == eEncodingSint)) - { - Process *process = exe_ctx.GetProcessPtr(); - if (process && reg_info->byte_size == process->GetAddressByteSize()) - { - addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS); - if (reg_addr != LLDB_INVALID_ADDRESS) - { - Address so_reg_addr; - if (exe_ctx.GetTargetRef().GetSectionLoadList().ResolveLoadAddress(reg_addr, so_reg_addr)) - { - strm.PutCString (" "); - so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(), Address::DumpStyleResolvedDescription); - } - } - } - } - strm.EOL(); - return true; + CommandObjectRegisterRead(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "register read", + "Dump the contents of one or more register values from the current " + "frame. If no register is specified, dumps them all.", + nullptr, + eCommandRequiresFrame | eCommandRequiresRegContext | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_option_group(), m_format_options(eFormatDefault), + m_command_options() { + CommandArgumentEntry arg; + CommandArgumentData register_arg; + + // Define the first (and only) variant of this arg. + register_arg.arg_type = eArgTypeRegisterName; + register_arg.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(register_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + + // Add the "--format" + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_FORMAT | + OptionGroupFormat::OPTION_GROUP_GDB_FMT, + LLDB_OPT_SET_ALL); + m_option_group.Append(&m_command_options); + m_option_group.Finalize(); + } + + ~CommandObjectRegisterRead() override = default; + + Options *GetOptions() override { return &m_option_group; } + + bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm, + RegisterContext *reg_ctx, const RegisterInfo *reg_info) { + if (reg_info) { + RegisterValue reg_value; + + if (reg_ctx->ReadRegister(reg_info, reg_value)) { + strm.Indent(); + + bool prefix_with_altname = (bool)m_command_options.alternate_name; + bool prefix_with_name = !prefix_with_altname; + reg_value.Dump(&strm, reg_info, prefix_with_name, prefix_with_altname, + m_format_options.GetFormat(), 8); + if ((reg_info->encoding == eEncodingUint) || + (reg_info->encoding == eEncodingSint)) { + Process *process = exe_ctx.GetProcessPtr(); + if (process && reg_info->byte_size == process->GetAddressByteSize()) { + addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS); + if (reg_addr != LLDB_INVALID_ADDRESS) { + Address so_reg_addr; + if (exe_ctx.GetTargetRef() + .GetSectionLoadList() + .ResolveLoadAddress(reg_addr, so_reg_addr)) { + strm.PutCString(" "); + so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(), + Address::DumpStyleResolvedDescription); + } } + } } - return false; + strm.EOL(); + return true; + } } - - bool - DumpRegisterSet (const ExecutionContext &exe_ctx, - Stream &strm, - RegisterContext *reg_ctx, - size_t set_idx, - bool primitive_only=false) - { - uint32_t unavailable_count = 0; - uint32_t available_count = 0; - - if (!reg_ctx) - return false; // thread has no registers (i.e. core files are corrupt, incomplete crash logs...) - - const RegisterSet * const reg_set = reg_ctx->GetRegisterSet(set_idx); - if (reg_set) - { - strm.Printf ("%s:\n", (reg_set->name ? reg_set->name : "unknown") ); - strm.IndentMore (); - const size_t num_registers = reg_set->num_registers; - for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) - { - const uint32_t reg = reg_set->registers[reg_idx]; - const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg); - // Skip the dumping of derived register if primitive_only is true. - if (primitive_only && reg_info && reg_info->value_regs) - continue; - - if (DumpRegister (exe_ctx, strm, reg_ctx, reg_info)) - ++available_count; - else - ++unavailable_count; - } - strm.IndentLess (); - if (unavailable_count) - { - strm.Indent (); - strm.Printf("%u registers were unavailable.\n", unavailable_count); - } - strm.EOL(); - } - return available_count > 0; + return false; + } + + bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm, + RegisterContext *reg_ctx, size_t set_idx, + bool primitive_only = false) { + uint32_t unavailable_count = 0; + uint32_t available_count = 0; + + if (!reg_ctx) + return false; // thread has no registers (i.e. core files are corrupt, + // incomplete crash logs...) + + const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx); + if (reg_set) { + strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown")); + strm.IndentMore(); + const size_t num_registers = reg_set->num_registers; + for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) { + const uint32_t reg = reg_set->registers[reg_idx]; + const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg); + // Skip the dumping of derived register if primitive_only is true. + if (primitive_only && reg_info && reg_info->value_regs) + continue; + + if (DumpRegister(exe_ctx, strm, reg_ctx, reg_info)) + ++available_count; + else + ++unavailable_count; + } + strm.IndentLess(); + if (unavailable_count) { + strm.Indent(); + strm.Printf("%u registers were unavailable.\n", unavailable_count); + } + strm.EOL(); } + return available_count > 0; + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Stream &strm = result.GetOutputStream(); - RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext (); - - const RegisterInfo *reg_info = nullptr; - if (command.GetArgumentCount() == 0) - { - size_t set_idx; - - size_t num_register_sets = 1; - const size_t set_array_size = m_command_options.set_indexes.GetSize(); - if (set_array_size > 0) - { - for (size_t i = 0; i < set_array_size; ++i) - { - set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX, nullptr); - if (set_idx < reg_ctx->GetRegisterSetCount()) - { - if (!DumpRegisterSet (m_exe_ctx, strm, reg_ctx, set_idx)) - { - if (errno) - result.AppendErrorWithFormat ("register read failed: %s\n", strerror(errno)); - else - result.AppendError ("unknown error while reading registers.\n"); - result.SetStatus (eReturnStatusFailed); - break; - } - } - else - { - result.AppendErrorWithFormat("invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx); - result.SetStatus (eReturnStatusFailed); - break; - } - } - } - else - { - if (m_command_options.dump_all_sets) - num_register_sets = reg_ctx->GetRegisterSetCount(); - - for (set_idx = 0; set_idx < num_register_sets; ++set_idx) - { - // When dump_all_sets option is set, dump primitive as well as derived registers. - DumpRegisterSet (m_exe_ctx, strm, reg_ctx, set_idx, !m_command_options.dump_all_sets.GetCurrentValue()); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Stream &strm = result.GetOutputStream(); + RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); + + const RegisterInfo *reg_info = nullptr; + if (command.GetArgumentCount() == 0) { + size_t set_idx; + + size_t num_register_sets = 1; + const size_t set_array_size = m_command_options.set_indexes.GetSize(); + if (set_array_size > 0) { + for (size_t i = 0; i < set_array_size; ++i) { + set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX, + nullptr); + if (set_idx < reg_ctx->GetRegisterSetCount()) { + if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) { + if (errno) + result.AppendErrorWithFormat("register read failed: %s\n", + strerror(errno)); + else + result.AppendError("unknown error while reading registers.\n"); + result.SetStatus(eReturnStatusFailed); + break; } + } else { + result.AppendErrorWithFormat( + "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx); + result.SetStatus(eReturnStatusFailed); + break; + } } - else - { - if (m_command_options.dump_all_sets) - { - result.AppendError ("the --all option can't be used when registers names are supplied as arguments\n"); - result.SetStatus (eReturnStatusFailed); - } - else if (m_command_options.set_indexes.GetSize() > 0) - { - result.AppendError ("the --set option can't be used when registers names are supplied as arguments\n"); - result.SetStatus (eReturnStatusFailed); - } - else - { - const char *arg_cstr; - for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) - { - // in most LLDB commands we accept $rbx as the name for register RBX - and here we would - // reject it and non-existant. we should be more consistent towards the user and allow them - // to say reg read $rbx - internally, however, we should be strict and not allow ourselves - // to call our registers $rbx in our own API - if (*arg_cstr == '$') - arg_cstr = arg_cstr+1; - reg_info = reg_ctx->GetRegisterInfoByName(arg_cstr); - - if (reg_info) - { - if (!DumpRegister (m_exe_ctx, strm, reg_ctx, reg_info)) - strm.Printf("%-12s = error: unavailable\n", reg_info->name); - } - else - { - result.AppendErrorWithFormat ("Invalid register name '%s'.\n", arg_cstr); - } - } - } + } else { + if (m_command_options.dump_all_sets) + num_register_sets = reg_ctx->GetRegisterSetCount(); + + for (set_idx = 0; set_idx < num_register_sets; ++set_idx) { + // When dump_all_sets option is set, dump primitive as well as derived + // registers. + DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx, + !m_command_options.dump_all_sets.GetCurrentValue()); } - return result.Succeeded(); + } + } else { + if (m_command_options.dump_all_sets) { + result.AppendError("the --all option can't be used when registers " + "names are supplied as arguments\n"); + result.SetStatus(eReturnStatusFailed); + } else if (m_command_options.set_indexes.GetSize() > 0) { + result.AppendError("the --set option can't be used when " + "registers names are supplied as arguments\n"); + result.SetStatus(eReturnStatusFailed); + } else { + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + // in most LLDB commands we accept $rbx as the name for register RBX - + // and here we would + // reject it and non-existant. we should be more consistent towards + // the user and allow them + // to say reg read $rbx - internally, however, we should be strict and + // not allow ourselves + // to call our registers $rbx in our own API + if (*arg_cstr == '$') + arg_cstr = arg_cstr + 1; + reg_info = reg_ctx->GetRegisterInfoByName(arg_cstr); + + if (reg_info) { + if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info)) + strm.Printf("%-12s = error: unavailable\n", reg_info->name); + } else { + result.AppendErrorWithFormat("Invalid register name '%s'.\n", + arg_cstr); + } + } + } } + return result.Succeeded(); + } - class CommandOptions : public OptionGroup - { - public: - CommandOptions () : - OptionGroup(), - set_indexes (OptionValue::ConvertTypeToMask (OptionValue::eTypeUInt64)), - dump_all_sets (false, false), // Initial and default values are false - alternate_name (false, false) - { - } + class CommandOptions : public OptionGroup { + public: + CommandOptions() + : OptionGroup(), + set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)), + dump_all_sets(false, false), // Initial and default values are false + alternate_name(false, false) {} - ~CommandOptions() override = default; + ~CommandOptions() override = default; - uint32_t - GetNumDefinitions () override; + uint32_t GetNumDefinitions() override; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - set_indexes.Clear(); - dump_all_sets.Clear(); - alternate_name.Clear(); - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - Error - SetOptionValue (uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_option_table[option_idx].short_option; - switch (short_option) - { - case 's': - { - OptionValueSP value_sp (OptionValueUInt64::Create (option_value, error)); - if (value_sp) - set_indexes.AppendValue (value_sp); - } - break; - - case 'a': - // When we don't use OptionValue::SetValueFromCString(const char *) to - // set an option value, it won't be marked as being set in the options - // so we make a call to let users know the value was set via option - dump_all_sets.SetCurrentValue (true); - dump_all_sets.SetOptionWasSet (); - break; - - case 'A': - // When we don't use OptionValue::SetValueFromCString(const char *) to - // set an option value, it won't be marked as being set in the options - // so we make a call to let users know the value was set via option - alternate_name.SetCurrentValue (true); - dump_all_sets.SetOptionWasSet (); - break; - - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - return error; - } - - // Options table: Required for subclasses of Options. - - static const OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - OptionValueArray set_indexes; - OptionValueBoolean dump_all_sets; - OptionValueBoolean alternate_name; - }; - - OptionGroupOptions m_option_group; - OptionGroupFormat m_format_options; - CommandOptions m_command_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + set_indexes.Clear(); + dump_all_sets.Clear(); + alternate_name.Clear(); + } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_option_table[option_idx].short_option; + switch (short_option) { + case 's': { + OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error)); + if (value_sp) + set_indexes.AppendValue(value_sp); + } break; + + case 'a': + // When we don't use OptionValue::SetValueFromCString(const char *) to + // set an option value, it won't be marked as being set in the options + // so we make a call to let users know the value was set via option + dump_all_sets.SetCurrentValue(true); + dump_all_sets.SetOptionWasSet(); + break; + + case 'A': + // When we don't use OptionValue::SetValueFromCString(const char *) to + // set an option value, it won't be marked as being set in the options + // so we make a call to let users know the value was set via option + alternate_name.SetCurrentValue(true); + dump_all_sets.SetOptionWasSet(); + break; + + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } + return error; + } + + // Options table: Required for subclasses of Options. + + static const OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + OptionValueArray set_indexes; + OptionValueBoolean dump_all_sets; + OptionValueBoolean alternate_name; + }; + + OptionGroupOptions m_option_group; + OptionGroupFormat m_format_options; + CommandOptions m_command_options; }; const OptionDefinition -CommandObjectRegisterRead::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectRegisterRead::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "alternate", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display register names using the alternate register name if there is one."}, {LLDB_OPT_SET_1, false, "set", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Specify which register sets to dump by index."}, {LLDB_OPT_SET_2, false, "all", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show all register sets."}, - // clang-format on + // clang-format on }; -uint32_t -CommandObjectRegisterRead::CommandOptions::GetNumDefinitions () -{ - return llvm::array_lengthof(g_option_table); +uint32_t CommandObjectRegisterRead::CommandOptions::GetNumDefinitions() { + return llvm::array_lengthof(g_option_table); } //---------------------------------------------------------------------- // "register write" //---------------------------------------------------------------------- -class CommandObjectRegisterWrite : public CommandObjectParsed -{ +class CommandObjectRegisterWrite : public CommandObjectParsed { public: - CommandObjectRegisterWrite (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "register write", - "Modify a single register value.", - nullptr, - eCommandRequiresFrame | - eCommandRequiresRegContext | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData register_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - register_arg.arg_type = eArgTypeRegisterName; - register_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (register_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - } - - ~CommandObjectRegisterWrite() override = default; + CommandObjectRegisterWrite(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "register write", + "Modify a single register value.", nullptr, + eCommandRequiresFrame | eCommandRequiresRegContext | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData register_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + register_arg.arg_type = eArgTypeRegisterName; + register_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(register_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectRegisterWrite() override = default; protected: - bool - DoExecute(Args& command, CommandReturnObject &result) override - { - DataExtractor reg_data; - RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext (); - - if (command.GetArgumentCount() != 2) - { - result.AppendError ("register write takes exactly 2 arguments: "); - result.SetStatus (eReturnStatusFailed); + bool DoExecute(Args &command, CommandReturnObject &result) override { + DataExtractor reg_data; + RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); + + if (command.GetArgumentCount() != 2) { + result.AppendError( + "register write takes exactly 2 arguments: "); + result.SetStatus(eReturnStatusFailed); + } else { + const char *reg_name = command.GetArgumentAtIndex(0); + const char *value_str = command.GetArgumentAtIndex(1); + + // in most LLDB commands we accept $rbx as the name for register RBX - and + // here we would + // reject it and non-existant. we should be more consistent towards the + // user and allow them + // to say reg write $rbx - internally, however, we should be strict and + // not allow ourselves + // to call our registers $rbx in our own API + if (reg_name && *reg_name == '$') + reg_name = reg_name + 1; + + const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); + + if (reg_info) { + RegisterValue reg_value; + + Error error(reg_value.SetValueFromCString(reg_info, value_str)); + if (error.Success()) { + if (reg_ctx->WriteRegister(reg_info, reg_value)) { + // Toss all frames and anything else in the thread + // after a register has been written. + m_exe_ctx.GetThreadRef().Flush(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } } - else - { - const char *reg_name = command.GetArgumentAtIndex(0); - const char *value_str = command.GetArgumentAtIndex(1); - - // in most LLDB commands we accept $rbx as the name for register RBX - and here we would - // reject it and non-existant. we should be more consistent towards the user and allow them - // to say reg write $rbx - internally, however, we should be strict and not allow ourselves - // to call our registers $rbx in our own API - if (reg_name && *reg_name == '$') - reg_name = reg_name+1; - - const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); - - if (reg_info) - { - RegisterValue reg_value; - - Error error (reg_value.SetValueFromCString (reg_info, value_str)); - if (error.Success()) - { - if (reg_ctx->WriteRegister (reg_info, reg_value)) - { - // Toss all frames and anything else in the thread - // after a register has been written. - m_exe_ctx.GetThreadRef().Flush(); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - return true; - } - } - if (error.AsCString()) - { - result.AppendErrorWithFormat ("Failed to write register '%s' with value '%s': %s\n", - reg_name, - value_str, - error.AsCString()); - } - else - { - result.AppendErrorWithFormat ("Failed to write register '%s' with value '%s'", - reg_name, - value_str); - } - result.SetStatus (eReturnStatusFailed); - } - else - { - result.AppendErrorWithFormat ("Register not found for '%s'.\n", reg_name); - result.SetStatus (eReturnStatusFailed); - } + if (error.AsCString()) { + result.AppendErrorWithFormat( + "Failed to write register '%s' with value '%s': %s\n", reg_name, + value_str, error.AsCString()); + } else { + result.AppendErrorWithFormat( + "Failed to write register '%s' with value '%s'", reg_name, + value_str); } - return result.Succeeded(); + result.SetStatus(eReturnStatusFailed); + } else { + result.AppendErrorWithFormat("Register not found for '%s'.\n", + reg_name); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- @@ -471,11 +416,13 @@ protected: //---------------------------------------------------------------------- CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "register", - "Commands to access registers for the current thread and stack frame.", - "register [read|write] ...") -{ - LoadSubCommand ("read", CommandObjectSP (new CommandObjectRegisterRead (interpreter))); - LoadSubCommand ("write", CommandObjectSP (new CommandObjectRegisterWrite (interpreter))); + "Commands to access registers for the current " + "thread and stack frame.", + "register [read|write] ...") { + LoadSubCommand("read", + CommandObjectSP(new CommandObjectRegisterRead(interpreter))); + LoadSubCommand("write", + CommandObjectSP(new CommandObjectRegisterWrite(interpreter))); } CommandObjectRegister::~CommandObjectRegister() = default; diff --git a/lldb/source/Commands/CommandObjectRegister.h b/lldb/source/Commands/CommandObjectRegister.h index e7b6974bc99..81f2f6bae22 100644 --- a/lldb/source/Commands/CommandObjectRegister.h +++ b/lldb/source/Commands/CommandObjectRegister.h @@ -22,21 +22,20 @@ namespace lldb_private { // CommandObjectRegister //------------------------------------------------------------------------- -class CommandObjectRegister : public CommandObjectMultiword -{ +class CommandObjectRegister : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectRegister(CommandInterpreter &interpreter); + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectRegister(CommandInterpreter &interpreter); - ~CommandObjectRegister() override; + ~CommandObjectRegister() override; private: - //------------------------------------------------------------------ - // For CommandObjectRegister only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectRegister); + //------------------------------------------------------------------ + // For CommandObjectRegister only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectRegister); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectSettings.cpp b/lldb/source/Commands/CommandObjectSettings.cpp index 4c33f1d8b67..4d545d79382 100644 --- a/lldb/source/Commands/CommandObjectSettings.cpp +++ b/lldb/source/Commands/CommandObjectSettings.cpp @@ -15,9 +15,9 @@ #include "llvm/ADT/StringRef.h" // Project includes +#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/OptionValueProperties.h" using namespace lldb; @@ -27,39 +27,42 @@ using namespace lldb_private; // CommandObjectSettingsSet //------------------------------------------------------------------------- -class CommandObjectSettingsSet : public CommandObjectRaw -{ +class CommandObjectSettingsSet : public CommandObjectRaw { public: - CommandObjectSettingsSet(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "settings set", "Set the value of the specified debugger setting.", nullptr), - m_options() - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData var_name_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - - SetHelpLong ( -"\nWhen setting a dictionary or array variable, you can set multiple entries \ -at once by giving the values to the set command. For example:" R"( + CommandObjectSettingsSet(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings set", + "Set the value of the specified debugger setting.", + nullptr), + m_options() { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData var_name_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + + SetHelpLong( + "\nWhen setting a dictionary or array variable, you can set multiple entries \ +at once by giving the values to the set command. For example:" + R"( (lldb) settings set target.run-args value1 value2 value3 (lldb) settings set target.env-vars MYPATH=~/.:/usr/bin SOME_ENV_VAR=12345 @@ -72,1108 +75,987 @@ at once by giving the values to the set command. For example:" R"( 'MYPATH=~/.:/usr/bin' 'SOME_ENV_VAR=12345' -)" "Warning: The 'set' command re-sets the entire array or dictionary. If you \ +)" + "Warning: The 'set' command re-sets the entire array or dictionary. If you \ just want to add, remove or update individual values (or add something to \ the end), use one of the other settings sub-commands: append, replace, \ -insert-before or insert-after." - ); +insert-before or insert-after."); + } - } + ~CommandObjectSettingsSet() override = default; + + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_global(false) {} + + ~CommandOptions() override = default; - ~CommandObjectSettingsSet() override = default; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } + switch (short_option) { + case 'g': + m_global = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized options '%c'", + short_option); + break; + } - Options * - GetOptions () override - { - return &m_options; + return error; } - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_global(false) - { - } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'g': - m_global = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized options '%c'", short_option); - break; - } - - return error; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_global = false; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_global = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_global; - }; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - const size_t argc = input.GetArgumentCount(); - const char *arg = nullptr; - int setting_var_idx; - for (setting_var_idx = 1; setting_var_idx < static_cast(argc); - ++setting_var_idx) - { - arg = input.GetArgumentAtIndex(setting_var_idx); - if (arg && arg[0] != '-') - break; // We found our setting variable name index - } - if (cursor_index == setting_var_idx) - { - // Attempting to complete setting variable name - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - } - else - { - arg = input.GetArgumentAtIndex(cursor_index); - - if (arg) - { - if (arg[0] == '-') - { - // Complete option name - } - else - { - // Complete setting value - const char *setting_var_name = input.GetArgumentAtIndex(setting_var_idx); - Error error; - lldb::OptionValueSP value_sp (m_interpreter.GetDebugger().GetPropertyValue(&m_exe_ctx, setting_var_name, false, error)); - if (value_sp) - { - value_sp->AutoComplete (m_interpreter, - completion_str.c_str(), - match_start_point, - max_return_elements, - word_complete, - matches); - } - } - } + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + bool m_global; + }; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + const size_t argc = input.GetArgumentCount(); + const char *arg = nullptr; + int setting_var_idx; + for (setting_var_idx = 1; setting_var_idx < static_cast(argc); + ++setting_var_idx) { + arg = input.GetArgumentAtIndex(setting_var_idx); + if (arg && arg[0] != '-') + break; // We found our setting variable name index + } + if (cursor_index == setting_var_idx) { + // Attempting to complete setting variable name + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + } else { + arg = input.GetArgumentAtIndex(cursor_index); + + if (arg) { + if (arg[0] == '-') { + // Complete option name + } else { + // Complete setting value + const char *setting_var_name = + input.GetArgumentAtIndex(setting_var_idx); + Error error; + lldb::OptionValueSP value_sp( + m_interpreter.GetDebugger().GetPropertyValue( + &m_exe_ctx, setting_var_name, false, error)); + if (value_sp) { + value_sp->AutoComplete(m_interpreter, completion_str.c_str(), + match_start_point, max_return_elements, + word_complete, matches); + } } - return matches.GetSize(); + } } - + return matches.GetSize(); + } + protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - Args cmd_args(command); - - // Process possible options. - if (!ParseOptions (cmd_args, result)) - return false; - - const size_t argc = cmd_args.GetArgumentCount (); - if ((argc < 2) && (!m_options.m_global)) - { - result.AppendError ("'settings set' takes more arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + Args cmd_args(command); + + // Process possible options. + if (!ParseOptions(cmd_args, result)) + return false; + + const size_t argc = cmd_args.GetArgumentCount(); + if ((argc < 2) && (!m_options.m_global)) { + result.AppendError("'settings set' takes more arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings set' command requires a valid variable name"); - result.SetStatus (eReturnStatusFailed); - return false; - } + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError( + "'settings set' command requires a valid variable name"); + result.SetStatus(eReturnStatusFailed); + return false; + } - // Split the raw command into var_name and value pair. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, false, false); - - Error error; - if (m_options.m_global) - { - error = m_interpreter.GetDebugger().SetPropertyValue(nullptr, - eVarSetOperationAssign, - var_name, - var_value_cstr); - } - - if (error.Success()) - { - // FIXME this is the same issue as the one in commands script import - // we could be setting target.load-script-from-symbol-file which would cause - // Python scripts to be loaded, which could run LLDB commands - // (e.g. settings set target.process.python-os-plugin-path) and cause a crash - // if we did not clear the command's exe_ctx first - ExecutionContext exe_ctx(m_exe_ctx); - m_exe_ctx.Clear(); - error = m_interpreter.GetDebugger().SetPropertyValue (&exe_ctx, - eVarSetOperationAssign, - var_name, - var_value_cstr); - } + // Split the raw command into var_name and value pair. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, false, false); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } + Error error; + if (m_options.m_global) { + error = m_interpreter.GetDebugger().SetPropertyValue( + nullptr, eVarSetOperationAssign, var_name, var_value_cstr); + } + + if (error.Success()) { + // FIXME this is the same issue as the one in commands script import + // we could be setting target.load-script-from-symbol-file which would + // cause + // Python scripts to be loaded, which could run LLDB commands + // (e.g. settings set target.process.python-os-plugin-path) and cause a + // crash + // if we did not clear the command's exe_ctx first + ExecutionContext exe_ctx(m_exe_ctx); + m_exe_ctx.Clear(); + error = m_interpreter.GetDebugger().SetPropertyValue( + &exe_ctx, eVarSetOperationAssign, var_name, var_value_cstr); + } - return result.Succeeded(); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + result.SetStatus(eReturnStatusSuccessFinishResult); } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectSettingsSet::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectSettingsSet::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_2, false, "global", 'g', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Apply the new value to the global default value."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectSettingsShow -- Show current values //------------------------------------------------------------------------- -class CommandObjectSettingsShow : public CommandObjectParsed -{ +class CommandObjectSettingsShow : public CommandObjectParsed { public: - CommandObjectSettingsShow(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "settings show", - "Show matching debugger settings and their current values. Defaults to showing all settings.", nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentData var_name_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - } - - ~CommandObjectSettingsShow() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + CommandObjectSettingsShow(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "settings show", + "Show matching debugger settings and their current " + "values. Defaults to showing all settings.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentData var_name_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + } + + ~CommandObjectSettingsShow() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishResult); - - const size_t argc = args.GetArgumentCount (); - if (argc > 0) - { - for (size_t i = 0; i < argc; ++i) - { - const char *property_path = args.GetArgumentAtIndex (i); - - Error error(m_interpreter.GetDebugger().DumpPropertyValue (&m_exe_ctx, result.GetOutputStream(), property_path, OptionValue::eDumpGroupValue)); - if (error.Success()) - { - result.GetOutputStream().EOL(); - } - else - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - } - } - else - { - m_interpreter.GetDebugger().DumpAllPropertyValues (&m_exe_ctx, result.GetOutputStream(), OptionValue::eDumpGroupValue); + bool DoExecute(Args &args, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishResult); + + const size_t argc = args.GetArgumentCount(); + if (argc > 0) { + for (size_t i = 0; i < argc; ++i) { + const char *property_path = args.GetArgumentAtIndex(i); + + Error error(m_interpreter.GetDebugger().DumpPropertyValue( + &m_exe_ctx, result.GetOutputStream(), property_path, + OptionValue::eDumpGroupValue)); + if (error.Success()) { + result.GetOutputStream().EOL(); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); } - - return result.Succeeded(); + } + } else { + m_interpreter.GetDebugger().DumpAllPropertyValues( + &m_exe_ctx, result.GetOutputStream(), OptionValue::eDumpGroupValue); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsList -- List settable variables //------------------------------------------------------------------------- -class CommandObjectSettingsList : public CommandObjectParsed -{ +class CommandObjectSettingsList : public CommandObjectParsed { public: - CommandObjectSettingsList(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "settings list", - "List and describe matching debugger settings. Defaults to all listing all settings.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData var_name_arg; - CommandArgumentData prefix_name_arg; - - // Define the first variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatOptional; - - // Define the second variant of this arg. - prefix_name_arg.arg_type = eArgTypeSettingPrefix; - prefix_name_arg.arg_repetition = eArgRepeatOptional; - - arg.push_back (var_name_arg); - arg.push_back (prefix_name_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectSettingsList() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + CommandObjectSettingsList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "settings list", + "List and describe matching debugger settings. " + "Defaults to all listing all settings.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData var_name_arg; + CommandArgumentData prefix_name_arg; + + // Define the first variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatOptional; + + // Define the second variant of this arg. + prefix_name_arg.arg_type = eArgTypeSettingPrefix; + prefix_name_arg.arg_repetition = eArgRepeatOptional; + + arg.push_back(var_name_arg); + arg.push_back(prefix_name_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectSettingsList() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishResult); - - const bool will_modify = false; - const size_t argc = args.GetArgumentCount (); - if (argc > 0) - { - const bool dump_qualified_name = true; - - for (size_t i = 0; i < argc; ++i) - { - const char *property_path = args.GetArgumentAtIndex (i); - - const Property *property = m_interpreter.GetDebugger().GetValueProperties()->GetPropertyAtPath (&m_exe_ctx, will_modify, property_path); - - if (property) - { - property->DumpDescription (m_interpreter, result.GetOutputStream(), 0, dump_qualified_name); - } - else - { - result.AppendErrorWithFormat ("invalid property path '%s'", property_path); - result.SetStatus (eReturnStatusFailed); - } - } - } - else - { - m_interpreter.GetDebugger().DumpAllDescriptions (m_interpreter, result.GetOutputStream()); + bool DoExecute(Args &args, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishResult); + + const bool will_modify = false; + const size_t argc = args.GetArgumentCount(); + if (argc > 0) { + const bool dump_qualified_name = true; + + for (size_t i = 0; i < argc; ++i) { + const char *property_path = args.GetArgumentAtIndex(i); + + const Property *property = + m_interpreter.GetDebugger().GetValueProperties()->GetPropertyAtPath( + &m_exe_ctx, will_modify, property_path); + + if (property) { + property->DumpDescription(m_interpreter, result.GetOutputStream(), 0, + dump_qualified_name); + } else { + result.AppendErrorWithFormat("invalid property path '%s'", + property_path); + result.SetStatus(eReturnStatusFailed); } - - return result.Succeeded(); + } + } else { + m_interpreter.GetDebugger().DumpAllDescriptions(m_interpreter, + result.GetOutputStream()); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsRemove //------------------------------------------------------------------------- -class CommandObjectSettingsRemove : public CommandObjectRaw -{ +class CommandObjectSettingsRemove : public CommandObjectRaw { public: - CommandObjectSettingsRemove(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "settings remove", - "Remove a value from a setting, specified by array index or dictionary key.", nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData var_name_arg; - CommandArgumentData index_arg; - CommandArgumentData key_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first variant of this arg. - index_arg.arg_type = eArgTypeSettingIndex; - index_arg.arg_repetition = eArgRepeatPlain; - - // Define the second variant of this arg. - key_arg.arg_type = eArgTypeSettingKey; - key_arg.arg_repetition = eArgRepeatPlain; - - // Push both variants into this arg - arg2.push_back (index_arg); - arg2.push_back (key_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); + CommandObjectSettingsRemove(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings remove", + "Remove a value from a setting, specified by array " + "index or dictionary key.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData var_name_arg; + CommandArgumentData index_arg; + CommandArgumentData key_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first variant of this arg. + index_arg.arg_type = eArgTypeSettingIndex; + index_arg.arg_repetition = eArgRepeatPlain; + + // Define the second variant of this arg. + key_arg.arg_type = eArgTypeSettingKey; + key_arg.arg_repetition = eArgRepeatPlain; + + // Push both variants into this arg + arg2.push_back(index_arg); + arg2.push_back(key_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectSettingsRemove() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + return matches.GetSize(); + } + +protected: + bool DoExecute(const char *command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + + Args cmd_args(command); + + // Process possible options. + if (!ParseOptions(cmd_args, result)) + return false; + + const size_t argc = cmd_args.GetArgumentCount(); + if (argc == 0) { + result.AppendError("'settings set' takes an array or dictionary item, or " + "an array followed by one or more indexes, or a " + "dictionary followed by one or more key names to " + "remove"); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectSettingsRemove() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError( + "'settings set' command requires a valid variable name"); + result.SetStatus(eReturnStatusFailed); + return false; } -protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - Args cmd_args(command); - - // Process possible options. - if (!ParseOptions (cmd_args, result)) - return false; - - const size_t argc = cmd_args.GetArgumentCount (); - if (argc == 0) - { - result.AppendError ("'settings set' takes an array or dictionary item, or an array followed by one or more indexes, or a dictionary followed by one or more key names to remove"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings set' command requires a valid variable name"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Split the raw command into var_name and value pair. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - - Error error (m_interpreter.GetDebugger().SetPropertyValue (&m_exe_ctx, - eVarSetOperationRemove, - var_name, - var_value_cstr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - - return result.Succeeded(); + // Split the raw command into var_name and value pair. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, true, false); + + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationRemove, var_name, var_value_cstr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsReplace //------------------------------------------------------------------------- -class CommandObjectSettingsReplace : public CommandObjectRaw -{ +class CommandObjectSettingsReplace : public CommandObjectRaw { public: - CommandObjectSettingsReplace(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "settings replace", - "Replace the debugger setting value specified by array index or dictionary key.", nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentEntry arg3; - CommandArgumentData var_name_arg; - CommandArgumentData index_arg; - CommandArgumentData key_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first (variant of this arg. - index_arg.arg_type = eArgTypeSettingIndex; - index_arg.arg_repetition = eArgRepeatPlain; - - // Define the second (variant of this arg. - key_arg.arg_type = eArgTypeSettingKey; - key_arg.arg_repetition = eArgRepeatPlain; - - // Put both variants into this arg - arg2.push_back (index_arg); - arg2.push_back (key_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg3.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - m_arguments.push_back (arg3); - } - - ~CommandObjectSettingsReplace() override = default; - - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - - return matches.GetSize(); - } + CommandObjectSettingsReplace(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings replace", + "Replace the debugger setting value specified by " + "array index or dictionary key.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentEntry arg3; + CommandArgumentData var_name_arg; + CommandArgumentData index_arg; + CommandArgumentData key_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first (variant of this arg. + index_arg.arg_type = eArgTypeSettingIndex; + index_arg.arg_repetition = eArgRepeatPlain; + + // Define the second (variant of this arg. + key_arg.arg_type = eArgTypeSettingKey; + key_arg.arg_repetition = eArgRepeatPlain; + + // Put both variants into this arg + arg2.push_back(index_arg); + arg2.push_back(key_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg3.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + m_arguments.push_back(arg3); + } + + ~CommandObjectSettingsReplace() override = default; + + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + + return matches.GetSize(); + } protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - Args cmd_args(command); - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings replace' command requires a valid variable name; No value supplied"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - // Split the raw command into var_name, index_value, and value triple. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - - Error error(m_interpreter.GetDebugger().SetPropertyValue (&m_exe_ctx, - eVarSetOperationReplace, - var_name, - var_value_cstr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + + Args cmd_args(command); + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError("'settings replace' command requires a valid variable " + "name; No value supplied"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + // Split the raw command into var_name, index_value, and value triple. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, true, false); + + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationReplace, var_name, var_value_cstr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsInsertBefore //------------------------------------------------------------------------- -class CommandObjectSettingsInsertBefore : public CommandObjectRaw -{ +class CommandObjectSettingsInsertBefore : public CommandObjectRaw { public: - CommandObjectSettingsInsertBefore(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "settings insert-before", "Insert one or more values into an debugger array " - "setting immediately before the specified element " - "index.", - nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentEntry arg3; - CommandArgumentData var_name_arg; - CommandArgumentData index_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first (variant of this arg. - index_arg.arg_type = eArgTypeSettingIndex; - index_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (index_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg3.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - m_arguments.push_back (arg3); - } - - ~CommandObjectSettingsInsertBefore() override = default; - - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - - return matches.GetSize(); - } + CommandObjectSettingsInsertBefore(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings insert-before", + "Insert one or more values into an debugger array " + "setting immediately before the specified element " + "index.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentEntry arg3; + CommandArgumentData var_name_arg; + CommandArgumentData index_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first (variant of this arg. + index_arg.arg_type = eArgTypeSettingIndex; + index_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(index_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg3.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + m_arguments.push_back(arg3); + } + + ~CommandObjectSettingsInsertBefore() override = default; + + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + + return matches.GetSize(); + } protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - Args cmd_args(command); - const size_t argc = cmd_args.GetArgumentCount (); - - if (argc < 3) - { - result.AppendError ("'settings insert-before' takes more arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings insert-before' command requires a valid variable name; No value supplied"); - result.SetStatus (eReturnStatusFailed); - return false; - } + Args cmd_args(command); + const size_t argc = cmd_args.GetArgumentCount(); - // Split the raw command into var_name, index_value, and value triple. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - - Error error(m_interpreter.GetDebugger().SetPropertyValue (&m_exe_ctx, - eVarSetOperationInsertBefore, - var_name, - var_value_cstr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (argc < 3) { + result.AppendError("'settings insert-before' takes more arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError("'settings insert-before' command requires a valid " + "variable name; No value supplied"); + result.SetStatus(eReturnStatusFailed); + return false; } + + // Split the raw command into var_name, index_value, and value triple. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, true, false); + + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationInsertBefore, var_name, var_value_cstr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingInsertAfter //------------------------------------------------------------------------- -class CommandObjectSettingsInsertAfter : public CommandObjectRaw -{ +class CommandObjectSettingsInsertAfter : public CommandObjectRaw { public: - CommandObjectSettingsInsertAfter(CommandInterpreter &interpreter) - : CommandObjectRaw( - interpreter, "settings insert-after", - "Insert one or more values into a debugger array settings after the specified element index.", nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentEntry arg3; - CommandArgumentData var_name_arg; - CommandArgumentData index_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first (variant of this arg. - index_arg.arg_type = eArgTypeSettingIndex; - index_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (index_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg3.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - m_arguments.push_back (arg3); - } + CommandObjectSettingsInsertAfter(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings insert-after", + "Insert one or more values into a debugger array " + "settings after the specified element index.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentEntry arg3; + CommandArgumentData var_name_arg; + CommandArgumentData index_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first (variant of this arg. + index_arg.arg_type = eArgTypeSettingIndex; + index_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(index_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg3.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + m_arguments.push_back(arg3); + } + + ~CommandObjectSettingsInsertAfter() override = default; + + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + + return matches.GetSize(); + } - ~CommandObjectSettingsInsertAfter() override = default; - - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - - return matches.GetSize(); - } - protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - Args cmd_args(command); - const size_t argc = cmd_args.GetArgumentCount (); - - if (argc < 3) - { - result.AppendError ("'settings insert-after' takes more arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings insert-after' command requires a valid variable name; No value supplied"); - result.SetStatus (eReturnStatusFailed); - return false; - } + Args cmd_args(command); + const size_t argc = cmd_args.GetArgumentCount(); - // Split the raw command into var_name, index_value, and value triple. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - - Error error(m_interpreter.GetDebugger().SetPropertyValue (&m_exe_ctx, - eVarSetOperationInsertAfter, - var_name, - var_value_cstr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (argc < 3) { + result.AppendError("'settings insert-after' takes more arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError("'settings insert-after' command requires a valid " + "variable name; No value supplied"); + result.SetStatus(eReturnStatusFailed); + return false; } + + // Split the raw command into var_name, index_value, and value triple. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, true, false); + + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationInsertAfter, var_name, var_value_cstr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsAppend //------------------------------------------------------------------------- -class CommandObjectSettingsAppend : public CommandObjectRaw -{ +class CommandObjectSettingsAppend : public CommandObjectRaw { public: - CommandObjectSettingsAppend(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "settings append", - "Append one or more values to a debugger array, dictionary, or string setting.", nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData var_name_arg; - CommandArgumentData value_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg1.push_back (var_name_arg); - - // Define the first (and only) variant of this arg. - value_arg.arg_type = eArgTypeValue; - value_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg2.push_back (value_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - } - - ~CommandObjectSettingsAppend() override = default; - - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - - return matches.GetSize(); - } + CommandObjectSettingsAppend(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "settings append", + "Append one or more values to a debugger array, " + "dictionary, or string setting.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData var_name_arg; + CommandArgumentData value_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg1.push_back(var_name_arg); + + // Define the first (and only) variant of this arg. + value_arg.arg_type = eArgTypeValue; + value_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg2.push_back(value_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectSettingsAppend() override = default; + + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + + return matches.GetSize(); + } protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); - const size_t argc = cmd_args.GetArgumentCount (); - - if (argc < 2) - { - result.AppendError ("'settings append' takes more arguments"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - const char *var_name = cmd_args.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings append' command requires a valid variable name; No value supplied"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + Args cmd_args(command); + const size_t argc = cmd_args.GetArgumentCount(); + + if (argc < 2) { + result.AppendError("'settings append' takes more arguments"); + result.SetStatus(eReturnStatusFailed); + return false; + } - // Do not perform cmd_args.Shift() since StringRef is manipulating the - // raw character string later on. - - // Split the raw command into var_name and value pair. - llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); - const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - - Error error(m_interpreter.GetDebugger().SetPropertyValue (&m_exe_ctx, - eVarSetOperationAppend, - var_name, - var_value_cstr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } + const char *var_name = cmd_args.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError("'settings append' command requires a valid variable " + "name; No value supplied"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + // Do not perform cmd_args.Shift() since StringRef is manipulating the + // raw character string later on. + + // Split the raw command into var_name and value pair. + llvm::StringRef raw_str(command); + std::string var_value_string = raw_str.split(var_name).second.str(); + const char *var_value_cstr = + Args::StripSpaces(var_value_string, true, true, false); + + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationAppend, var_name, var_value_cstr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectSettingsClear //------------------------------------------------------------------------- -class CommandObjectSettingsClear : public CommandObjectParsed -{ +class CommandObjectSettingsClear : public CommandObjectParsed { public: - CommandObjectSettingsClear(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "settings clear", "Clear a debugger setting array, dictionary, or string.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData var_name_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeSettingVariableName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (var_name_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectSettingsClear() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex (cursor_index), cursor_char_position); - - // Attempting to complete variable name - if (cursor_index < 2) - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSettingsNameCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - - return matches.GetSize(); - } + CommandObjectSettingsClear(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "settings clear", + "Clear a debugger setting array, dictionary, or string.", nullptr) { + CommandArgumentEntry arg; + CommandArgumentData var_name_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeSettingVariableName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(var_name_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectSettingsClear() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index), + cursor_char_position); + + // Attempting to complete variable name + if (cursor_index < 2) + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSettingsNameCompletion, + completion_str.c_str(), match_start_point, max_return_elements, + nullptr, word_complete, matches); + + return matches.GetSize(); + } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - result.SetStatus (eReturnStatusSuccessFinishNoResult); - const size_t argc = command.GetArgumentCount (); - - if (argc != 1) - { - result.AppendError ("'settings clear' takes exactly one argument"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + const size_t argc = command.GetArgumentCount(); + + if (argc != 1) { + result.AppendError("'settings clear' takes exactly one argument"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const char *var_name = command.GetArgumentAtIndex (0); - if ((var_name == nullptr) || (var_name[0] == '\0')) - { - result.AppendError ("'settings clear' command requires a valid variable name; No value supplied"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - Error error(m_interpreter.GetDebugger().SetPropertyValue(&m_exe_ctx, - eVarSetOperationClear, - var_name, - nullptr)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } + const char *var_name = command.GetArgumentAtIndex(0); + if ((var_name == nullptr) || (var_name[0] == '\0')) { + result.AppendError("'settings clear' command requires a valid variable " + "name; No value supplied"); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + Error error(m_interpreter.GetDebugger().SetPropertyValue( + &m_exe_ctx, eVarSetOperationClear, var_name, nullptr)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectMultiwordSettings //------------------------------------------------------------------------- -CommandObjectMultiwordSettings::CommandObjectMultiwordSettings(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "settings", "Commands for managing LLDB settings.", - "settings []") -{ - LoadSubCommand ("set", CommandObjectSP (new CommandObjectSettingsSet (interpreter))); - LoadSubCommand ("show", CommandObjectSP (new CommandObjectSettingsShow (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectSettingsList (interpreter))); - LoadSubCommand ("remove", CommandObjectSP (new CommandObjectSettingsRemove (interpreter))); - LoadSubCommand ("replace", CommandObjectSP (new CommandObjectSettingsReplace (interpreter))); - LoadSubCommand ("insert-before", CommandObjectSP (new CommandObjectSettingsInsertBefore (interpreter))); - LoadSubCommand ("insert-after", CommandObjectSP (new CommandObjectSettingsInsertAfter (interpreter))); - LoadSubCommand ("append", CommandObjectSP (new CommandObjectSettingsAppend (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectSettingsClear (interpreter))); +CommandObjectMultiwordSettings::CommandObjectMultiwordSettings( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "settings", + "Commands for managing LLDB settings.", + "settings []") { + LoadSubCommand("set", + CommandObjectSP(new CommandObjectSettingsSet(interpreter))); + LoadSubCommand("show", + CommandObjectSP(new CommandObjectSettingsShow(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectSettingsList(interpreter))); + LoadSubCommand("remove", + CommandObjectSP(new CommandObjectSettingsRemove(interpreter))); + LoadSubCommand("replace", CommandObjectSP( + new CommandObjectSettingsReplace(interpreter))); + LoadSubCommand( + "insert-before", + CommandObjectSP(new CommandObjectSettingsInsertBefore(interpreter))); + LoadSubCommand( + "insert-after", + CommandObjectSP(new CommandObjectSettingsInsertAfter(interpreter))); + LoadSubCommand("append", + CommandObjectSP(new CommandObjectSettingsAppend(interpreter))); + LoadSubCommand("clear", + CommandObjectSP(new CommandObjectSettingsClear(interpreter))); } CommandObjectMultiwordSettings::~CommandObjectMultiwordSettings() = default; diff --git a/lldb/source/Commands/CommandObjectSettings.h b/lldb/source/Commands/CommandObjectSettings.h index 93ee91981c1..3376cccd179 100644 --- a/lldb/source/Commands/CommandObjectSettings.h +++ b/lldb/source/Commands/CommandObjectSettings.h @@ -18,20 +18,17 @@ #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/Options.h" - namespace lldb_private { //------------------------------------------------------------------------- // CommandObjectMultiwordSettings //------------------------------------------------------------------------- -class CommandObjectMultiwordSettings : public CommandObjectMultiword -{ +class CommandObjectMultiwordSettings : public CommandObjectMultiword { public: + CommandObjectMultiwordSettings(CommandInterpreter &interpreter); - CommandObjectMultiwordSettings (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordSettings() override; + ~CommandObjectMultiwordSettings() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectSource.cpp b/lldb/source/Commands/CommandObjectSource.cpp index d35cba42599..6085168c8da 100644 --- a/lldb/source/Commands/CommandObjectSource.cpp +++ b/lldb/source/Commands/CommandObjectSource.cpp @@ -18,10 +18,12 @@ #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/SourceManager.h" -#include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Host/FileSpec.h" #include "lldb/Host/StringConvert.h" +#include "lldb/Interpreter/CommandCompletions.h" +#include "lldb/Interpreter/CommandInterpreter.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Function.h" #include "lldb/Symbol/Symbol.h" @@ -29,8 +31,6 @@ #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/TargetList.h" -#include "lldb/Interpreter/CommandCompletions.h" -#include "lldb/Interpreter/Options.h" using namespace lldb; using namespace lldb_private; @@ -40,668 +40,617 @@ using namespace lldb_private; // CommandObjectSourceInfo - debug line entries dumping command //---------------------------------------------------------------------- -class CommandObjectSourceInfo : public CommandObjectParsed -{ - class CommandOptions : public Options - { - public: - CommandOptions() : Options() {} - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_option_table[option_idx].short_option; - switch (short_option) - { - case 'l': - start_line = StringConvert::ToUInt32(option_arg, 0); - if (start_line == 0) - error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg); - break; - - case 'e': - end_line = StringConvert::ToUInt32(option_arg, 0); - if (end_line == 0) - error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg); - break; - - case 'c': - num_lines = StringConvert::ToUInt32(option_arg, 0); - if (num_lines == 0) - error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg); - break; - - case 'f': - file_name = option_arg; - break; - - case 'n': - symbol_name = option_arg; - break; - - case 'a': - { - address = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - } - break; - case 's': - modules.push_back(std::string(option_arg)); - break; - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } - - return error; - } +class CommandObjectSourceInfo : public CommandObjectParsed { + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_option_table[option_idx].short_option; + switch (short_option) { + case 'l': + start_line = StringConvert::ToUInt32(option_arg, 0); + if (start_line == 0) + error.SetErrorStringWithFormat("invalid line number: '%s'", + option_arg); + break; + + case 'e': + end_line = StringConvert::ToUInt32(option_arg, 0); + if (end_line == 0) + error.SetErrorStringWithFormat("invalid line number: '%s'", + option_arg); + break; + + case 'c': + num_lines = StringConvert::ToUInt32(option_arg, 0); + if (num_lines == 0) + error.SetErrorStringWithFormat("invalid line count: '%s'", + option_arg); + break; + + case 'f': + file_name = option_arg; + break; + + case 'n': + symbol_name = option_arg; + break; + + case 'a': { + address = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + } break; + case 's': + modules.push_back(std::string(option_arg)); + break; + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } + + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - file_spec.Clear(); - file_name.clear(); - symbol_name.clear(); - address = LLDB_INVALID_ADDRESS; - start_line = 0; - end_line = 0; - num_lines = 0; - modules.clear(); - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + file_spec.Clear(); + file_name.clear(); + symbol_name.clear(); + address = LLDB_INVALID_ADDRESS; + start_line = 0; + end_line = 0; + num_lines = 0; + modules.clear(); + } - const OptionDefinition * - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. - FileSpec file_spec; - std::string file_name; - std::string symbol_name; - lldb::addr_t address; - uint32_t start_line; - uint32_t end_line; - uint32_t num_lines; - STLStringArray modules; - }; + // Instance variables to hold the values for command options. + FileSpec file_spec; + std::string file_name; + std::string symbol_name; + lldb::addr_t address; + uint32_t start_line; + uint32_t end_line; + uint32_t num_lines; + STLStringArray modules; + }; public: - CommandObjectSourceInfo(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "source info", "Display source line information for the current target " - "process. Defaults to instruction pointer in current stack " - "frame.", - nullptr, eCommandRequiresTarget), - m_options() - { - } + CommandObjectSourceInfo(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "source info", + "Display source line information for the current target " + "process. Defaults to instruction pointer in current stack " + "frame.", + nullptr, eCommandRequiresTarget), + m_options() {} - ~CommandObjectSourceInfo() override = default; + ~CommandObjectSourceInfo() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - // Dump the line entries in each symbol context. - // Return the number of entries found. - // If module_list is set, only dump lines contained in one of the modules. - // If file_spec is set, only dump lines in the file. - // If the start_line option was specified, don't print lines less than start_line. - // If the end_line option was specified, don't print lines greater than end_line. - // If the num_lines option was specified, dont print more than num_lines entries. - uint32_t - DumpLinesInSymbolContexts (Stream &strm, const SymbolContextList &sc_list, - const ModuleList &module_list, const FileSpec &file_spec) - { - uint32_t start_line = m_options.start_line; - uint32_t end_line = m_options.end_line; - uint32_t num_lines = m_options.num_lines; - Target *target = m_exe_ctx.GetTargetPtr(); - - uint32_t num_matches = 0; - bool has_path = false; - if (file_spec) - { - assert(file_spec.GetFilename().AsCString()); - has_path = (file_spec.GetDirectory().AsCString() != nullptr); - } - - // Dump all the line entries for the file in the list. - ConstString last_module_file_name; - uint32_t num_scs = sc_list.GetSize(); - for (uint32_t i = 0; i < num_scs; ++i) - { - SymbolContext sc; - sc_list.GetContextAtIndex(i, sc); - if (sc.comp_unit) - { - Module *module = sc.module_sp.get(); - CompileUnit *cu = sc.comp_unit; - const LineEntry &line_entry = sc.line_entry; - assert(module && cu); - - // Are we looking for specific modules, files or lines? - if (module_list.GetSize() && module_list.GetIndexForModule(module) == LLDB_INVALID_INDEX32) - continue; - if (file_spec && !lldb_private::FileSpec::Equal(file_spec, line_entry.file, has_path)) - continue; - if (start_line > 0 && line_entry.line < start_line) - continue; - if (end_line > 0 && line_entry.line > end_line) - continue; - if (num_lines > 0 && num_matches > num_lines) - continue; - - // Print a new header if the module changed. - const ConstString &module_file_name = module->GetFileSpec().GetFilename(); - assert(module_file_name); - if (module_file_name != last_module_file_name) - { - if (num_matches > 0) - strm << "\n\n"; - strm << "Lines found in module `" << module_file_name << "\n"; - } - // Dump the line entry. - line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, - target, /*show_address_only=*/false); - strm << "\n"; - last_module_file_name = module_file_name; - num_matches++; - } - } - return num_matches; + // Dump the line entries in each symbol context. + // Return the number of entries found. + // If module_list is set, only dump lines contained in one of the modules. + // If file_spec is set, only dump lines in the file. + // If the start_line option was specified, don't print lines less than + // start_line. + // If the end_line option was specified, don't print lines greater than + // end_line. + // If the num_lines option was specified, dont print more than num_lines + // entries. + uint32_t DumpLinesInSymbolContexts(Stream &strm, + const SymbolContextList &sc_list, + const ModuleList &module_list, + const FileSpec &file_spec) { + uint32_t start_line = m_options.start_line; + uint32_t end_line = m_options.end_line; + uint32_t num_lines = m_options.num_lines; + Target *target = m_exe_ctx.GetTargetPtr(); + + uint32_t num_matches = 0; + bool has_path = false; + if (file_spec) { + assert(file_spec.GetFilename().AsCString()); + has_path = (file_spec.GetDirectory().AsCString() != nullptr); } - - // Dump the requested line entries for the file in the compilation unit. - // Return the number of entries found. - // If module_list is set, only dump lines contained in one of the modules. - // If the start_line option was specified, don't print lines less than start_line. - // If the end_line option was specified, don't print lines greater than end_line. - // If the num_lines option was specified, dont print more than num_lines entries. - uint32_t - DumpFileLinesInCompUnit (Stream &strm, Module *module, CompileUnit *cu, const FileSpec &file_spec) - { - uint32_t start_line = m_options.start_line; - uint32_t end_line = m_options.end_line; - uint32_t num_lines = m_options.num_lines; - Target *target = m_exe_ctx.GetTargetPtr(); - - uint32_t num_matches = 0; - assert(module); - if (cu) - { - assert(file_spec.GetFilename().AsCString()); - bool has_path = (file_spec.GetDirectory().AsCString() != nullptr); - const FileSpecList &cu_file_list = cu->GetSupportFiles(); - size_t file_idx = cu_file_list.FindFileIndex(0, file_spec, has_path); - if (file_idx != UINT32_MAX) - { - // Update the file to how it appears in the CU. - const FileSpec &cu_file_spec = cu_file_list.GetFileSpecAtIndex(file_idx); - - // Dump all matching lines at or above start_line for the file in the CU. - const ConstString &file_spec_name = file_spec.GetFilename(); - const ConstString &module_file_name = module->GetFileSpec().GetFilename(); - bool cu_header_printed = false; - uint32_t line = start_line; - while (true) - { - LineEntry line_entry; - - // Find the lowest index of a line entry with a line equal to - // or higher than 'line'. - uint32_t start_idx = 0; - start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, - /*exact=*/false, &line_entry); - if (start_idx == UINT32_MAX) - // No more line entries for our file in this CU. - break; - - if (end_line > 0 && line_entry.line > end_line) - break; - - // Loop through to find any other entries for this line, dumping each. - line = line_entry.line; - do - { - num_matches++; - if (num_lines > 0 && num_matches > num_lines) - break; - assert(lldb_private::FileSpec::Equal(cu_file_spec, line_entry.file, has_path)); - if (!cu_header_printed) - { - if (num_matches > 0) - strm << "\n\n"; - strm << "Lines found for file " << file_spec_name - << " in compilation unit " << cu->GetFilename() - << " in `" << module_file_name << "\n"; - cu_header_printed = true; - } - line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, - target, /*show_address_only=*/false); - strm << "\n"; - - // Anymore after this one? - start_idx++; - start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, - /*exact=*/true, &line_entry); - } while (start_idx != UINT32_MAX); - - // Try the next higher line, starting over at start_idx 0. - line++; - } - } + + // Dump all the line entries for the file in the list. + ConstString last_module_file_name; + uint32_t num_scs = sc_list.GetSize(); + for (uint32_t i = 0; i < num_scs; ++i) { + SymbolContext sc; + sc_list.GetContextAtIndex(i, sc); + if (sc.comp_unit) { + Module *module = sc.module_sp.get(); + CompileUnit *cu = sc.comp_unit; + const LineEntry &line_entry = sc.line_entry; + assert(module && cu); + + // Are we looking for specific modules, files or lines? + if (module_list.GetSize() && + module_list.GetIndexForModule(module) == LLDB_INVALID_INDEX32) + continue; + if (file_spec && + !lldb_private::FileSpec::Equal(file_spec, line_entry.file, + has_path)) + continue; + if (start_line > 0 && line_entry.line < start_line) + continue; + if (end_line > 0 && line_entry.line > end_line) + continue; + if (num_lines > 0 && num_matches > num_lines) + continue; + + // Print a new header if the module changed. + const ConstString &module_file_name = + module->GetFileSpec().GetFilename(); + assert(module_file_name); + if (module_file_name != last_module_file_name) { + if (num_matches > 0) + strm << "\n\n"; + strm << "Lines found in module `" << module_file_name << "\n"; } - return num_matches; + // Dump the line entry. + line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, + target, /*show_address_only=*/false); + strm << "\n"; + last_module_file_name = module_file_name; + num_matches++; + } } - - // Dump the requested line entries for the file in the module. - // Return the number of entries found. - // If module_list is set, only dump lines contained in one of the modules. - // If the start_line option was specified, don't print lines less than start_line. - // If the end_line option was specified, don't print lines greater than end_line. - // If the num_lines option was specified, dont print more than num_lines entries. - uint32_t - DumpFileLinesInModule (Stream &strm, Module *module, const FileSpec &file_spec) - { - uint32_t num_matches = 0; - if (module) - { - // Look through all the compilation units (CUs) in this module for ones that - // contain lines of code from this source file. - for (size_t i = 0; i < module->GetNumCompileUnits(); i++) - { - // Look for a matching source file in this CU. - CompUnitSP cu_sp(module->GetCompileUnitAtIndex(i)); - if (cu_sp) - { - num_matches += DumpFileLinesInCompUnit(strm, module, cu_sp.get(), file_spec); - } + return num_matches; + } + + // Dump the requested line entries for the file in the compilation unit. + // Return the number of entries found. + // If module_list is set, only dump lines contained in one of the modules. + // If the start_line option was specified, don't print lines less than + // start_line. + // If the end_line option was specified, don't print lines greater than + // end_line. + // If the num_lines option was specified, dont print more than num_lines + // entries. + uint32_t DumpFileLinesInCompUnit(Stream &strm, Module *module, + CompileUnit *cu, const FileSpec &file_spec) { + uint32_t start_line = m_options.start_line; + uint32_t end_line = m_options.end_line; + uint32_t num_lines = m_options.num_lines; + Target *target = m_exe_ctx.GetTargetPtr(); + + uint32_t num_matches = 0; + assert(module); + if (cu) { + assert(file_spec.GetFilename().AsCString()); + bool has_path = (file_spec.GetDirectory().AsCString() != nullptr); + const FileSpecList &cu_file_list = cu->GetSupportFiles(); + size_t file_idx = cu_file_list.FindFileIndex(0, file_spec, has_path); + if (file_idx != UINT32_MAX) { + // Update the file to how it appears in the CU. + const FileSpec &cu_file_spec = + cu_file_list.GetFileSpecAtIndex(file_idx); + + // Dump all matching lines at or above start_line for the file in the + // CU. + const ConstString &file_spec_name = file_spec.GetFilename(); + const ConstString &module_file_name = + module->GetFileSpec().GetFilename(); + bool cu_header_printed = false; + uint32_t line = start_line; + while (true) { + LineEntry line_entry; + + // Find the lowest index of a line entry with a line equal to + // or higher than 'line'. + uint32_t start_idx = 0; + start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, + /*exact=*/false, &line_entry); + if (start_idx == UINT32_MAX) + // No more line entries for our file in this CU. + break; + + if (end_line > 0 && line_entry.line > end_line) + break; + + // Loop through to find any other entries for this line, dumping each. + line = line_entry.line; + do { + num_matches++; + if (num_lines > 0 && num_matches > num_lines) + break; + assert(lldb_private::FileSpec::Equal(cu_file_spec, line_entry.file, + has_path)); + if (!cu_header_printed) { + if (num_matches > 0) + strm << "\n\n"; + strm << "Lines found for file " << file_spec_name + << " in compilation unit " << cu->GetFilename() << " in `" + << module_file_name << "\n"; + cu_header_printed = true; } + line_entry.GetDescription(&strm, lldb::eDescriptionLevelBrief, cu, + target, /*show_address_only=*/false); + strm << "\n"; + + // Anymore after this one? + start_idx++; + start_idx = cu->FindLineEntry(start_idx, line, &cu_file_spec, + /*exact=*/true, &line_entry); + } while (start_idx != UINT32_MAX); + + // Try the next higher line, starting over at start_idx 0. + line++; } - return num_matches; + } } - - // Given an address and a list of modules, append the symbol contexts of all line entries - // containing the address found in the modules and return the count of matches. If none - // is found, return an error in 'error_strm'. - size_t - GetSymbolContextsForAddress (const ModuleList &module_list, lldb::addr_t addr, - SymbolContextList &sc_list, StreamString &error_strm) - { - Address so_addr; - size_t num_matches = 0; - assert(module_list.GetSize() > 0); - Target *target = m_exe_ctx.GetTargetPtr(); - if (target->GetSectionLoadList().IsEmpty()) - { - // The target isn't loaded yet, we need to lookup the file address in - // all modules. Note: the module list option does not apply to addresses. - const size_t num_modules = module_list.GetSize(); - for (size_t i = 0; i < num_modules; ++i) - { - ModuleSP module_sp(module_list.GetModuleAtIndex(i)); - if (!module_sp) - continue; - if (module_sp->ResolveFileAddress(addr, so_addr)) - { - SymbolContext sc; - sc.Clear(true); - if (module_sp->ResolveSymbolContextForAddress(so_addr, eSymbolContextEverything, sc) & - eSymbolContextLineEntry) - { - sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); - ++num_matches; - } - } - } - if (num_matches == 0) - error_strm.Printf("Source information for file address 0x%" PRIx64 - " not found in any modules.\n", addr); - } - else - { - // The target has some things loaded, resolve this address to a - // compile unit + file + line and display - if (target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) - { - ModuleSP module_sp(so_addr.GetModule()); - // Check to make sure this module is in our list. - if (module_sp && - module_list.GetIndexForModule(module_sp.get()) != LLDB_INVALID_INDEX32) - { - SymbolContext sc; - sc.Clear(true); - if (module_sp->ResolveSymbolContextForAddress(so_addr, eSymbolContextEverything, sc) & - eSymbolContextLineEntry) - { - sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); - ++num_matches; - } - else - { - StreamString addr_strm; - so_addr.Dump(&addr_strm, nullptr, Address::DumpStyleModuleWithFileAddress); - error_strm.Printf("Address 0x%" PRIx64 " resolves to %s, but there is" - " no source information available for this address.\n", - addr, addr_strm.GetData()); - } - } - else - { - StreamString addr_strm; - so_addr.Dump(&addr_strm, nullptr, Address::DumpStyleModuleWithFileAddress); - error_strm.Printf("Address 0x%" PRIx64 " resolves to %s, but it cannot" - " be found in any modules.\n", - addr, addr_strm.GetData()); - } - } - else - error_strm.Printf("Unable to resolve address 0x%" PRIx64 ".\n", addr); + return num_matches; + } + + // Dump the requested line entries for the file in the module. + // Return the number of entries found. + // If module_list is set, only dump lines contained in one of the modules. + // If the start_line option was specified, don't print lines less than + // start_line. + // If the end_line option was specified, don't print lines greater than + // end_line. + // If the num_lines option was specified, dont print more than num_lines + // entries. + uint32_t DumpFileLinesInModule(Stream &strm, Module *module, + const FileSpec &file_spec) { + uint32_t num_matches = 0; + if (module) { + // Look through all the compilation units (CUs) in this module for ones + // that + // contain lines of code from this source file. + for (size_t i = 0; i < module->GetNumCompileUnits(); i++) { + // Look for a matching source file in this CU. + CompUnitSP cu_sp(module->GetCompileUnitAtIndex(i)); + if (cu_sp) { + num_matches += + DumpFileLinesInCompUnit(strm, module, cu_sp.get(), file_spec); } - return num_matches; + } } - - // Dump the line entries found in functions matching the name specified in the option. - bool - DumpLinesInFunctions (CommandReturnObject &result) - { - SymbolContextList sc_list_funcs; - ConstString name(m_options.symbol_name.c_str()); - SymbolContextList sc_list_lines; - Target *target = m_exe_ctx.GetTargetPtr(); - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - - // Note: module_list can't be const& because FindFunctionSymbols isn't const. - ModuleList module_list = (m_module_list.GetSize() > 0) ? - m_module_list : target->GetImages(); - size_t num_matches = module_list.FindFunctions(name, - eFunctionNameTypeAuto, - /*include_symbols=*/false, - /*include_inlines=*/true, - /*append=*/true, - sc_list_funcs); - if (!num_matches) - { - // If we didn't find any functions with that name, try searching for - // symbols that line up exactly with function addresses. - SymbolContextList sc_list_symbols; - size_t num_symbol_matches = module_list.FindFunctionSymbols(name, - eFunctionNameTypeAuto, - sc_list_symbols); - for (size_t i = 0; i < num_symbol_matches; i++) - { - SymbolContext sc; - sc_list_symbols.GetContextAtIndex(i, sc); - if (sc.symbol && sc.symbol->ValueIsAddress()) - { - const Address &base_address = sc.symbol->GetAddressRef(); - Function *function = base_address.CalculateSymbolContextFunction(); - if (function) - { - sc_list_funcs.Append(SymbolContext(function)); - num_matches++; - } - } - } - } - if (num_matches == 0) - { - result.AppendErrorWithFormat("Could not find function named \'%s\'.\n", - m_options.symbol_name.c_str()); - return false; + return num_matches; + } + + // Given an address and a list of modules, append the symbol contexts of all + // line entries + // containing the address found in the modules and return the count of + // matches. If none + // is found, return an error in 'error_strm'. + size_t GetSymbolContextsForAddress(const ModuleList &module_list, + lldb::addr_t addr, + SymbolContextList &sc_list, + StreamString &error_strm) { + Address so_addr; + size_t num_matches = 0; + assert(module_list.GetSize() > 0); + Target *target = m_exe_ctx.GetTargetPtr(); + if (target->GetSectionLoadList().IsEmpty()) { + // The target isn't loaded yet, we need to lookup the file address in + // all modules. Note: the module list option does not apply to addresses. + const size_t num_modules = module_list.GetSize(); + for (size_t i = 0; i < num_modules; ++i) { + ModuleSP module_sp(module_list.GetModuleAtIndex(i)); + if (!module_sp) + continue; + if (module_sp->ResolveFileAddress(addr, so_addr)) { + SymbolContext sc; + sc.Clear(true); + if (module_sp->ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, sc) & + eSymbolContextLineEntry) { + sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); + ++num_matches; + } } - for (size_t i = 0; i < num_matches; i++) - { - SymbolContext sc; - sc_list_funcs.GetContextAtIndex(i, sc); - bool context_found_for_symbol = false; - // Loop through all the ranges in the function. - AddressRange range; - for (uint32_t r = 0; - sc.GetAddressRange(eSymbolContextEverything, - r, - /*use_inline_block_range=*/true, - range); - ++r) - { - // Append the symbol contexts for each address in the range to sc_list_lines. - const Address &base_address = range.GetBaseAddress(); - const addr_t size = range.GetByteSize(); - lldb::addr_t start_addr = base_address.GetLoadAddress(target); - if (start_addr == LLDB_INVALID_ADDRESS) - start_addr = base_address.GetFileAddress(); - lldb::addr_t end_addr = start_addr + size; - for (lldb::addr_t addr = start_addr; addr < end_addr; addr += addr_byte_size) - { - StreamString error_strm; - if (!GetSymbolContextsForAddress(module_list, addr, sc_list_lines, error_strm)) - result.AppendWarningWithFormat("in symbol '%s': %s", - sc.GetFunctionName().AsCString(), - error_strm.GetData()); - else - context_found_for_symbol = true; - } - } - if (!context_found_for_symbol) - result.AppendWarningWithFormat("Unable to find line information" - " for matching symbol '%s'.\n", - sc.GetFunctionName().AsCString()); - } - if (sc_list_lines.GetSize() == 0) - { - result.AppendErrorWithFormat("No line information could be found" - " for any symbols matching '%s'.\n", - name.AsCString()); - return false; + } + if (num_matches == 0) + error_strm.Printf("Source information for file address 0x%" PRIx64 + " not found in any modules.\n", + addr); + } else { + // The target has some things loaded, resolve this address to a + // compile unit + file + line and display + if (target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) { + ModuleSP module_sp(so_addr.GetModule()); + // Check to make sure this module is in our list. + if (module_sp && + module_list.GetIndexForModule(module_sp.get()) != + LLDB_INVALID_INDEX32) { + SymbolContext sc; + sc.Clear(true); + if (module_sp->ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, sc) & + eSymbolContextLineEntry) { + sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/false); + ++num_matches; + } else { + StreamString addr_strm; + so_addr.Dump(&addr_strm, nullptr, + Address::DumpStyleModuleWithFileAddress); + error_strm.Printf( + "Address 0x%" PRIx64 " resolves to %s, but there is" + " no source information available for this address.\n", + addr, addr_strm.GetData()); + } + } else { + StreamString addr_strm; + so_addr.Dump(&addr_strm, nullptr, + Address::DumpStyleModuleWithFileAddress); + error_strm.Printf("Address 0x%" PRIx64 + " resolves to %s, but it cannot" + " be found in any modules.\n", + addr, addr_strm.GetData()); } - FileSpec file_spec; - if (!DumpLinesInSymbolContexts(result.GetOutputStream(), - sc_list_lines, module_list, file_spec)) - { - result.AppendErrorWithFormat("Unable to dump line information for symbol '%s'.\n", - name.AsCString()); - return false; - } - return true; + } else + error_strm.Printf("Unable to resolve address 0x%" PRIx64 ".\n", addr); } - - // Dump the line entries found for the address specified in the option. - bool - DumpLinesForAddress (CommandReturnObject &result) - { - Target *target = m_exe_ctx.GetTargetPtr(); - SymbolContextList sc_list; - - StreamString error_strm; - if (!GetSymbolContextsForAddress(target->GetImages(), m_options.address, sc_list, error_strm)) - { - result.AppendErrorWithFormat("%s.\n", error_strm.GetData()); - return false; + return num_matches; + } + + // Dump the line entries found in functions matching the name specified in the + // option. + bool DumpLinesInFunctions(CommandReturnObject &result) { + SymbolContextList sc_list_funcs; + ConstString name(m_options.symbol_name.c_str()); + SymbolContextList sc_list_lines; + Target *target = m_exe_ctx.GetTargetPtr(); + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + + // Note: module_list can't be const& because FindFunctionSymbols isn't + // const. + ModuleList module_list = + (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages(); + size_t num_matches = + module_list.FindFunctions(name, eFunctionNameTypeAuto, + /*include_symbols=*/false, + /*include_inlines=*/true, + /*append=*/true, sc_list_funcs); + if (!num_matches) { + // If we didn't find any functions with that name, try searching for + // symbols that line up exactly with function addresses. + SymbolContextList sc_list_symbols; + size_t num_symbol_matches = module_list.FindFunctionSymbols( + name, eFunctionNameTypeAuto, sc_list_symbols); + for (size_t i = 0; i < num_symbol_matches; i++) { + SymbolContext sc; + sc_list_symbols.GetContextAtIndex(i, sc); + if (sc.symbol && sc.symbol->ValueIsAddress()) { + const Address &base_address = sc.symbol->GetAddressRef(); + Function *function = base_address.CalculateSymbolContextFunction(); + if (function) { + sc_list_funcs.Append(SymbolContext(function)); + num_matches++; + } } - ModuleList module_list; - FileSpec file_spec; - if (!DumpLinesInSymbolContexts(result.GetOutputStream(), - sc_list, module_list, file_spec)) - { - result.AppendErrorWithFormat("No modules contain load address 0x%" PRIx64 ".\n", - m_options.address); - return false; + } + } + if (num_matches == 0) { + result.AppendErrorWithFormat("Could not find function named \'%s\'.\n", + m_options.symbol_name.c_str()); + return false; + } + for (size_t i = 0; i < num_matches; i++) { + SymbolContext sc; + sc_list_funcs.GetContextAtIndex(i, sc); + bool context_found_for_symbol = false; + // Loop through all the ranges in the function. + AddressRange range; + for (uint32_t r = 0; + sc.GetAddressRange(eSymbolContextEverything, r, + /*use_inline_block_range=*/true, range); + ++r) { + // Append the symbol contexts for each address in the range to + // sc_list_lines. + const Address &base_address = range.GetBaseAddress(); + const addr_t size = range.GetByteSize(); + lldb::addr_t start_addr = base_address.GetLoadAddress(target); + if (start_addr == LLDB_INVALID_ADDRESS) + start_addr = base_address.GetFileAddress(); + lldb::addr_t end_addr = start_addr + size; + for (lldb::addr_t addr = start_addr; addr < end_addr; + addr += addr_byte_size) { + StreamString error_strm; + if (!GetSymbolContextsForAddress(module_list, addr, sc_list_lines, + error_strm)) + result.AppendWarningWithFormat("in symbol '%s': %s", + sc.GetFunctionName().AsCString(), + error_strm.GetData()); + else + context_found_for_symbol = true; } - return true; + } + if (!context_found_for_symbol) + result.AppendWarningWithFormat("Unable to find line information" + " for matching symbol '%s'.\n", + sc.GetFunctionName().AsCString()); + } + if (sc_list_lines.GetSize() == 0) { + result.AppendErrorWithFormat("No line information could be found" + " for any symbols matching '%s'.\n", + name.AsCString()); + return false; } + FileSpec file_spec; + if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list_lines, + module_list, file_spec)) { + result.AppendErrorWithFormat( + "Unable to dump line information for symbol '%s'.\n", + name.AsCString()); + return false; + } + return true; + } + + // Dump the line entries found for the address specified in the option. + bool DumpLinesForAddress(CommandReturnObject &result) { + Target *target = m_exe_ctx.GetTargetPtr(); + SymbolContextList sc_list; + + StreamString error_strm; + if (!GetSymbolContextsForAddress(target->GetImages(), m_options.address, + sc_list, error_strm)) { + result.AppendErrorWithFormat("%s.\n", error_strm.GetData()); + return false; + } + ModuleList module_list; + FileSpec file_spec; + if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, + module_list, file_spec)) { + result.AppendErrorWithFormat("No modules contain load address 0x%" PRIx64 + ".\n", + m_options.address); + return false; + } + return true; + } + + // Dump the line entries found in the file specified in the option. + bool DumpLinesForFile(CommandReturnObject &result) { + FileSpec file_spec(m_options.file_name, false); + const char *filename = m_options.file_name.c_str(); + Target *target = m_exe_ctx.GetTargetPtr(); + const ModuleList &module_list = + (m_module_list.GetSize() > 0) ? m_module_list : target->GetImages(); + + bool displayed_something = false; + const size_t num_modules = module_list.GetSize(); + for (uint32_t i = 0; i < num_modules; ++i) { + // Dump lines for this module. + Module *module = module_list.GetModulePointerAtIndex(i); + assert(module); + if (DumpFileLinesInModule(result.GetOutputStream(), module, file_spec)) + displayed_something = true; + } + if (!displayed_something) { + result.AppendErrorWithFormat("No source filenames matched '%s'.\n", + filename); + return false; + } + return true; + } + + // Dump the line entries for the current frame. + bool DumpLinesForFrame(CommandReturnObject &result) { + StackFrame *cur_frame = m_exe_ctx.GetFramePtr(); + if (cur_frame == nullptr) { + result.AppendError( + "No selected frame to use to find the default source."); + return false; + } else if (!cur_frame->HasDebugInformation()) { + result.AppendError("No debug info for the selected frame."); + return false; + } else { + const SymbolContext &sc = + cur_frame->GetSymbolContext(eSymbolContextLineEntry); + SymbolContextList sc_list; + sc_list.Append(sc); + ModuleList module_list; + FileSpec file_spec; + if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, + module_list, file_spec)) { + result.AppendError( + "No source line info available for the selected frame."); + return false; + } + } + return true; + } - // Dump the line entries found in the file specified in the option. - bool - DumpLinesForFile (CommandReturnObject &result) - { - FileSpec file_spec(m_options.file_name, false); - const char *filename = m_options.file_name.c_str(); - Target *target = m_exe_ctx.GetTargetPtr(); - const ModuleList &module_list = (m_module_list.GetSize() > 0) ? - m_module_list : target->GetImages(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); - bool displayed_something = false; - const size_t num_modules = module_list.GetSize(); - for (uint32_t i = 0; i < num_modules; ++i) - { - // Dump lines for this module. - Module *module = module_list.GetModulePointerAtIndex(i); - assert(module); - if (DumpFileLinesInModule(result.GetOutputStream(), module, file_spec)) - displayed_something = true; - } - if (!displayed_something) - { - result.AppendErrorWithFormat("No source filenames matched '%s'.\n", filename); - return false; - } - return true; + if (argc != 0) { + result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", + GetCommandName()); + result.SetStatus(eReturnStatusFailed); + return false; } - // Dump the line entries for the current frame. - bool - DumpLinesForFrame (CommandReturnObject &result) - { - StackFrame *cur_frame = m_exe_ctx.GetFramePtr(); - if (cur_frame == nullptr) - { - result.AppendError("No selected frame to use to find the default source."); - return false; - } - else if (!cur_frame->HasDebugInformation()) - { - result.AppendError("No debug info for the selected frame."); - return false; - } - else - { - const SymbolContext &sc = cur_frame->GetSymbolContext(eSymbolContextLineEntry); - SymbolContextList sc_list; - sc_list.Append(sc); - ModuleList module_list; - FileSpec file_spec; - if (!DumpLinesInSymbolContexts(result.GetOutputStream(), sc_list, module_list, file_spec)) - { - result.AppendError("No source line info available for the selected frame."); - return false; - } - } - return true; + Target *target = m_exe_ctx.GetTargetPtr(); + if (target == nullptr) { + target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command."); + result.SetStatus(eReturnStatusFailed); + return false; + } } - bool - DoExecute (Args &command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc != 0) - { - result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", - GetCommandName()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - Target *target = m_exe_ctx.GetTargetPtr(); - if (target == nullptr) - { - target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError("invalid target, create a debug target using the " - "'target create' command."); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - - // Collect the list of modules to search. - m_module_list.Clear(); - if (!m_options.modules.empty()) - { - for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) - { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); - if (module_file_spec) - { - ModuleSpec module_spec(module_file_spec); - if (target->GetImages().FindModules(module_spec, m_module_list) == 0) - result.AppendWarningWithFormat("No module found for '%s'.\n", - m_options.modules[i].c_str()); - } - } - if (!m_module_list.GetSize()) - { - result.AppendError("No modules match the input."); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else if (target->GetImages().GetSize() == 0) - { - result.AppendError("The target has no associated executable images."); - result.SetStatus(eReturnStatusFailed); - return false; + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + + // Collect the list of modules to search. + m_module_list.Clear(); + if (!m_options.modules.empty()) { + for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { + FileSpec module_file_spec(m_options.modules[i].c_str(), false); + if (module_file_spec) { + ModuleSpec module_spec(module_file_spec); + if (target->GetImages().FindModules(module_spec, m_module_list) == 0) + result.AppendWarningWithFormat("No module found for '%s'.\n", + m_options.modules[i].c_str()); } + } + if (!m_module_list.GetSize()) { + result.AppendError("No modules match the input."); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else if (target->GetImages().GetSize() == 0) { + result.AppendError("The target has no associated executable images."); + result.SetStatus(eReturnStatusFailed); + return false; + } - // Check the arguments to see what lines we should dump. - if (!m_options.symbol_name.empty()) - { - // Print lines for symbol. - if (DumpLinesInFunctions(result)) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - result.SetStatus(eReturnStatusFailed); - } - else if (m_options.address != LLDB_INVALID_ADDRESS) - { - // Print lines for an address. - if (DumpLinesForAddress(result)) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - result.SetStatus(eReturnStatusFailed); - } - else if (!m_options.file_name.empty()) - { - // Dump lines for a file. - if (DumpLinesForFile(result)) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - result.SetStatus(eReturnStatusFailed); - } - else - { - // Dump the line for the current frame. - if (DumpLinesForFrame(result)) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - result.SetStatus(eReturnStatusFailed); - } - return result.Succeeded(); + // Check the arguments to see what lines we should dump. + if (!m_options.symbol_name.empty()) { + // Print lines for symbol. + if (DumpLinesInFunctions(result)) + result.SetStatus(eReturnStatusSuccessFinishResult); + else + result.SetStatus(eReturnStatusFailed); + } else if (m_options.address != LLDB_INVALID_ADDRESS) { + // Print lines for an address. + if (DumpLinesForAddress(result)) + result.SetStatus(eReturnStatusSuccessFinishResult); + else + result.SetStatus(eReturnStatusFailed); + } else if (!m_options.file_name.empty()) { + // Dump lines for a file. + if (DumpLinesForFile(result)) + result.SetStatus(eReturnStatusSuccessFinishResult); + else + result.SetStatus(eReturnStatusFailed); + } else { + // Dump the line for the current frame. + if (DumpLinesForFrame(result)) + result.SetStatus(eReturnStatusSuccessFinishResult); + else + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - CommandOptions m_options; - ModuleList m_module_list; + CommandOptions m_options; + ModuleList m_module_list; }; OptionDefinition CommandObjectSourceInfo::CommandOptions::g_option_table[] = { - // clang-format off + // clang-format off {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "The number of line entries to display."}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source in the given module or shared library (can be specified more than once)."}, {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "The file from which to display source."}, @@ -710,7 +659,7 @@ OptionDefinition CommandObjectSourceInfo::CommandOptions::g_option_table[] = { {LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSymbolCompletion, eArgTypeSymbol, "The name of a function whose source to display."}, {LLDB_OPT_SET_3, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Lookup the address and display the source information for the corresponding file and line."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectSourceList @@ -718,748 +667,638 @@ OptionDefinition CommandObjectSourceInfo::CommandOptions::g_option_table[] = { // CommandObjectSourceList //------------------------------------------------------------------------- -class CommandObjectSourceList : public CommandObjectParsed -{ - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } +class CommandObjectSourceList : public CommandObjectParsed { + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_option_table[option_idx].short_option; + switch (short_option) { + case 'l': + start_line = StringConvert::ToUInt32(option_arg, 0); + if (start_line == 0) + error.SetErrorStringWithFormat("invalid line number: '%s'", + option_arg); + break; + + case 'c': + num_lines = StringConvert::ToUInt32(option_arg, 0); + if (num_lines == 0) + error.SetErrorStringWithFormat("invalid line count: '%s'", + option_arg); + break; + + case 'f': + file_name = option_arg; + break; + + case 'n': + symbol_name = option_arg; + break; + + case 'a': { + address = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + } break; + case 's': + modules.push_back(std::string(option_arg)); + break; + + case 'b': + show_bp_locs = true; + break; + case 'r': + reverse = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized short option '%c'", + short_option); + break; + } + + return error; + } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_option_table[option_idx].short_option; - switch (short_option) - { - case 'l': - start_line = StringConvert::ToUInt32 (option_arg, 0); - if (start_line == 0) - error.SetErrorStringWithFormat("invalid line number: '%s'", option_arg); - break; - - case 'c': - num_lines = StringConvert::ToUInt32 (option_arg, 0); - if (num_lines == 0) - error.SetErrorStringWithFormat("invalid line count: '%s'", option_arg); - break; - - case 'f': - file_name = option_arg; - break; - - case 'n': - symbol_name = option_arg; - break; - - case 'a': - { - address = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - } - break; - case 's': - modules.push_back (std::string (option_arg)); - break; - - case 'b': - show_bp_locs = true; - break; - case 'r': - reverse = true; - break; - default: - error.SetErrorStringWithFormat("unrecognized short option '%c'", short_option); - break; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + file_spec.Clear(); + file_name.clear(); + symbol_name.clear(); + address = LLDB_INVALID_ADDRESS; + start_line = 0; + num_lines = 0; + show_bp_locs = false; + reverse = false; + modules.clear(); + } - return error; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - file_spec.Clear(); - file_name.clear(); - symbol_name.clear(); - address = LLDB_INVALID_ADDRESS; - start_line = 0; - num_lines = 0; - show_bp_locs = false; - reverse = false; - modules.clear(); - } + static OptionDefinition g_option_table[]; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + // Instance variables to hold the values for command options. + FileSpec file_spec; + std::string file_name; + std::string symbol_name; + lldb::addr_t address; + uint32_t start_line; + uint32_t num_lines; + STLStringArray modules; + bool show_bp_locs; + bool reverse; + }; - static OptionDefinition g_option_table[]; +public: + CommandObjectSourceList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "source list", + "Display source code for the current target " + "process as specified by options.", + nullptr, eCommandRequiresTarget), + m_options() {} + + ~CommandObjectSourceList() override = default; + + Options *GetOptions() override { return &m_options; } + + const char *GetRepeatCommand(Args ¤t_command_args, + uint32_t index) override { + // This is kind of gross, but the command hasn't been parsed yet so we can't + // look at the option + // values for this invocation... I have to scan the arguments directly. + size_t num_args = current_command_args.GetArgumentCount(); + bool is_reverse = false; + for (size_t i = 0; i < num_args; i++) { + const char *arg = current_command_args.GetArgumentAtIndex(i); + if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0)) { + is_reverse = true; + } + } + if (is_reverse) { + if (m_reverse_name.empty()) { + m_reverse_name = m_cmd_name; + m_reverse_name.append(" -r"); + } + return m_reverse_name.c_str(); + } else + return m_cmd_name.c_str(); + } - // Instance variables to hold the values for command options. - FileSpec file_spec; - std::string file_name; - std::string symbol_name; - lldb::addr_t address; - uint32_t start_line; - uint32_t num_lines; - STLStringArray modules; - bool show_bp_locs; - bool reverse; - }; +protected: + struct SourceInfo { + ConstString function; + LineEntry line_entry; -public: - CommandObjectSourceList(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "source list", - "Display source code for the current target process as specified by options.", nullptr, - eCommandRequiresTarget), - m_options() - { + SourceInfo(const ConstString &name, const LineEntry &line_entry) + : function(name), line_entry(line_entry) {} + + SourceInfo() : function(), line_entry() {} + + bool IsValid() const { return (bool)function && line_entry.IsValid(); } + + bool operator==(const SourceInfo &rhs) const { + return function == rhs.function && + line_entry.original_file == rhs.line_entry.original_file && + line_entry.line == rhs.line_entry.line; } - ~CommandObjectSourceList() override = default; + bool operator!=(const SourceInfo &rhs) const { + return function != rhs.function || + line_entry.original_file != rhs.line_entry.original_file || + line_entry.line != rhs.line_entry.line; + } - Options * - GetOptions () override - { - return &m_options; + bool operator<(const SourceInfo &rhs) const { + if (function.GetCString() < rhs.function.GetCString()) + return true; + if (line_entry.file.GetDirectory().GetCString() < + rhs.line_entry.file.GetDirectory().GetCString()) + return true; + if (line_entry.file.GetFilename().GetCString() < + rhs.line_entry.file.GetFilename().GetCString()) + return true; + if (line_entry.line < rhs.line_entry.line) + return true; + return false; } + }; - const char * - GetRepeatCommand (Args ¤t_command_args, uint32_t index) override - { - // This is kind of gross, but the command hasn't been parsed yet so we can't look at the option - // values for this invocation... I have to scan the arguments directly. - size_t num_args = current_command_args.GetArgumentCount(); - bool is_reverse = false; - for (size_t i = 0; i < num_args; i++) - { - const char *arg = current_command_args.GetArgumentAtIndex(i); - if (arg && (strcmp(arg, "-r") == 0 || strcmp(arg, "--reverse") == 0)) - { - is_reverse = true; - } - } - if (is_reverse) - { - if (m_reverse_name.empty()) - { - m_reverse_name = m_cmd_name; - m_reverse_name.append (" -r"); - } - return m_reverse_name.c_str(); - } - else - return m_cmd_name.c_str(); + size_t DisplayFunctionSource(const SymbolContext &sc, SourceInfo &source_info, + CommandReturnObject &result) { + if (!source_info.IsValid()) { + source_info.function = sc.GetFunctionName(); + source_info.line_entry = sc.GetFunctionStartLineEntry(); } -protected: - struct SourceInfo - { - ConstString function; - LineEntry line_entry; - - SourceInfo (const ConstString &name, const LineEntry &line_entry) : - function(name), - line_entry(line_entry) - { - } - - SourceInfo () : - function(), - line_entry() - { - } - - bool - IsValid () const - { - return (bool)function && line_entry.IsValid(); + if (sc.function) { + Target *target = m_exe_ctx.GetTargetPtr(); + + FileSpec start_file; + uint32_t start_line; + uint32_t end_line; + FileSpec end_file; + + if (sc.block == nullptr) { + // Not an inlined function + sc.function->GetStartLineSourceInfo(start_file, start_line); + if (start_line == 0) { + result.AppendErrorWithFormat("Could not find line information for " + "start of function: \"%s\".\n", + source_info.function.GetCString()); + result.SetStatus(eReturnStatusFailed); + return 0; } - - bool - operator == (const SourceInfo &rhs) const - { - return function == rhs.function && - line_entry.original_file == rhs.line_entry.original_file && - line_entry.line == rhs.line_entry.line; - } - - bool - operator != (const SourceInfo &rhs) const - { - return function != rhs.function || - line_entry.original_file != rhs.line_entry.original_file || - line_entry.line != rhs.line_entry.line; - } - - bool - operator < (const SourceInfo &rhs) const - { - if (function.GetCString() < rhs.function.GetCString()) - return true; - if (line_entry.file.GetDirectory().GetCString() < rhs.line_entry.file.GetDirectory().GetCString()) - return true; - if (line_entry.file.GetFilename().GetCString() < rhs.line_entry.file.GetFilename().GetCString()) - return true; - if (line_entry.line < rhs.line_entry.line) - return true; - return false; + sc.function->GetEndLineSourceInfo(end_file, end_line); + } else { + // We have an inlined function + start_file = source_info.line_entry.file; + start_line = source_info.line_entry.line; + end_line = start_line + m_options.num_lines; + } + + // This is a little hacky, but the first line table entry for a function + // points to the "{" that + // starts the function block. It would be nice to actually get the + // function + // declaration in there too. So back up a bit, but not further than what + // you're going to display. + uint32_t extra_lines; + if (m_options.num_lines >= 10) + extra_lines = 5; + else + extra_lines = m_options.num_lines / 2; + uint32_t line_no; + if (start_line <= extra_lines) + line_no = 1; + else + line_no = start_line - extra_lines; + + // For fun, if the function is shorter than the number of lines we're + // supposed to display, + // only display the function... + if (end_line != 0) { + if (m_options.num_lines > end_line - line_no) + m_options.num_lines = end_line - line_no + extra_lines; + } + + m_breakpoint_locations.Clear(); + + if (m_options.show_bp_locs) { + const bool show_inlines = true; + m_breakpoint_locations.Reset(start_file, 0, show_inlines); + SearchFilterForUnconstrainedSearches target_search_filter( + m_exe_ctx.GetTargetSP()); + target_search_filter.Search(m_breakpoint_locations); + } + + result.AppendMessageWithFormat("File: %s\n", + start_file.GetPath().c_str()); + return target->GetSourceManager().DisplaySourceLinesWithLineNumbers( + start_file, line_no, 0, m_options.num_lines, "", + &result.GetOutputStream(), GetBreakpointLocations()); + } else { + result.AppendErrorWithFormat( + "Could not find function info for: \"%s\".\n", + m_options.symbol_name.c_str()); + } + return 0; + } + + // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions + // "take a possibly empty vector of strings which are names of modules, and + // run the two search functions on the subset of the full module list that + // matches the strings in the input vector". If we wanted to put these + // somewhere, + // there should probably be a module-filter-list that can be passed to the + // various ModuleList::Find* calls, which would either be a vector of string + // names or a ModuleSpecList. + size_t FindMatchingFunctions(Target *target, const ConstString &name, + SymbolContextList &sc_list) { + // Displaying the source for a symbol: + bool include_inlines = true; + bool append = true; + bool include_symbols = false; + size_t num_matches = 0; + + if (m_options.num_lines == 0) + m_options.num_lines = 10; + + const size_t num_modules = m_options.modules.size(); + if (num_modules > 0) { + ModuleList matching_modules; + for (size_t i = 0; i < num_modules; ++i) { + FileSpec module_file_spec(m_options.modules[i].c_str(), false); + if (module_file_spec) { + ModuleSpec module_spec(module_file_spec); + matching_modules.Clear(); + target->GetImages().FindModules(module_spec, matching_modules); + num_matches += matching_modules.FindFunctions( + name, eFunctionNameTypeAuto, include_symbols, include_inlines, + append, sc_list); } - }; - - size_t - DisplayFunctionSource (const SymbolContext &sc, - SourceInfo &source_info, - CommandReturnObject &result) - { - if (!source_info.IsValid()) - { - source_info.function = sc.GetFunctionName(); - source_info.line_entry = sc.GetFunctionStartLineEntry(); + } + } else { + num_matches = target->GetImages().FindFunctions( + name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, + sc_list); + } + return num_matches; + } + + size_t FindMatchingFunctionSymbols(Target *target, const ConstString &name, + SymbolContextList &sc_list) { + size_t num_matches = 0; + const size_t num_modules = m_options.modules.size(); + if (num_modules > 0) { + ModuleList matching_modules; + for (size_t i = 0; i < num_modules; ++i) { + FileSpec module_file_spec(m_options.modules[i].c_str(), false); + if (module_file_spec) { + ModuleSpec module_spec(module_file_spec); + matching_modules.Clear(); + target->GetImages().FindModules(module_spec, matching_modules); + num_matches += matching_modules.FindFunctionSymbols( + name, eFunctionNameTypeAuto, sc_list); } - - if (sc.function) - { - Target *target = m_exe_ctx.GetTargetPtr(); - - FileSpec start_file; - uint32_t start_line; - uint32_t end_line; - FileSpec end_file; - - if (sc.block == nullptr) - { - // Not an inlined function - sc.function->GetStartLineSourceInfo (start_file, start_line); - if (start_line == 0) - { - result.AppendErrorWithFormat("Could not find line information for start of function: \"%s\".\n", source_info.function.GetCString()); - result.SetStatus (eReturnStatusFailed); - return 0; - } - sc.function->GetEndLineSourceInfo (end_file, end_line); - } - else - { - // We have an inlined function - start_file = source_info.line_entry.file; - start_line = source_info.line_entry.line; - end_line = start_line + m_options.num_lines; - } + } + } else { + num_matches = target->GetImages().FindFunctionSymbols( + name, eFunctionNameTypeAuto, sc_list); + } + return num_matches; + } - // This is a little hacky, but the first line table entry for a function points to the "{" that - // starts the function block. It would be nice to actually get the function - // declaration in there too. So back up a bit, but not further than what you're going to display. - uint32_t extra_lines; - if (m_options.num_lines >= 10) - extra_lines = 5; - else - extra_lines = m_options.num_lines/2; - uint32_t line_no; - if (start_line <= extra_lines) - line_no = 1; - else - line_no = start_line - extra_lines; - - // For fun, if the function is shorter than the number of lines we're supposed to display, - // only display the function... - if (end_line != 0) - { - if (m_options.num_lines > end_line - line_no) - m_options.num_lines = end_line - line_no + extra_lines; - } - - m_breakpoint_locations.Clear(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc != 0) { + result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", + GetCommandName()); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (m_options.show_bp_locs) - { - const bool show_inlines = true; - m_breakpoint_locations.Reset (start_file, 0, show_inlines); - SearchFilterForUnconstrainedSearches target_search_filter (m_exe_ctx.GetTargetSP()); - target_search_filter.Search (m_breakpoint_locations); + Target *target = m_exe_ctx.GetTargetPtr(); + + if (!m_options.symbol_name.empty()) { + SymbolContextList sc_list; + ConstString name(m_options.symbol_name.c_str()); + + // Displaying the source for a symbol. Search for function named name. + size_t num_matches = FindMatchingFunctions(target, name, sc_list); + if (!num_matches) { + // If we didn't find any functions with that name, try searching for + // symbols + // that line up exactly with function addresses. + SymbolContextList sc_list_symbols; + size_t num_symbol_matches = + FindMatchingFunctionSymbols(target, name, sc_list_symbols); + for (size_t i = 0; i < num_symbol_matches; i++) { + SymbolContext sc; + sc_list_symbols.GetContextAtIndex(i, sc); + if (sc.symbol && sc.symbol->ValueIsAddress()) { + const Address &base_address = sc.symbol->GetAddressRef(); + Function *function = base_address.CalculateSymbolContextFunction(); + if (function) { + sc_list.Append(SymbolContext(function)); + num_matches++; + break; } - - result.AppendMessageWithFormat("File: %s\n", start_file.GetPath().c_str()); - return target->GetSourceManager().DisplaySourceLinesWithLineNumbers (start_file, - line_no, - 0, - m_options.num_lines, - "", - &result.GetOutputStream(), - GetBreakpointLocations ()); - } - else - { - result.AppendErrorWithFormat("Could not find function info for: \"%s\".\n", m_options.symbol_name.c_str()); + } } - return 0; - } + } - // From Jim: The FindMatchingFunctions / FindMatchingFunctionSymbols functions - // "take a possibly empty vector of strings which are names of modules, and - // run the two search functions on the subset of the full module list that - // matches the strings in the input vector". If we wanted to put these somewhere, - // there should probably be a module-filter-list that can be passed to the - // various ModuleList::Find* calls, which would either be a vector of string - // names or a ModuleSpecList. - size_t FindMatchingFunctions (Target *target, const ConstString &name, SymbolContextList& sc_list) - { - // Displaying the source for a symbol: - bool include_inlines = true; - bool append = true; - bool include_symbols = false; - size_t num_matches = 0; - - if (m_options.num_lines == 0) - m_options.num_lines = 10; + if (num_matches == 0) { + result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", + m_options.symbol_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (num_matches > 1) { + std::set source_match_set; - const size_t num_modules = m_options.modules.size(); - if (num_modules > 0) - { - ModuleList matching_modules; - for (size_t i = 0; i < num_modules; ++i) - { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); - if (module_file_spec) - { - ModuleSpec module_spec (module_file_spec); - matching_modules.Clear(); - target->GetImages().FindModules (module_spec, matching_modules); - num_matches += matching_modules.FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list); - } + bool displayed_something = false; + for (size_t i = 0; i < num_matches; i++) { + SymbolContext sc; + sc_list.GetContextAtIndex(i, sc); + SourceInfo source_info(sc.GetFunctionName(), + sc.GetFunctionStartLineEntry()); + + if (source_info.IsValid()) { + if (source_match_set.find(source_info) == source_match_set.end()) { + source_match_set.insert(source_info); + if (DisplayFunctionSource(sc, source_info, result)) + displayed_something = true; } + } } + + if (displayed_something) + result.SetStatus(eReturnStatusSuccessFinishResult); else - { - num_matches = target->GetImages().FindFunctions (name, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list); + result.SetStatus(eReturnStatusFailed); + } else { + SymbolContext sc; + sc_list.GetContextAtIndex(0, sc); + SourceInfo source_info; + + if (DisplayFunctionSource(sc, source_info, result)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.SetStatus(eReturnStatusFailed); + } + } + return result.Succeeded(); + } else if (m_options.address != LLDB_INVALID_ADDRESS) { + Address so_addr; + StreamString error_strm; + SymbolContextList sc_list; + + if (target->GetSectionLoadList().IsEmpty()) { + // The target isn't loaded yet, we need to lookup the file address + // in all modules + const ModuleList &module_list = target->GetImages(); + const size_t num_modules = module_list.GetSize(); + for (size_t i = 0; i < num_modules; ++i) { + ModuleSP module_sp(module_list.GetModuleAtIndex(i)); + if (module_sp && + module_sp->ResolveFileAddress(m_options.address, so_addr)) { + SymbolContext sc; + sc.Clear(true); + if (module_sp->ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, sc) & + eSymbolContextLineEntry) + sc_list.Append(sc); + } } - return num_matches; - } - size_t FindMatchingFunctionSymbols (Target *target, const ConstString &name, SymbolContextList& sc_list) - { - size_t num_matches = 0; - const size_t num_modules = m_options.modules.size(); - if (num_modules > 0) - { - ModuleList matching_modules; - for (size_t i = 0; i < num_modules; ++i) - { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); - if (module_file_spec) - { - ModuleSpec module_spec (module_file_spec); - matching_modules.Clear(); - target->GetImages().FindModules (module_spec, matching_modules); - num_matches += matching_modules.FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list); - } - } + if (sc_list.GetSize() == 0) { + result.AppendErrorWithFormat( + "no modules have source information for file address 0x%" PRIx64 + ".\n", + m_options.address); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - num_matches = target->GetImages().FindFunctionSymbols (name, eFunctionNameTypeAuto, sc_list); + } else { + // The target has some things loaded, resolve this address to a + // compile unit + file + line and display + if (target->GetSectionLoadList().ResolveLoadAddress(m_options.address, + so_addr)) { + ModuleSP module_sp(so_addr.GetModule()); + if (module_sp) { + SymbolContext sc; + sc.Clear(true); + if (module_sp->ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, sc) & + eSymbolContextLineEntry) { + sc_list.Append(sc); + } else { + so_addr.Dump(&error_strm, nullptr, + Address::DumpStyleModuleWithFileAddress); + result.AppendErrorWithFormat("address resolves to %s, but there " + "is no line table information " + "available for this address.\n", + error_strm.GetData()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } } - return num_matches; - } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - if (argc != 0) - { - result.AppendErrorWithFormat("'%s' takes no arguments, only flags.\n", GetCommandName()); - result.SetStatus (eReturnStatusFailed); - return false; + if (sc_list.GetSize() == 0) { + result.AppendErrorWithFormat( + "no modules contain load address 0x%" PRIx64 ".\n", + m_options.address); + result.SetStatus(eReturnStatusFailed); + return false; } + } + uint32_t num_matches = sc_list.GetSize(); + for (uint32_t i = 0; i < num_matches; ++i) { + SymbolContext sc; + sc_list.GetContextAtIndex(i, sc); + if (sc.comp_unit) { + if (m_options.show_bp_locs) { + m_breakpoint_locations.Clear(); + const bool show_inlines = true; + m_breakpoint_locations.Reset(*sc.comp_unit, 0, show_inlines); + SearchFilterForUnconstrainedSearches target_search_filter( + target->shared_from_this()); + target_search_filter.Search(m_breakpoint_locations); + } + + bool show_fullpaths = true; + bool show_module = true; + bool show_inlined_frames = true; + const bool show_function_arguments = true; + const bool show_function_name = true; + sc.DumpStopContext(&result.GetOutputStream(), + m_exe_ctx.GetBestExecutionContextScope(), + sc.line_entry.range.GetBaseAddress(), + show_fullpaths, show_module, show_inlined_frames, + show_function_arguments, show_function_name); + result.GetOutputStream().EOL(); + + if (m_options.num_lines == 0) + m_options.num_lines = 10; - Target *target = m_exe_ctx.GetTargetPtr(); - - if (!m_options.symbol_name.empty()) - { - SymbolContextList sc_list; - ConstString name(m_options.symbol_name.c_str()); - - // Displaying the source for a symbol. Search for function named name. - size_t num_matches = FindMatchingFunctions (target, name, sc_list); - if (!num_matches) - { - // If we didn't find any functions with that name, try searching for symbols - // that line up exactly with function addresses. - SymbolContextList sc_list_symbols; - size_t num_symbol_matches = FindMatchingFunctionSymbols (target, name, sc_list_symbols); - for (size_t i = 0; i < num_symbol_matches; i++) - { - SymbolContext sc; - sc_list_symbols.GetContextAtIndex (i, sc); - if (sc.symbol && sc.symbol->ValueIsAddress()) - { - const Address &base_address = sc.symbol->GetAddressRef(); - Function *function = base_address.CalculateSymbolContextFunction(); - if (function) - { - sc_list.Append (SymbolContext(function)); - num_matches++; - break; - } - } - } - } - - if (num_matches == 0) - { - result.AppendErrorWithFormat("Could not find function named: \"%s\".\n", m_options.symbol_name.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + size_t lines_to_back_up = + m_options.num_lines >= 10 ? 5 : m_options.num_lines / 2; - if (num_matches > 1) - { - std::set source_match_set; - - bool displayed_something = false; - for (size_t i = 0; i < num_matches; i++) - { - SymbolContext sc; - sc_list.GetContextAtIndex (i, sc); - SourceInfo source_info (sc.GetFunctionName(), - sc.GetFunctionStartLineEntry()); - - if (source_info.IsValid()) - { - if (source_match_set.find(source_info) == source_match_set.end()) - { - source_match_set.insert(source_info); - if (DisplayFunctionSource (sc, source_info, result)) - displayed_something = true; - } - } - } - - if (displayed_something) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - result.SetStatus (eReturnStatusFailed); - } - else - { - SymbolContext sc; - sc_list.GetContextAtIndex (0, sc); - SourceInfo source_info; - - if (DisplayFunctionSource (sc, source_info, result)) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.SetStatus (eReturnStatusFailed); - } - } - return result.Succeeded(); + target->GetSourceManager().DisplaySourceLinesWithLineNumbers( + sc.comp_unit, sc.line_entry.line, lines_to_back_up, + m_options.num_lines - lines_to_back_up, "->", + &result.GetOutputStream(), GetBreakpointLocations()); + result.SetStatus(eReturnStatusSuccessFinishResult); } - else if (m_options.address != LLDB_INVALID_ADDRESS) - { - Address so_addr; - StreamString error_strm; - SymbolContextList sc_list; - - if (target->GetSectionLoadList().IsEmpty()) - { - // The target isn't loaded yet, we need to lookup the file address - // in all modules - const ModuleList &module_list = target->GetImages(); - const size_t num_modules = module_list.GetSize(); - for (size_t i = 0; i < num_modules; ++i) - { - ModuleSP module_sp (module_list.GetModuleAtIndex(i)); - if (module_sp && module_sp->ResolveFileAddress(m_options.address, so_addr)) - { - SymbolContext sc; - sc.Clear(true); - if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry) - sc_list.Append(sc); - } - } - - if (sc_list.GetSize() == 0) - { - result.AppendErrorWithFormat("no modules have source information for file address 0x%" PRIx64 ".\n", - m_options.address); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - // The target has some things loaded, resolve this address to a - // compile unit + file + line and display - if (target->GetSectionLoadList().ResolveLoadAddress (m_options.address, so_addr)) - { - ModuleSP module_sp (so_addr.GetModule()); - if (module_sp) - { - SymbolContext sc; - sc.Clear(true); - if (module_sp->ResolveSymbolContextForAddress (so_addr, eSymbolContextEverything, sc) & eSymbolContextLineEntry) - { - sc_list.Append(sc); - } - else - { - so_addr.Dump(&error_strm, nullptr, Address::DumpStyleModuleWithFileAddress); - result.AppendErrorWithFormat("address resolves to %s, but there is no line table information available for this address.\n", - error_strm.GetData()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - - if (sc_list.GetSize() == 0) - { - result.AppendErrorWithFormat("no modules contain load address 0x%" PRIx64 ".\n", m_options.address); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - uint32_t num_matches = sc_list.GetSize(); - for (uint32_t i = 0; i < num_matches; ++i) - { - SymbolContext sc; - sc_list.GetContextAtIndex(i, sc); - if (sc.comp_unit) - { - if (m_options.show_bp_locs) - { - m_breakpoint_locations.Clear(); - const bool show_inlines = true; - m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines); - SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this()); - target_search_filter.Search (m_breakpoint_locations); - } - - bool show_fullpaths = true; - bool show_module = true; - bool show_inlined_frames = true; - const bool show_function_arguments = true; - const bool show_function_name = true; - sc.DumpStopContext(&result.GetOutputStream(), - m_exe_ctx.GetBestExecutionContextScope(), - sc.line_entry.range.GetBaseAddress(), - show_fullpaths, - show_module, - show_inlined_frames, - show_function_arguments, - show_function_name); - result.GetOutputStream().EOL(); - - if (m_options.num_lines == 0) - m_options.num_lines = 10; - - size_t lines_to_back_up = m_options.num_lines >= 10 ? 5 : m_options.num_lines/2; - - target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit, - sc.line_entry.line, - lines_to_back_up, - m_options.num_lines - lines_to_back_up, - "->", - &result.GetOutputStream(), - GetBreakpointLocations ()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - } + } + } else if (m_options.file_name.empty()) { + // Last valid source manager context, or the current frame if no + // valid last context in source manager. + // One little trick here, if you type the exact same list command twice in + // a row, it is + // more likely because you typed it once, then typed it again + if (m_options.start_line == 0) { + if (target->GetSourceManager().DisplayMoreWithLineNumbers( + &result.GetOutputStream(), m_options.num_lines, + m_options.reverse, GetBreakpointLocations())) { + result.SetStatus(eReturnStatusSuccessFinishResult); } - else if (m_options.file_name.empty()) - { - // Last valid source manager context, or the current frame if no - // valid last context in source manager. - // One little trick here, if you type the exact same list command twice in a row, it is - // more likely because you typed it once, then typed it again - if (m_options.start_line == 0) - { - if (target->GetSourceManager().DisplayMoreWithLineNumbers (&result.GetOutputStream(), - m_options.num_lines, - m_options.reverse, - GetBreakpointLocations ())) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - } - else - { - if (m_options.num_lines == 0) - m_options.num_lines = 10; - - if (m_options.show_bp_locs) - { - SourceManager::FileSP last_file_sp (target->GetSourceManager().GetLastFile ()); - if (last_file_sp) - { - const bool show_inlines = true; - m_breakpoint_locations.Reset (last_file_sp->GetFileSpec(), 0, show_inlines); - SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this()); - target_search_filter.Search (m_breakpoint_locations); - } - } - else - m_breakpoint_locations.Clear(); - - if (target->GetSourceManager().DisplaySourceLinesWithLineNumbersUsingLastFile( - m_options.start_line, // Line to display - m_options.num_lines, // Lines after line to - UINT32_MAX, // Don't mark "line" - "", // Don't mark "line" - &result.GetOutputStream(), - GetBreakpointLocations ())) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - } - } + } else { + if (m_options.num_lines == 0) + m_options.num_lines = 10; + + if (m_options.show_bp_locs) { + SourceManager::FileSP last_file_sp( + target->GetSourceManager().GetLastFile()); + if (last_file_sp) { + const bool show_inlines = true; + m_breakpoint_locations.Reset(last_file_sp->GetFileSpec(), 0, + show_inlines); + SearchFilterForUnconstrainedSearches target_search_filter( + target->shared_from_this()); + target_search_filter.Search(m_breakpoint_locations); + } + } else + m_breakpoint_locations.Clear(); + + if (target->GetSourceManager() + .DisplaySourceLinesWithLineNumbersUsingLastFile( + m_options.start_line, // Line to display + m_options.num_lines, // Lines after line to + UINT32_MAX, // Don't mark "line" + "", // Don't mark "line" + &result.GetOutputStream(), GetBreakpointLocations())) { + result.SetStatus(eReturnStatusSuccessFinishResult); } - else - { - const char *filename = m_options.file_name.c_str(); - - bool check_inlines = false; - SymbolContextList sc_list; - size_t num_matches = 0; - - if (!m_options.modules.empty()) - { - ModuleList matching_modules; - for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) - { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); - if (module_file_spec) - { - ModuleSpec module_spec (module_file_spec); - matching_modules.Clear(); - target->GetImages().FindModules (module_spec, matching_modules); - num_matches += matching_modules.ResolveSymbolContextForFilePath (filename, - 0, - check_inlines, - eSymbolContextModule | eSymbolContextCompUnit, - sc_list); - } - } - } - else - { - num_matches = target->GetImages().ResolveSymbolContextForFilePath (filename, - 0, - check_inlines, - eSymbolContextModule | eSymbolContextCompUnit, - sc_list); - } - - if (num_matches == 0) - { - result.AppendErrorWithFormat("Could not find source file \"%s\".\n", - m_options.file_name.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + } + } else { + const char *filename = m_options.file_name.c_str(); + + bool check_inlines = false; + SymbolContextList sc_list; + size_t num_matches = 0; + + if (!m_options.modules.empty()) { + ModuleList matching_modules; + for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { + FileSpec module_file_spec(m_options.modules[i].c_str(), false); + if (module_file_spec) { + ModuleSpec module_spec(module_file_spec); + matching_modules.Clear(); + target->GetImages().FindModules(module_spec, matching_modules); + num_matches += matching_modules.ResolveSymbolContextForFilePath( + filename, 0, check_inlines, + eSymbolContextModule | eSymbolContextCompUnit, sc_list); + } + } + } else { + num_matches = target->GetImages().ResolveSymbolContextForFilePath( + filename, 0, check_inlines, + eSymbolContextModule | eSymbolContextCompUnit, sc_list); + } + + if (num_matches == 0) { + result.AppendErrorWithFormat("Could not find source file \"%s\".\n", + m_options.file_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (num_matches > 1) { + bool got_multiple = false; + FileSpec *test_cu_spec = nullptr; + + for (unsigned i = 0; i < num_matches; i++) { + SymbolContext sc; + sc_list.GetContextAtIndex(i, sc); + if (sc.comp_unit) { + if (test_cu_spec) { + if (test_cu_spec != static_cast(sc.comp_unit)) + got_multiple = true; + break; + } else + test_cu_spec = sc.comp_unit; + } + } + if (got_multiple) { + result.AppendErrorWithFormat( + "Multiple source files found matching: \"%s.\"\n", + m_options.file_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + SymbolContext sc; + if (sc_list.GetContextAtIndex(0, sc)) { + if (sc.comp_unit) { + if (m_options.show_bp_locs) { + const bool show_inlines = true; + m_breakpoint_locations.Reset(*sc.comp_unit, 0, show_inlines); + SearchFilterForUnconstrainedSearches target_search_filter( + target->shared_from_this()); + target_search_filter.Search(m_breakpoint_locations); + } else + m_breakpoint_locations.Clear(); - if (num_matches > 1) - { - bool got_multiple = false; - FileSpec *test_cu_spec = nullptr; - - for (unsigned i = 0; i < num_matches; i++) - { - SymbolContext sc; - sc_list.GetContextAtIndex(i, sc); - if (sc.comp_unit) - { - if (test_cu_spec) - { - if (test_cu_spec != static_cast (sc.comp_unit)) - got_multiple = true; - break; - } - else - test_cu_spec = sc.comp_unit; - } - } - if (got_multiple) - { - result.AppendErrorWithFormat("Multiple source files found matching: \"%s.\"\n", - m_options.file_name.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - - SymbolContext sc; - if (sc_list.GetContextAtIndex(0, sc)) - { - if (sc.comp_unit) - { - if (m_options.show_bp_locs) - { - const bool show_inlines = true; - m_breakpoint_locations.Reset (*sc.comp_unit, 0, show_inlines); - SearchFilterForUnconstrainedSearches target_search_filter (target->shared_from_this()); - target_search_filter.Search (m_breakpoint_locations); - } - else - m_breakpoint_locations.Clear(); - - if (m_options.num_lines == 0) - m_options.num_lines = 10; - - target->GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.comp_unit, - m_options.start_line, - 0, - m_options.num_lines, - "", - &result.GetOutputStream(), - GetBreakpointLocations ()); - - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n", - m_options.file_name.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } + if (m_options.num_lines == 0) + m_options.num_lines = 10; + + target->GetSourceManager().DisplaySourceLinesWithLineNumbers( + sc.comp_unit, m_options.start_line, 0, m_options.num_lines, "", + &result.GetOutputStream(), GetBreakpointLocations()); + + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("No comp unit found for: \"%s.\"\n", + m_options.file_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } - return result.Succeeded(); + } } - - const SymbolContextList * - GetBreakpointLocations () - { - if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0) - return &m_breakpoint_locations.GetFileLineMatches(); - return nullptr; - } - - CommandOptions m_options; - FileLineResolver m_breakpoint_locations; - std::string m_reverse_name; + return result.Succeeded(); + } + + const SymbolContextList *GetBreakpointLocations() { + if (m_breakpoint_locations.GetFileLineMatches().GetSize() > 0) + return &m_breakpoint_locations.GetFileLineMatches(); + return nullptr; + } + + CommandOptions m_options; + FileLineResolver m_breakpoint_locations; + std::string m_reverse_name; }; -OptionDefinition -CommandObjectSourceList::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectSourceList::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "The number of source lines to display."}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Look up the source file in the given shared library."}, {LLDB_OPT_SET_ALL, false, "show-breakpoints", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show the line table locations from the debug information that indicate valid places to set source level breakpoints."}, @@ -1469,7 +1308,7 @@ CommandObjectSourceList::CommandOptions::g_option_table[] = {LLDB_OPT_SET_3, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Lookup the address and display the source information for the corresponding file and line."}, {LLDB_OPT_SET_4, false, "reverse", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Reverse the listing to look backwards from the last displayed block of source."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectMultiwordSource @@ -1477,14 +1316,17 @@ CommandObjectSourceList::CommandOptions::g_option_table[] = // CommandObjectMultiwordSource //------------------------------------------------------------------------- -CommandObjectMultiwordSource::CommandObjectMultiwordSource(CommandInterpreter &interpreter) - : CommandObjectMultiword( - interpreter, "source", - "Commands for examining source code described by debug information for the current target process.", - "source []") -{ - LoadSubCommand ("info", CommandObjectSP (new CommandObjectSourceInfo (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectSourceList (interpreter))); +CommandObjectMultiwordSource::CommandObjectMultiwordSource( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "source", "Commands for examining " + "source code described by " + "debug information for the " + "current target process.", + "source []") { + LoadSubCommand("info", + CommandObjectSP(new CommandObjectSourceInfo(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectSourceList(interpreter))); } CommandObjectMultiwordSource::~CommandObjectMultiwordSource() = default; diff --git a/lldb/source/Commands/CommandObjectSource.h b/lldb/source/Commands/CommandObjectSource.h index 7ed08cdc959..e81ac1961d2 100644 --- a/lldb/source/Commands/CommandObjectSource.h +++ b/lldb/source/Commands/CommandObjectSource.h @@ -1,4 +1,5 @@ -//===-- CommandObjectSource.h.h -----------------------------------*- C++ -*-===// +//===-- CommandObjectSource.h.h -----------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -14,9 +15,9 @@ // C++ Includes // Other libraries and framework includes // Project includes +#include "lldb/Core/STLUtils.h" #include "lldb/Interpreter/CommandObject.h" #include "lldb/Interpreter/CommandObjectMultiword.h" -#include "lldb/Core/STLUtils.h" namespace lldb_private { @@ -24,13 +25,11 @@ namespace lldb_private { // CommandObjectMultiwordSource //------------------------------------------------------------------------- -class CommandObjectMultiwordSource : public CommandObjectMultiword -{ +class CommandObjectMultiwordSource : public CommandObjectMultiword { public: + CommandObjectMultiwordSource(CommandInterpreter &interpreter); - CommandObjectMultiwordSource (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordSource() override; + ~CommandObjectMultiwordSource() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectSyntax.cpp b/lldb/source/Commands/CommandObjectSyntax.cpp index c238bccfb5d..6594906bfbe 100644 --- a/lldb/source/Commands/CommandObjectSyntax.cpp +++ b/lldb/source/Commands/CommandObjectSyntax.cpp @@ -14,10 +14,10 @@ #include "CommandObjectSyntax.h" #include "CommandObjectHelp.h" #include "lldb/Interpreter/Args.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Interpreter/Options.h" using namespace lldb; using namespace lldb_private; @@ -26,97 +26,80 @@ using namespace lldb_private; // CommandObjectSyntax //------------------------------------------------------------------------- -CommandObjectSyntax::CommandObjectSyntax (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "syntax", - "Shows the correct syntax for a given debugger command.", - "syntax ") -{ - CommandArgumentEntry arg; - CommandArgumentData command_arg; +CommandObjectSyntax::CommandObjectSyntax(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "syntax", + "Shows the correct syntax for a given debugger command.", + "syntax ") { + CommandArgumentEntry arg; + CommandArgumentData command_arg; - // Define the first (and only) variant of this arg. - command_arg.arg_type = eArgTypeCommandName; - command_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + command_arg.arg_type = eArgTypeCommandName; + command_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (command_arg); + // There is only one variant this argument could be; put it into the argument + // entry. + arg.push_back(command_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); } CommandObjectSyntax::~CommandObjectSyntax() = default; -bool -CommandObjectSyntax::DoExecute (Args& command, CommandReturnObject &result) -{ - CommandObject::CommandMap::iterator pos; - CommandObject *cmd_obj; - const size_t argc = command.GetArgumentCount(); +bool CommandObjectSyntax::DoExecute(Args &command, + CommandReturnObject &result) { + CommandObject::CommandMap::iterator pos; + CommandObject *cmd_obj; + const size_t argc = command.GetArgumentCount(); - if (argc > 0) - { - cmd_obj = m_interpreter.GetCommandObject (command.GetArgumentAtIndex(0)); - bool all_okay = true; - for (size_t i = 1; i < argc; ++i) - { - std::string sub_command = command.GetArgumentAtIndex (i); - if (!cmd_obj->IsMultiwordObject()) - { - all_okay = false; - break; - } - else - { - cmd_obj = cmd_obj->GetSubcommandObject(sub_command.c_str()); - if (!cmd_obj) - { - all_okay = false; - break; - } - } - } - - if (all_okay && (cmd_obj != nullptr)) - { - Stream &output_strm = result.GetOutputStream(); - if (cmd_obj->GetOptions() != nullptr) - { - output_strm.Printf ("\nSyntax: %s\n", cmd_obj->GetSyntax()); - output_strm.Printf ("(Try 'help %s' for more information on command options syntax.)\n", - cmd_obj->GetCommandName()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - output_strm.Printf ("\nSyntax: %s\n", cmd_obj->GetSyntax()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - } - else - { - std::string cmd_string; - command.GetCommandString (cmd_string); - - StreamString error_msg_stream; - const bool generate_apropos = true; - const bool generate_type_lookup = false; - CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, - cmd_string.c_str(), - nullptr, - nullptr, - generate_apropos, - generate_type_lookup); - result.AppendErrorWithFormat ("%s", error_msg_stream.GetData()); - result.SetStatus (eReturnStatusFailed); + if (argc > 0) { + cmd_obj = m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0)); + bool all_okay = true; + for (size_t i = 1; i < argc; ++i) { + std::string sub_command = command.GetArgumentAtIndex(i); + if (!cmd_obj->IsMultiwordObject()) { + all_okay = false; + break; + } else { + cmd_obj = cmd_obj->GetSubcommandObject(sub_command.c_str()); + if (!cmd_obj) { + all_okay = false; + break; } + } } - else - { - result.AppendError ("Must call 'syntax' with a valid command."); - result.SetStatus (eReturnStatusFailed); + + if (all_okay && (cmd_obj != nullptr)) { + Stream &output_strm = result.GetOutputStream(); + if (cmd_obj->GetOptions() != nullptr) { + output_strm.Printf("\nSyntax: %s\n", cmd_obj->GetSyntax()); + output_strm.Printf( + "(Try 'help %s' for more information on command options syntax.)\n", + cmd_obj->GetCommandName()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + output_strm.Printf("\nSyntax: %s\n", cmd_obj->GetSyntax()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } + } else { + std::string cmd_string; + command.GetCommandString(cmd_string); + + StreamString error_msg_stream; + const bool generate_apropos = true; + const bool generate_type_lookup = false; + CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage( + &error_msg_stream, cmd_string.c_str(), nullptr, nullptr, + generate_apropos, generate_type_lookup); + result.AppendErrorWithFormat("%s", error_msg_stream.GetData()); + result.SetStatus(eReturnStatusFailed); } + } else { + result.AppendError("Must call 'syntax' with a valid command."); + result.SetStatus(eReturnStatusFailed); + } - return result.Succeeded(); + return result.Succeeded(); } diff --git a/lldb/source/Commands/CommandObjectSyntax.h b/lldb/source/Commands/CommandObjectSyntax.h index 1a3e4e04f01..b65e9b1b750 100644 --- a/lldb/source/Commands/CommandObjectSyntax.h +++ b/lldb/source/Commands/CommandObjectSyntax.h @@ -22,18 +22,14 @@ namespace lldb_private { // CommandObjectSyntax //------------------------------------------------------------------------- -class CommandObjectSyntax : public CommandObjectParsed -{ +class CommandObjectSyntax : public CommandObjectParsed { public: + CommandObjectSyntax(CommandInterpreter &interpreter); - CommandObjectSyntax (CommandInterpreter &interpreter); + ~CommandObjectSyntax() override; - ~CommandObjectSyntax() override; - protected: - bool - DoExecute(Args& command, - CommandReturnObject &result) override; + bool DoExecute(Args &command, CommandReturnObject &result) override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectTarget.cpp b/lldb/source/Commands/CommandObjectTarget.cpp index dc67e50ee72..d7e4dfa2e9d 100644 --- a/lldb/source/Commands/CommandObjectTarget.cpp +++ b/lldb/source/Commands/CommandObjectTarget.cpp @@ -15,7 +15,6 @@ // Other libraries and framework includes // Project includes -#include "lldb/Interpreter/Args.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/IOHandler.h" #include "lldb/Core/Module.h" @@ -27,19 +26,20 @@ #include "lldb/DataFormatters/ValueObjectPrinter.h" #include "lldb/Host/StringConvert.h" #include "lldb/Host/Symbols.h" +#include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionGroupArchitecture.h" #include "lldb/Interpreter/OptionGroupBoolean.h" #include "lldb/Interpreter/OptionGroupFile.h" #include "lldb/Interpreter/OptionGroupFormat.h" -#include "lldb/Interpreter/OptionGroupVariable.h" #include "lldb/Interpreter/OptionGroupPlatform.h" +#include "lldb/Interpreter/OptionGroupString.h" #include "lldb/Interpreter/OptionGroupUInt64.h" #include "lldb/Interpreter/OptionGroupUUID.h" -#include "lldb/Interpreter/OptionGroupString.h" #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" +#include "lldb/Interpreter/OptionGroupVariable.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/FuncUnwinders.h" #include "lldb/Symbol/LineTable.h" @@ -58,89 +58,78 @@ using namespace lldb; using namespace lldb_private; -static void -DumpTargetInfo (uint32_t target_idx, Target *target, const char *prefix_cstr, bool show_stopped_process_status, Stream &strm) -{ - const ArchSpec &target_arch = target->GetArchitecture(); - - Module *exe_module = target->GetExecutableModulePointer(); - char exe_path[PATH_MAX]; - bool exe_valid = false; - if (exe_module) - exe_valid = exe_module->GetFileSpec().GetPath (exe_path, sizeof(exe_path)); - - if (!exe_valid) - ::strcpy (exe_path, ""); - - strm.Printf ("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx, exe_path); - - uint32_t properties = 0; - if (target_arch.IsValid()) - { - strm.Printf ("%sarch=", properties++ > 0 ? ", " : " ( "); - target_arch.DumpTriple (strm); - properties++; - } - PlatformSP platform_sp (target->GetPlatform()); - if (platform_sp) - strm.Printf ("%splatform=%s", properties++ > 0 ? ", " : " ( ", platform_sp->GetName().GetCString()); - - ProcessSP process_sp (target->GetProcessSP()); - bool show_process_status = false; - if (process_sp) - { - lldb::pid_t pid = process_sp->GetID(); - StateType state = process_sp->GetState(); - if (show_stopped_process_status) - show_process_status = StateIsStoppedState(state, true); - const char *state_cstr = StateAsCString (state); - if (pid != LLDB_INVALID_PROCESS_ID) - strm.Printf ("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid); - strm.Printf ("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr); - } - if (properties > 0) - strm.PutCString (" )\n"); - else - strm.EOL(); - if (show_process_status) - { - const bool only_threads_with_stop_reason = true; - const uint32_t start_frame = 0; - const uint32_t num_frames = 1; - const uint32_t num_frames_with_source = 1; - process_sp->GetStatus (strm); - process_sp->GetThreadStatus (strm, - only_threads_with_stop_reason, - start_frame, - num_frames, - num_frames_with_source); - - } +static void DumpTargetInfo(uint32_t target_idx, Target *target, + const char *prefix_cstr, + bool show_stopped_process_status, Stream &strm) { + const ArchSpec &target_arch = target->GetArchitecture(); + + Module *exe_module = target->GetExecutableModulePointer(); + char exe_path[PATH_MAX]; + bool exe_valid = false; + if (exe_module) + exe_valid = exe_module->GetFileSpec().GetPath(exe_path, sizeof(exe_path)); + + if (!exe_valid) + ::strcpy(exe_path, ""); + + strm.Printf("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx, + exe_path); + + uint32_t properties = 0; + if (target_arch.IsValid()) { + strm.Printf("%sarch=", properties++ > 0 ? ", " : " ( "); + target_arch.DumpTriple(strm); + properties++; + } + PlatformSP platform_sp(target->GetPlatform()); + if (platform_sp) + strm.Printf("%splatform=%s", properties++ > 0 ? ", " : " ( ", + platform_sp->GetName().GetCString()); + + ProcessSP process_sp(target->GetProcessSP()); + bool show_process_status = false; + if (process_sp) { + lldb::pid_t pid = process_sp->GetID(); + StateType state = process_sp->GetState(); + if (show_stopped_process_status) + show_process_status = StateIsStoppedState(state, true); + const char *state_cstr = StateAsCString(state); + if (pid != LLDB_INVALID_PROCESS_ID) + strm.Printf("%spid=%" PRIu64, properties++ > 0 ? ", " : " ( ", pid); + strm.Printf("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr); + } + if (properties > 0) + strm.PutCString(" )\n"); + else + strm.EOL(); + if (show_process_status) { + const bool only_threads_with_stop_reason = true; + const uint32_t start_frame = 0; + const uint32_t num_frames = 1; + const uint32_t num_frames_with_source = 1; + process_sp->GetStatus(strm); + process_sp->GetThreadStatus(strm, only_threads_with_stop_reason, + start_frame, num_frames, + num_frames_with_source); + } } -static uint32_t -DumpTargetList (TargetList &target_list, bool show_stopped_process_status, Stream &strm) -{ - const uint32_t num_targets = target_list.GetNumTargets(); - if (num_targets) - { - TargetSP selected_target_sp (target_list.GetSelectedTarget()); - strm.PutCString ("Current targets:\n"); - for (uint32_t i = 0; i < num_targets; ++i) - { - TargetSP target_sp (target_list.GetTargetAtIndex (i)); - if (target_sp) - { - bool is_selected = target_sp.get() == selected_target_sp.get(); - DumpTargetInfo (i, - target_sp.get(), - is_selected ? "* " : " ", - show_stopped_process_status, - strm); - } - } +static uint32_t DumpTargetList(TargetList &target_list, + bool show_stopped_process_status, Stream &strm) { + const uint32_t num_targets = target_list.GetNumTargets(); + if (num_targets) { + TargetSP selected_target_sp(target_list.GetSelectedTarget()); + strm.PutCString("Current targets:\n"); + for (uint32_t i = 0; i < num_targets; ++i) { + TargetSP target_sp(target_list.GetTargetAtIndex(i)); + if (target_sp) { + bool is_selected = target_sp.get() == selected_target_sp.get(); + DumpTargetInfo(i, target_sp.get(), is_selected ? "* " : " ", + show_stopped_process_status, strm); + } } - return num_targets; + } + return num_targets; } #pragma mark CommandObjectTargetCreate @@ -149,312 +138,283 @@ DumpTargetList (TargetList &target_list, bool show_stopped_process_status, Strea // "target create" //------------------------------------------------------------------------- -class CommandObjectTargetCreate : public CommandObjectParsed -{ +class CommandObjectTargetCreate : public CommandObjectParsed { public: - CommandObjectTargetCreate(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target create", - "Create a target using the argument as the main executable.", - nullptr), - m_option_group (), - m_arch_option (), - m_core_file (LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename, "Fullpath to a core file to use for this target."), - m_platform_path (LLDB_OPT_SET_1, false, "platform-path", 'P', 0, eArgTypePath, "Path to the remote file to use for this target."), - m_symbol_file (LLDB_OPT_SET_1, false, "symfile", 's', 0, eArgTypeFilename, "Fullpath to a stand alone debug symbols file for when debug symbols are not in the executable."), - m_remote_file (LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename, "Fullpath to the file on the remote host if debugging remotely."), - m_add_dependents (LLDB_OPT_SET_1, false, "no-dependents", 'd', "Don't load dependent files when creating the target, just add the specified executable.", true, true) - { - CommandArgumentEntry arg; - CommandArgumentData file_arg; - - // Define the first (and only) variant of this arg. - file_arg.arg_type = eArgTypeFilename; - file_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (file_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - - m_option_group.Append (&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_core_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_platform_path, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_remote_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_add_dependents, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } - - ~CommandObjectTargetCreate() override = default; + CommandObjectTargetCreate(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target create", + "Create a target using the argument as the main executable.", + nullptr), + m_option_group(), m_arch_option(), + m_core_file(LLDB_OPT_SET_1, false, "core", 'c', 0, eArgTypeFilename, + "Fullpath to a core file to use for this target."), + m_platform_path(LLDB_OPT_SET_1, false, "platform-path", 'P', 0, + eArgTypePath, + "Path to the remote file to use for this target."), + m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0, + eArgTypeFilename, "Fullpath to a stand alone debug " + "symbols file for when debug symbols " + "are not in the executable."), + m_remote_file( + LLDB_OPT_SET_1, false, "remote-file", 'r', 0, eArgTypeFilename, + "Fullpath to the file on the remote host if debugging remotely."), + m_add_dependents(LLDB_OPT_SET_1, false, "no-dependents", 'd', + "Don't load dependent files when creating the target, " + "just add the specified executable.", + true, true) { + CommandArgumentEntry arg; + CommandArgumentData file_arg; + + // Define the first (and only) variant of this arg. + file_arg.arg_type = eArgTypeFilename; + file_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(file_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + + m_option_group.Append(&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_core_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_platform_path, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_remote_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_add_dependents, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectTargetCreate() override = default; + + Options *GetOptions() override { return &m_option_group; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } - Options * - GetOptions () override - { - return &m_option_group; - } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + FileSpec core_file(m_core_file.GetOptionValue().GetCurrentValue()); + FileSpec remote_file(m_remote_file.GetOptionValue().GetCurrentValue()); + + if (core_file) { + if (!core_file.Exists()) { + result.AppendErrorWithFormat("core file '%s' doesn't exist", + core_file.GetPath().c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (!core_file.Readable()) { + result.AppendErrorWithFormat("core file '%s' is not readable", + core_file.GetPath().c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } } -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - FileSpec core_file (m_core_file.GetOptionValue().GetCurrentValue()); - FileSpec remote_file (m_remote_file.GetOptionValue().GetCurrentValue()); - - if (core_file) - { - if (!core_file.Exists()) - { - result.AppendErrorWithFormat("core file '%s' doesn't exist", core_file.GetPath().c_str()); - result.SetStatus (eReturnStatusFailed); + if (argc == 1 || core_file || remote_file) { + FileSpec symfile(m_symbol_file.GetOptionValue().GetCurrentValue()); + if (symfile) { + if (symfile.Exists()) { + if (!symfile.Readable()) { + result.AppendErrorWithFormat("symbol file '%s' is not readable", + symfile.GetPath().c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + char symfile_path[PATH_MAX]; + symfile.GetPath(symfile_path, sizeof(symfile_path)); + result.AppendErrorWithFormat("invalid symbol file path '%s'", + symfile_path); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + const char *file_path = command.GetArgumentAtIndex(0); + Timer scoped_timer(LLVM_PRETTY_FUNCTION, "(lldb) target create '%s'", + file_path); + FileSpec file_spec; + + if (file_path) + file_spec.SetFile(file_path, true); + + bool must_set_platform_path = false; + + Debugger &debugger = m_interpreter.GetDebugger(); + + TargetSP target_sp; + const char *arch_cstr = m_arch_option.GetArchitectureName(); + const bool get_dependent_files = + m_add_dependents.GetOptionValue().GetCurrentValue(); + Error error(debugger.GetTargetList().CreateTarget( + debugger, file_path, arch_cstr, get_dependent_files, nullptr, + target_sp)); + + if (target_sp) { + // Only get the platform after we create the target because we might + // have + // switched platforms depending on what the arguments were to + // CreateTarget() + // we can't rely on the selected platform. + + PlatformSP platform_sp = target_sp->GetPlatform(); + + if (remote_file) { + if (platform_sp) { + // I have a remote file.. two possible cases + if (file_spec && file_spec.Exists()) { + // if the remote file does not exist, push it there + if (!platform_sp->GetFileExists(remote_file)) { + Error err = platform_sp->PutFile(file_spec, remote_file); + if (err.Fail()) { + result.AppendError(err.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + } else { + // there is no local file and we need one + // in order to make the remote ---> local transfer we need a + // platform + // TODO: if the user has passed in a --platform argument, use it + // to fetch the right platform + if (!platform_sp) { + result.AppendError( + "unable to perform remote debugging without a platform"); + result.SetStatus(eReturnStatusFailed); return false; - - } - if (!core_file.Readable()) - { - result.AppendErrorWithFormat("core file '%s' is not readable", core_file.GetPath().c_str()); - result.SetStatus (eReturnStatusFailed); + } + if (file_path) { + // copy the remote file to the local file + Error err = platform_sp->GetFile(remote_file, file_spec); + if (err.Fail()) { + result.AppendError(err.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + // make up a local file + result.AppendError("remote --> local transfer without local " + "path is not implemented yet"); + result.SetStatus(eReturnStatusFailed); return false; + } } + } else { + result.AppendError("no platform found for target"); + result.SetStatus(eReturnStatusFailed); + return false; + } } - if (argc == 1 || core_file || remote_file) - { - FileSpec symfile (m_symbol_file.GetOptionValue().GetCurrentValue()); + if (symfile || remote_file) { + ModuleSP module_sp(target_sp->GetExecutableModule()); + if (module_sp) { if (symfile) - { - if (symfile.Exists()) - { - if (!symfile.Readable()) - { - result.AppendErrorWithFormat("symbol file '%s' is not readable", symfile.GetPath().c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - char symfile_path[PATH_MAX]; - symfile.GetPath(symfile_path, sizeof(symfile_path)); - result.AppendErrorWithFormat("invalid symbol file path '%s'", symfile_path); - result.SetStatus (eReturnStatusFailed); - return false; - } + module_sp->SetSymbolFileFileSpec(symfile); + if (remote_file) { + std::string remote_path = remote_file.GetPath(); + target_sp->SetArg0(remote_path.c_str()); + module_sp->SetPlatformFileSpec(remote_file); } + } + } - const char *file_path = command.GetArgumentAtIndex(0); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "(lldb) target create '%s'", file_path); - FileSpec file_spec; - - if (file_path) - file_spec.SetFile (file_path, true); - - bool must_set_platform_path = false; - - Debugger &debugger = m_interpreter.GetDebugger(); - - TargetSP target_sp; - const char *arch_cstr = m_arch_option.GetArchitectureName(); - const bool get_dependent_files = m_add_dependents.GetOptionValue().GetCurrentValue(); - Error error(debugger.GetTargetList().CreateTarget(debugger, - file_path, - arch_cstr, - get_dependent_files, - nullptr, - target_sp)); - - if (target_sp) - { - // Only get the platform after we create the target because we might have - // switched platforms depending on what the arguments were to CreateTarget() - // we can't rely on the selected platform. - - PlatformSP platform_sp = target_sp->GetPlatform(); - - if (remote_file) - { - if (platform_sp) - { - // I have a remote file.. two possible cases - if (file_spec && file_spec.Exists()) - { - // if the remote file does not exist, push it there - if (!platform_sp->GetFileExists (remote_file)) - { - Error err = platform_sp->PutFile(file_spec, remote_file); - if (err.Fail()) - { - result.AppendError(err.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - else - { - // there is no local file and we need one - // in order to make the remote ---> local transfer we need a platform - // TODO: if the user has passed in a --platform argument, use it to fetch the right platform - if (!platform_sp) - { - result.AppendError("unable to perform remote debugging without a platform"); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (file_path) - { - // copy the remote file to the local file - Error err = platform_sp->GetFile(remote_file, file_spec); - if (err.Fail()) - { - result.AppendError(err.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - // make up a local file - result.AppendError("remote --> local transfer without local path is not implemented yet"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - else - { - result.AppendError("no platform found for target"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - - if (symfile || remote_file) - { - ModuleSP module_sp (target_sp->GetExecutableModule()); - if (module_sp) - { - if (symfile) - module_sp->SetSymbolFileFileSpec(symfile); - if (remote_file) - { - std::string remote_path = remote_file.GetPath(); - target_sp->SetArg0(remote_path.c_str()); - module_sp->SetPlatformFileSpec(remote_file); - } - } - } - - debugger.GetTargetList().SetSelectedTarget(target_sp.get()); - if (must_set_platform_path) - { - ModuleSpec main_module_spec(file_spec); - ModuleSP module_sp = target_sp->GetSharedModule(main_module_spec); - if (module_sp) - module_sp->SetPlatformFileSpec(remote_file); - } - if (core_file) - { - char core_path[PATH_MAX]; - core_file.GetPath(core_path, sizeof(core_path)); - if (core_file.Exists()) - { - if (!core_file.Readable()) - { - result.AppendMessageWithFormat ("Core file '%s' is not readable.\n", core_path); - result.SetStatus (eReturnStatusFailed); - return false; - } - FileSpec core_file_dir; - core_file_dir.GetDirectory() = core_file.GetDirectory(); - target_sp->GetExecutableSearchPaths ().Append (core_file_dir); - - ProcessSP process_sp(target_sp->CreateProcess(m_interpreter.GetDebugger().GetListener(), nullptr, &core_file)); - - if (process_sp) - { - // Seems weird that we Launch a core file, but that is - // what we do! - error = process_sp->LoadCore(); - - if (error.Fail()) - { - result.AppendError(error.AsCString("can't find plug-in for core file")); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - result.AppendMessageWithFormat ("Core file '%s' (%s) was loaded.\n", core_path, target_sp->GetArchitecture().GetArchitectureName()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - } - else - { - result.AppendErrorWithFormat ("Unable to find process plug-in for core file '%s'\n", core_path); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("Core file '%s' does not exist\n", core_path); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendMessageWithFormat ("Current executable set to '%s' (%s).\n", file_path, target_sp->GetArchitecture().GetArchitectureName()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } + debugger.GetTargetList().SetSelectedTarget(target_sp.get()); + if (must_set_platform_path) { + ModuleSpec main_module_spec(file_spec); + ModuleSP module_sp = target_sp->GetSharedModule(main_module_spec); + if (module_sp) + module_sp->SetPlatformFileSpec(remote_file); + } + if (core_file) { + char core_path[PATH_MAX]; + core_file.GetPath(core_path, sizeof(core_path)); + if (core_file.Exists()) { + if (!core_file.Readable()) { + result.AppendMessageWithFormat( + "Core file '%s' is not readable.\n", core_path); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - result.AppendError(error.AsCString()); - result.SetStatus (eReturnStatusFailed); + FileSpec core_file_dir; + core_file_dir.GetDirectory() = core_file.GetDirectory(); + target_sp->GetExecutableSearchPaths().Append(core_file_dir); + + ProcessSP process_sp(target_sp->CreateProcess( + m_interpreter.GetDebugger().GetListener(), nullptr, + &core_file)); + + if (process_sp) { + // Seems weird that we Launch a core file, but that is + // what we do! + error = process_sp->LoadCore(); + + if (error.Fail()) { + result.AppendError( + error.AsCString("can't find plug-in for core file")); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + result.AppendMessageWithFormat( + "Core file '%s' (%s) was loaded.\n", core_path, + target_sp->GetArchitecture().GetArchitectureName()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } + } else { + result.AppendErrorWithFormat( + "Unable to find process plug-in for core file '%s'\n", + core_path); + result.SetStatus(eReturnStatusFailed); } + } else { + result.AppendErrorWithFormat("Core file '%s' does not exist\n", + core_path); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendMessageWithFormat( + "Current executable set to '%s' (%s).\n", file_path, + target_sp->GetArchitecture().GetArchitectureName()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } - else - { - result.AppendErrorWithFormat("'%s' takes exactly one executable path argument, or use the --core option.\n", m_cmd_name.c_str()); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + } else { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat("'%s' takes exactly one executable path " + "argument, or use the --core option.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } private: - OptionGroupOptions m_option_group; - OptionGroupArchitecture m_arch_option; - OptionGroupFile m_core_file; - OptionGroupFile m_platform_path; - OptionGroupFile m_symbol_file; - OptionGroupFile m_remote_file; - OptionGroupBoolean m_add_dependents; + OptionGroupOptions m_option_group; + OptionGroupArchitecture m_arch_option; + OptionGroupFile m_core_file; + OptionGroupFile m_platform_path; + OptionGroupFile m_symbol_file; + OptionGroupFile m_remote_file; + OptionGroupBoolean m_add_dependents; }; #pragma mark CommandObjectTargetList @@ -463,41 +423,33 @@ private: // "target list" //---------------------------------------------------------------------- -class CommandObjectTargetList : public CommandObjectParsed -{ +class CommandObjectTargetList : public CommandObjectParsed { public: - CommandObjectTargetList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target list", - "List all current targets in the current debug session.", - nullptr) - { - } + CommandObjectTargetList(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target list", + "List all current targets in the current debug session.", nullptr) { + } - ~CommandObjectTargetList() override = default; + ~CommandObjectTargetList() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - if (args.GetArgumentCount() == 0) - { - Stream &strm = result.GetOutputStream(); - - bool show_stopped_process_status = false; - if (DumpTargetList (m_interpreter.GetDebugger().GetTargetList(), show_stopped_process_status, strm) == 0) - { - strm.PutCString ("No targets.\n"); - } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("the 'target list' command takes no arguments\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &args, CommandReturnObject &result) override { + if (args.GetArgumentCount() == 0) { + Stream &strm = result.GetOutputStream(); + + bool show_stopped_process_status = false; + if (DumpTargetList(m_interpreter.GetDebugger().GetTargetList(), + show_stopped_process_status, strm) == 0) { + strm.PutCString("No targets.\n"); + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("the 'target list' command takes no arguments\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetSelect @@ -506,78 +458,63 @@ protected: // "target select" //---------------------------------------------------------------------- -class CommandObjectTargetSelect : public CommandObjectParsed -{ +class CommandObjectTargetSelect : public CommandObjectParsed { public: - CommandObjectTargetSelect (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target select", - "Select a target as the current target by target index.", - nullptr) - { - } + CommandObjectTargetSelect(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target select", + "Select a target as the current target by target index.", nullptr) { + } - ~CommandObjectTargetSelect() override = default; + ~CommandObjectTargetSelect() override = default; protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - if (args.GetArgumentCount() == 1) - { - bool success = false; - const char *target_idx_arg = args.GetArgumentAtIndex(0); - uint32_t target_idx = StringConvert::ToUInt32 (target_idx_arg, UINT32_MAX, 0, &success); - if (success) - { - TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); - const uint32_t num_targets = target_list.GetNumTargets(); - if (target_idx < num_targets) - { - TargetSP target_sp (target_list.GetTargetAtIndex (target_idx)); - if (target_sp) - { - Stream &strm = result.GetOutputStream(); - target_list.SetSelectedTarget (target_sp.get()); - bool show_stopped_process_status = false; - DumpTargetList (target_list, show_stopped_process_status, strm); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("target #%u is NULL in target list\n", target_idx); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - if (num_targets > 0) - { - result.AppendErrorWithFormat ("index %u is out of range, valid target indexes are 0 - %u\n", - target_idx, - num_targets - 1); - } - else - { - result.AppendErrorWithFormat ("index %u is out of range since there are no active targets\n", - target_idx); - } - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat("invalid index string value '%s'\n", target_idx_arg); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("'target select' takes a single argument: a target index\n"); - result.SetStatus (eReturnStatusFailed); + bool DoExecute(Args &args, CommandReturnObject &result) override { + if (args.GetArgumentCount() == 1) { + bool success = false; + const char *target_idx_arg = args.GetArgumentAtIndex(0); + uint32_t target_idx = + StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success); + if (success) { + TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); + const uint32_t num_targets = target_list.GetNumTargets(); + if (target_idx < num_targets) { + TargetSP target_sp(target_list.GetTargetAtIndex(target_idx)); + if (target_sp) { + Stream &strm = result.GetOutputStream(); + target_list.SetSelectedTarget(target_sp.get()); + bool show_stopped_process_status = false; + DumpTargetList(target_list, show_stopped_process_status, strm); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("target #%u is NULL in target list\n", + target_idx); + result.SetStatus(eReturnStatusFailed); + } + } else { + if (num_targets > 0) { + result.AppendErrorWithFormat( + "index %u is out of range, valid target indexes are 0 - %u\n", + target_idx, num_targets - 1); + } else { + result.AppendErrorWithFormat( + "index %u is out of range since there are no active targets\n", + target_idx); + } + result.SetStatus(eReturnStatusFailed); } - return result.Succeeded(); + } else { + result.AppendErrorWithFormat("invalid index string value '%s'\n", + target_idx_arg); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError( + "'target select' takes a single argument: a target index\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetSelect @@ -586,130 +523,114 @@ protected: // "target delete" //---------------------------------------------------------------------- -class CommandObjectTargetDelete : public CommandObjectParsed -{ +class CommandObjectTargetDelete : public CommandObjectParsed { public: - CommandObjectTargetDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target delete", + CommandObjectTargetDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target delete", "Delete one or more targets by target index.", nullptr), - m_option_group(), - m_all_option(LLDB_OPT_SET_1, false, "all", 'a', "Delete all targets.", false, true), + m_option_group(), m_all_option(LLDB_OPT_SET_1, false, "all", 'a', + "Delete all targets.", false, true), m_cleanup_option( - LLDB_OPT_SET_1, - false, - "clean", 'c', - "Perform extra cleanup to minimize memory consumption after deleting the target. " - "By default, LLDB will keep in memory any modules previously loaded by the target as well " - "as all of its debug info. Specifying --clean will unload all of these shared modules and " + LLDB_OPT_SET_1, false, "clean", 'c', + "Perform extra cleanup to minimize memory consumption after " + "deleting the target. " + "By default, LLDB will keep in memory any modules previously " + "loaded by the target as well " + "as all of its debug info. Specifying --clean will unload all of " + "these shared modules and " "cause them to be reparsed again the next time the target is run", - false, true) - { - m_option_group.Append(&m_all_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append(&m_cleanup_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } + false, true) { + m_option_group.Append(&m_all_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_cleanup_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Finalize(); + } - ~CommandObjectTargetDelete() override = default; + ~CommandObjectTargetDelete() override = default; - Options * - GetOptions () override - { - return &m_option_group; - } + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - const size_t argc = args.GetArgumentCount(); - std::vector delete_target_list; - TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); - TargetSP target_sp; - - if (m_all_option.GetOptionValue()) - { - for (int i = 0; i < target_list.GetNumTargets(); ++i) - delete_target_list.push_back(target_list.GetTargetAtIndex(i)); + bool DoExecute(Args &args, CommandReturnObject &result) override { + const size_t argc = args.GetArgumentCount(); + std::vector delete_target_list; + TargetList &target_list = m_interpreter.GetDebugger().GetTargetList(); + TargetSP target_sp; + + if (m_all_option.GetOptionValue()) { + for (int i = 0; i < target_list.GetNumTargets(); ++i) + delete_target_list.push_back(target_list.GetTargetAtIndex(i)); + } else if (argc > 0) { + const uint32_t num_targets = target_list.GetNumTargets(); + // Bail out if don't have any targets. + if (num_targets == 0) { + result.AppendError("no targets to delete"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + for (uint32_t arg_idx = 0; arg_idx < argc; ++arg_idx) { + const char *target_idx_arg = args.GetArgumentAtIndex(arg_idx); + bool success = false; + uint32_t target_idx = + StringConvert::ToUInt32(target_idx_arg, UINT32_MAX, 0, &success); + if (!success) { + result.AppendErrorWithFormat("invalid target index '%s'\n", + target_idx_arg); + result.SetStatus(eReturnStatusFailed); + return false; } - else if (argc > 0) - { - const uint32_t num_targets = target_list.GetNumTargets(); - // Bail out if don't have any targets. - if (num_targets == 0) { - result.AppendError("no targets to delete"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - for (uint32_t arg_idx = 0; arg_idx < argc; ++arg_idx) - { - const char *target_idx_arg = args.GetArgumentAtIndex(arg_idx); - bool success = false; - uint32_t target_idx = StringConvert::ToUInt32 (target_idx_arg, UINT32_MAX, 0, &success); - if (!success) - { - result.AppendErrorWithFormat("invalid target index '%s'\n", target_idx_arg); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (target_idx < num_targets) - { - target_sp = target_list.GetTargetAtIndex (target_idx); - if (target_sp) - { - delete_target_list.push_back (target_sp); - continue; - } - } - if (num_targets > 1) - result.AppendErrorWithFormat ("target index %u is out of range, valid target indexes are 0 - %u\n", - target_idx, - num_targets - 1); - else - result.AppendErrorWithFormat("target index %u is out of range, the only valid index is 0\n", - target_idx); - - result.SetStatus (eReturnStatusFailed); - return false; - } + if (target_idx < num_targets) { + target_sp = target_list.GetTargetAtIndex(target_idx); + if (target_sp) { + delete_target_list.push_back(target_sp); + continue; + } } + if (num_targets > 1) + result.AppendErrorWithFormat("target index %u is out of range, valid " + "target indexes are 0 - %u\n", + target_idx, num_targets - 1); else - { - target_sp = target_list.GetSelectedTarget(); - if (!target_sp) - { - result.AppendErrorWithFormat("no target is currently selected\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - delete_target_list.push_back (target_sp); - } + result.AppendErrorWithFormat( + "target index %u is out of range, the only valid index is 0\n", + target_idx); - const size_t num_targets_to_delete = delete_target_list.size(); - for (size_t idx = 0; idx < num_targets_to_delete; ++idx) - { - target_sp = delete_target_list[idx]; - target_list.DeleteTarget(target_sp); - target_sp->Destroy(); - } - // If "--clean" was specified, prune any orphaned shared modules from - // the global shared module list - if (m_cleanup_option.GetOptionValue ()) - { - const bool mandatory = true; - ModuleList::RemoveOrphanSharedModules(mandatory); - } - result.GetOutputStream().Printf("%u targets deleted.\n", (uint32_t)num_targets_to_delete); - result.SetStatus(eReturnStatusSuccessFinishResult); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + target_sp = target_list.GetSelectedTarget(); + if (!target_sp) { + result.AppendErrorWithFormat("no target is currently selected\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + delete_target_list.push_back(target_sp); + } - return true; + const size_t num_targets_to_delete = delete_target_list.size(); + for (size_t idx = 0; idx < num_targets_to_delete; ++idx) { + target_sp = delete_target_list[idx]; + target_list.DeleteTarget(target_sp); + target_sp->Destroy(); } + // If "--clean" was specified, prune any orphaned shared modules from + // the global shared module list + if (m_cleanup_option.GetOptionValue()) { + const bool mandatory = true; + ModuleList::RemoveOrphanSharedModules(mandatory); + } + result.GetOutputStream().Printf("%u targets deleted.\n", + (uint32_t)num_targets_to_delete); + result.SetStatus(eReturnStatusSuccessFinishResult); + + return true; + } - OptionGroupOptions m_option_group; - OptionGroupBoolean m_all_option; - OptionGroupBoolean m_cleanup_option; + OptionGroupOptions m_option_group; + OptionGroupBoolean m_all_option; + OptionGroupBoolean m_cleanup_option; }; #pragma mark CommandObjectTargetVariable @@ -718,1308 +639,1138 @@ protected: // "target variable" //---------------------------------------------------------------------- -class CommandObjectTargetVariable : public CommandObjectParsed -{ - static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file' - static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb' +class CommandObjectTargetVariable : public CommandObjectParsed { + static const uint32_t SHORT_OPTION_FILE = 0x66696c65; // 'file' + static const uint32_t SHORT_OPTION_SHLB = 0x73686c62; // 'shlb' public: - CommandObjectTargetVariable(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "target variable", - "Read global variables for the current target, before or while running a process.", - nullptr, eCommandRequiresTarget), - m_option_group(), - m_option_variable(false), // Don't include frame options - m_option_format(eFormatDefault), - m_option_compile_units(LLDB_OPT_SET_1, false, "file", SHORT_OPTION_FILE, 0, eArgTypeFilename, - "A basename or fullpath to a file that contains global variables. This option can be " - "specified multiple times."), - m_option_shared_libraries(LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0, eArgTypeFilename, - "A basename or fullpath to a shared library to use in the search for global " - "variables. This option can be specified multiple times."), - m_varobj_options() - { - CommandArgumentEntry arg; - CommandArgumentData var_name_arg; - - // Define the first (and only) variant of this arg. - var_name_arg.arg_type = eArgTypeVarName; - var_name_arg.arg_repetition = eArgRepeatPlus; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (var_name_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - - m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_option_format, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1); - m_option_group.Append (&m_option_compile_units, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_option_shared_libraries, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); + CommandObjectTargetVariable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target variable", + "Read global variables for the current target, " + "before or while running a process.", + nullptr, eCommandRequiresTarget), + m_option_group(), + m_option_variable(false), // Don't include frame options + m_option_format(eFormatDefault), + m_option_compile_units(LLDB_OPT_SET_1, false, "file", SHORT_OPTION_FILE, + 0, eArgTypeFilename, + "A basename or fullpath to a file that contains " + "global variables. This option can be " + "specified multiple times."), + m_option_shared_libraries( + LLDB_OPT_SET_1, false, "shlib", SHORT_OPTION_SHLB, 0, + eArgTypeFilename, + "A basename or fullpath to a shared library to use in the search " + "for global " + "variables. This option can be specified multiple times."), + m_varobj_options() { + CommandArgumentEntry arg; + CommandArgumentData var_name_arg; + + // Define the first (and only) variant of this arg. + var_name_arg.arg_type = eArgTypeVarName; + var_name_arg.arg_repetition = eArgRepeatPlus; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(var_name_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + + m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_option_format, + OptionGroupFormat::OPTION_GROUP_FORMAT | + OptionGroupFormat::OPTION_GROUP_GDB_FMT, + LLDB_OPT_SET_1); + m_option_group.Append(&m_option_compile_units, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Append(&m_option_shared_libraries, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectTargetVariable() override = default; + + void DumpValueObject(Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp, + const char *root_name) { + DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions()); + + if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() && + valobj_sp->IsRuntimeSupportValue()) + return; + + switch (var_sp->GetScope()) { + case eValueTypeVariableGlobal: + if (m_option_variable.show_scope) + s.PutCString("GLOBAL: "); + break; + + case eValueTypeVariableStatic: + if (m_option_variable.show_scope) + s.PutCString("STATIC: "); + break; + + case eValueTypeVariableArgument: + if (m_option_variable.show_scope) + s.PutCString(" ARG: "); + break; + + case eValueTypeVariableLocal: + if (m_option_variable.show_scope) + s.PutCString(" LOCAL: "); + break; + + case eValueTypeVariableThreadLocal: + if (m_option_variable.show_scope) + s.PutCString("THREAD: "); + break; + + default: + break; } - ~CommandObjectTargetVariable() override = default; - - void - DumpValueObject (Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp, const char *root_name) - { - DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions()); + if (m_option_variable.show_decl) { + bool show_fullpaths = false; + bool show_module = true; + if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module)) + s.PutCString(": "); + } - if (!valobj_sp->GetTargetSP()->GetDisplayRuntimeSupportValues() && - valobj_sp->IsRuntimeSupportValue()) - return; - - switch (var_sp->GetScope()) - { - case eValueTypeVariableGlobal: - if (m_option_variable.show_scope) - s.PutCString("GLOBAL: "); - break; + const Format format = m_option_format.GetFormat(); + if (format != eFormatDefault) + options.SetFormat(format); - case eValueTypeVariableStatic: - if (m_option_variable.show_scope) - s.PutCString("STATIC: "); - break; + options.SetRootValueObjectName(root_name); - case eValueTypeVariableArgument: - if (m_option_variable.show_scope) - s.PutCString(" ARG: "); - break; + valobj_sp->Dump(s, options); + } - case eValueTypeVariableLocal: - if (m_option_variable.show_scope) - s.PutCString(" LOCAL: "); - break; + static size_t GetVariableCallback(void *baton, const char *name, + VariableList &variable_list) { + Target *target = static_cast(baton); + if (target) { + return target->GetImages().FindGlobalVariables(ConstString(name), true, + UINT32_MAX, variable_list); + } + return 0; + } - case eValueTypeVariableThreadLocal: - if (m_option_variable.show_scope) - s.PutCString("THREAD: "); - break; + Options *GetOptions() override { return &m_option_group; } - default: - break; +protected: + void DumpGlobalVariableList(const ExecutionContext &exe_ctx, + const SymbolContext &sc, + const VariableList &variable_list, Stream &s) { + size_t count = variable_list.GetSize(); + if (count > 0) { + if (sc.module_sp) { + if (sc.comp_unit) { + s.Printf("Global variables for %s in %s:\n", + sc.comp_unit->GetPath().c_str(), + sc.module_sp->GetFileSpec().GetPath().c_str()); + } else { + s.Printf("Global variables for %s\n", + sc.module_sp->GetFileSpec().GetPath().c_str()); } - - if (m_option_variable.show_decl) - { - bool show_fullpaths = false; - bool show_module = true; - if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module)) - s.PutCString (": "); + } else if (sc.comp_unit) { + s.Printf("Global variables for %s\n", sc.comp_unit->GetPath().c_str()); + } + + for (uint32_t i = 0; i < count; ++i) { + VariableSP var_sp(variable_list.GetVariableAtIndex(i)); + if (var_sp) { + ValueObjectSP valobj_sp(ValueObjectVariable::Create( + exe_ctx.GetBestExecutionContextScope(), var_sp)); + + if (valobj_sp) + DumpValueObject(s, var_sp, valobj_sp, + var_sp->GetName().GetCString()); } - - const Format format = m_option_format.GetFormat(); - if (format != eFormatDefault) - options.SetFormat(format); - - options.SetRootValueObjectName(root_name); - - valobj_sp->Dump(s,options); + } } - - static size_t GetVariableCallback (void *baton, - const char *name, - VariableList &variable_list) - { - Target *target = static_cast(baton); - if (target) - { - return target->GetImages().FindGlobalVariables (ConstString(name), - true, - UINT32_MAX, - variable_list); + } + + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_exe_ctx.GetTargetPtr(); + const size_t argc = args.GetArgumentCount(); + Stream &s = result.GetOutputStream(); + + if (argc > 0) { + + for (size_t idx = 0; idx < argc; ++idx) { + VariableList variable_list; + ValueObjectList valobj_list; + + const char *arg = args.GetArgumentAtIndex(idx); + size_t matches = 0; + bool use_var_name = false; + if (m_option_variable.use_regex) { + RegularExpression regex(arg); + if (!regex.IsValid()) { + result.GetErrorStream().Printf( + "error: invalid regular expression: '%s'\n", arg); + result.SetStatus(eReturnStatusFailed); + return false; + } + use_var_name = true; + matches = target->GetImages().FindGlobalVariables( + regex, true, UINT32_MAX, variable_list); + } else { + Error error(Variable::GetValuesForVariableExpressionPath( + arg, m_exe_ctx.GetBestExecutionContextScope(), + GetVariableCallback, target, variable_list, valobj_list)); + matches = variable_list.GetSize(); } - return 0; - } - - Options * - GetOptions () override - { - return &m_option_group; - } - -protected: - void - DumpGlobalVariableList(const ExecutionContext &exe_ctx, const SymbolContext &sc, const VariableList &variable_list, Stream &s) - { - size_t count = variable_list.GetSize(); - if (count > 0) - { - if (sc.module_sp) - { - if (sc.comp_unit) - { - s.Printf ("Global variables for %s in %s:\n", - sc.comp_unit->GetPath().c_str(), - sc.module_sp->GetFileSpec().GetPath().c_str()); - } - else - { - s.Printf ("Global variables for %s\n", - sc.module_sp->GetFileSpec().GetPath().c_str()); - } - } - else if (sc.comp_unit) - { - s.Printf ("Global variables for %s\n", - sc.comp_unit->GetPath().c_str()); - } - for (uint32_t i = 0; i < count; ++i) - { - VariableSP var_sp (variable_list.GetVariableAtIndex(i)); - if (var_sp) - { - ValueObjectSP valobj_sp (ValueObjectVariable::Create (exe_ctx.GetBestExecutionContextScope(), var_sp)); - - if (valobj_sp) - DumpValueObject (s, var_sp, valobj_sp, var_sp->GetName().GetCString()); - } + if (matches == 0) { + result.GetErrorStream().Printf( + "error: can't find global variable '%s'\n", arg); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + for (uint32_t global_idx = 0; global_idx < matches; ++global_idx) { + VariableSP var_sp(variable_list.GetVariableAtIndex(global_idx)); + if (var_sp) { + ValueObjectSP valobj_sp( + valobj_list.GetValueObjectAtIndex(global_idx)); + if (!valobj_sp) + valobj_sp = ValueObjectVariable::Create( + m_exe_ctx.GetBestExecutionContextScope(), var_sp); + + if (valobj_sp) + DumpValueObject(s, var_sp, valobj_sp, + use_var_name ? var_sp->GetName().GetCString() + : arg); } + } } - } - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_exe_ctx.GetTargetPtr(); - const size_t argc = args.GetArgumentCount(); - Stream &s = result.GetOutputStream(); - - if (argc > 0) - { - - for (size_t idx = 0; idx < argc; ++idx) - { - VariableList variable_list; - ValueObjectList valobj_list; - - const char *arg = args.GetArgumentAtIndex(idx); - size_t matches = 0; - bool use_var_name = false; - if (m_option_variable.use_regex) - { - RegularExpression regex(arg); - if (!regex.IsValid ()) - { - result.GetErrorStream().Printf ("error: invalid regular expression: '%s'\n", arg); - result.SetStatus (eReturnStatusFailed); - return false; - } - use_var_name = true; - matches = target->GetImages().FindGlobalVariables (regex, - true, - UINT32_MAX, - variable_list); - } - else - { - Error error (Variable::GetValuesForVariableExpressionPath (arg, - m_exe_ctx.GetBestExecutionContextScope(), - GetVariableCallback, - target, - variable_list, - valobj_list)); - matches = variable_list.GetSize(); - } - - if (matches == 0) - { - result.GetErrorStream().Printf ("error: can't find global variable '%s'\n", arg); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - for (uint32_t global_idx=0; global_idxGetName().GetCString() : arg); - } - } - } + } + } else { + const FileSpecList &compile_units = + m_option_compile_units.GetOptionValue().GetCurrentValue(); + const FileSpecList &shlibs = + m_option_shared_libraries.GetOptionValue().GetCurrentValue(); + SymbolContextList sc_list; + const size_t num_compile_units = compile_units.GetSize(); + const size_t num_shlibs = shlibs.GetSize(); + if (num_compile_units == 0 && num_shlibs == 0) { + bool success = false; + StackFrame *frame = m_exe_ctx.GetFramePtr(); + CompileUnit *comp_unit = nullptr; + if (frame) { + SymbolContext sc = frame->GetSymbolContext(eSymbolContextCompUnit); + if (sc.comp_unit) { + const bool can_create = true; + VariableListSP comp_unit_varlist_sp( + sc.comp_unit->GetVariableList(can_create)); + if (comp_unit_varlist_sp) { + size_t count = comp_unit_varlist_sp->GetSize(); + if (count > 0) { + DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s); + success = true; + } } + } } - else - { - const FileSpecList &compile_units = m_option_compile_units.GetOptionValue().GetCurrentValue(); - const FileSpecList &shlibs = m_option_shared_libraries.GetOptionValue().GetCurrentValue(); - SymbolContextList sc_list; - const size_t num_compile_units = compile_units.GetSize(); - const size_t num_shlibs = shlibs.GetSize(); - if (num_compile_units == 0 && num_shlibs == 0) - { - bool success = false; - StackFrame *frame = m_exe_ctx.GetFramePtr(); - CompileUnit *comp_unit = nullptr; - if (frame) - { - SymbolContext sc = frame->GetSymbolContext (eSymbolContextCompUnit); - if (sc.comp_unit) - { - const bool can_create = true; - VariableListSP comp_unit_varlist_sp (sc.comp_unit->GetVariableList(can_create)); - if (comp_unit_varlist_sp) - { - size_t count = comp_unit_varlist_sp->GetSize(); - if (count > 0) - { - DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s); - success = true; - } - } - } - } - if (!success) - { - if (frame) - { - if (comp_unit) - result.AppendErrorWithFormat ("no global variables in current compile unit: %s\n", - comp_unit->GetPath().c_str()); - else - result.AppendErrorWithFormat ("no debug information for frame %u\n", frame->GetFrameIndex()); - } - else - result.AppendError ("'target variable' takes one or more global variable names as arguments\n"); - result.SetStatus (eReturnStatusFailed); - } - } + if (!success) { + if (frame) { + if (comp_unit) + result.AppendErrorWithFormat( + "no global variables in current compile unit: %s\n", + comp_unit->GetPath().c_str()); else - { - SymbolContextList sc_list; - const bool append = true; - // We have one or more compile unit or shlib - if (num_shlibs > 0) - { - for (size_t shlib_idx=0; shlib_idxGetImages().FindFirstModule(module_spec)); - if (module_sp) - { - if (num_compile_units > 0) - { - for (size_t cu_idx=0; cu_idxFindCompileUnits(compile_units.GetFileSpecAtIndex(cu_idx), append, sc_list); - } - else - { - SymbolContext sc; - sc.module_sp = module_sp; - sc_list.Append(sc); - } - } - else - { - // Didn't find matching shlib/module in target... - result.AppendErrorWithFormat ("target doesn't contain the specified shared library: %s\n", - module_file.GetPath().c_str()); - } - } - } - else - { - // No shared libraries, we just want to find globals for the compile units files that were specified - for (size_t cu_idx=0; cu_idxGetImages().FindCompileUnits(compile_units.GetFileSpecAtIndex(cu_idx), append, sc_list); - } - - const uint32_t num_scs = sc_list.GetSize(); - if (num_scs > 0) - { - SymbolContext sc; - for (uint32_t sc_idx=0; sc_idxGetVariableList(can_create)); - if (comp_unit_varlist_sp) - DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, s); - } - else if (sc.module_sp) - { - // Get all global variables for this module - lldb_private::RegularExpression all_globals_regex("."); // Any global with at least one character - VariableList variable_list; - sc.module_sp->FindGlobalVariables(all_globals_regex, append, UINT32_MAX, variable_list); - DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s); - } - } - } - } + result.AppendErrorWithFormat( + "no debug information for frame %u\n", + frame->GetFrameIndex()); + } else + result.AppendError("'target variable' takes one or more global " + "variable names as arguments\n"); + result.SetStatus(eReturnStatusFailed); + } + } else { + SymbolContextList sc_list; + const bool append = true; + // We have one or more compile unit or shlib + if (num_shlibs > 0) { + for (size_t shlib_idx = 0; shlib_idx < num_shlibs; ++shlib_idx) { + const FileSpec module_file(shlibs.GetFileSpecAtIndex(shlib_idx)); + ModuleSpec module_spec(module_file); + + ModuleSP module_sp( + target->GetImages().FindFirstModule(module_spec)); + if (module_sp) { + if (num_compile_units > 0) { + for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) + module_sp->FindCompileUnits( + compile_units.GetFileSpecAtIndex(cu_idx), append, + sc_list); + } else { + SymbolContext sc; + sc.module_sp = module_sp; + sc_list.Append(sc); + } + } else { + // Didn't find matching shlib/module in target... + result.AppendErrorWithFormat( + "target doesn't contain the specified shared library: %s\n", + module_file.GetPath().c_str()); } + } + } else { + // No shared libraries, we just want to find globals for the compile + // units files that were specified + for (size_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) + target->GetImages().FindCompileUnits( + compile_units.GetFileSpecAtIndex(cu_idx), append, sc_list); } - if (m_interpreter.TruncationWarningNecessary()) - { - result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(), - m_cmd_name.c_str()); - m_interpreter.TruncationWarningGiven(); + const uint32_t num_scs = sc_list.GetSize(); + if (num_scs > 0) { + SymbolContext sc; + for (uint32_t sc_idx = 0; sc_idx < num_scs; ++sc_idx) { + if (sc_list.GetContextAtIndex(sc_idx, sc)) { + if (sc.comp_unit) { + const bool can_create = true; + VariableListSP comp_unit_varlist_sp( + sc.comp_unit->GetVariableList(can_create)); + if (comp_unit_varlist_sp) + DumpGlobalVariableList(m_exe_ctx, sc, *comp_unit_varlist_sp, + s); + } else if (sc.module_sp) { + // Get all global variables for this module + lldb_private::RegularExpression all_globals_regex( + "."); // Any global with at least one character + VariableList variable_list; + sc.module_sp->FindGlobalVariables(all_globals_regex, append, + UINT32_MAX, variable_list); + DumpGlobalVariableList(m_exe_ctx, sc, variable_list, s); + } + } + } } + } + } - return result.Succeeded(); + if (m_interpreter.TruncationWarningNecessary()) { + result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(), + m_cmd_name.c_str()); + m_interpreter.TruncationWarningGiven(); } - OptionGroupOptions m_option_group; - OptionGroupVariable m_option_variable; - OptionGroupFormat m_option_format; - OptionGroupFileList m_option_compile_units; - OptionGroupFileList m_option_shared_libraries; - OptionGroupValueObjectDisplay m_varobj_options; + return result.Succeeded(); + } + + OptionGroupOptions m_option_group; + OptionGroupVariable m_option_variable; + OptionGroupFormat m_option_format; + OptionGroupFileList m_option_compile_units; + OptionGroupFileList m_option_shared_libraries; + OptionGroupValueObjectDisplay m_varobj_options; }; #pragma mark CommandObjectTargetModulesSearchPathsAdd -class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed -{ +class CommandObjectTargetModulesSearchPathsAdd : public CommandObjectParsed { public: - CommandObjectTargetModulesSearchPathsAdd (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target modules search-paths add", - "Add new image search paths substitution pairs to the current target.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData old_prefix_arg; - CommandArgumentData new_prefix_arg; - - // Define the first variant of this arg pair. - old_prefix_arg.arg_type = eArgTypeOldPathPrefix; - old_prefix_arg.arg_repetition = eArgRepeatPairPlus; - - // Define the first variant of this arg pair. - new_prefix_arg.arg_type = eArgTypeNewPathPrefix; - new_prefix_arg.arg_repetition = eArgRepeatPairPlus; - - // There are two required arguments that must always occur together, i.e. an argument "pair". Because they - // must always occur together, they are treated as two variants of one argument rather than two independent - // arguments. Push them both into the first argument position for m_arguments... - - arg.push_back (old_prefix_arg); - arg.push_back (new_prefix_arg); - - m_arguments.push_back (arg); - } - - ~CommandObjectTargetModulesSearchPathsAdd() override = default; + CommandObjectTargetModulesSearchPathsAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules search-paths add", + "Add new image search paths substitution pairs to " + "the current target.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData old_prefix_arg; + CommandArgumentData new_prefix_arg; + + // Define the first variant of this arg pair. + old_prefix_arg.arg_type = eArgTypeOldPathPrefix; + old_prefix_arg.arg_repetition = eArgRepeatPairPlus; + + // Define the first variant of this arg pair. + new_prefix_arg.arg_type = eArgTypeNewPathPrefix; + new_prefix_arg.arg_repetition = eArgRepeatPairPlus; + + // There are two required arguments that must always occur together, i.e. an + // argument "pair". Because they + // must always occur together, they are treated as two variants of one + // argument rather than two independent + // arguments. Push them both into the first argument position for + // m_arguments... + + arg.push_back(old_prefix_arg); + arg.push_back(new_prefix_arg); + + m_arguments.push_back(arg); + } + + ~CommandObjectTargetModulesSearchPathsAdd() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - { - const size_t argc = command.GetArgumentCount(); - if (argc & 1) - { - result.AppendError ("add requires an even number of arguments\n"); - result.SetStatus (eReturnStatusFailed); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) { + const size_t argc = command.GetArgumentCount(); + if (argc & 1) { + result.AppendError("add requires an even number of arguments\n"); + result.SetStatus(eReturnStatusFailed); + } else { + for (size_t i = 0; i < argc; i += 2) { + const char *from = command.GetArgumentAtIndex(i); + const char *to = command.GetArgumentAtIndex(i + 1); + + if (from[0] && to[0]) { + Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); + if (log) { + log->Printf("target modules search path adding ImageSearchPath " + "pair: '%s' -> '%s'", + from, to); } + bool last_pair = ((argc - i) == 2); + target->GetImageSearchPathList().Append( + ConstString(from), ConstString(to), + last_pair); // Notify if this is the last pair + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + if (from[0]) + result.AppendError(" can't be empty\n"); else - { - for (size_t i = 0; i < argc; i+=2) - { - const char *from = command.GetArgumentAtIndex(i); - const char *to = command.GetArgumentAtIndex(i+1); - - if (from[0] && to[0]) - { - Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); - if (log) - { - log->Printf ("target modules search path adding ImageSearchPath pair: '%s' -> '%s'", - from, to); - } - bool last_pair = ((argc - i) == 2); - target->GetImageSearchPathList().Append (ConstString(from), - ConstString(to), - last_pair); // Notify if this is the last pair - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - if (from[0]) - result.AppendError (" can't be empty\n"); - else - result.AppendError (" can't be empty\n"); - result.SetStatus (eReturnStatusFailed); - } - } - } - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); + result.AppendError(" can't be empty\n"); + result.SetStatus(eReturnStatusFailed); + } } - return result.Succeeded(); + } + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesSearchPathsClear -class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed -{ +class CommandObjectTargetModulesSearchPathsClear : public CommandObjectParsed { public: - CommandObjectTargetModulesSearchPathsClear (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target modules search-paths clear", - "Clear all current image search path substitution pairs from the current target.", - "target modules search-paths clear") - { - } + CommandObjectTargetModulesSearchPathsClear(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules search-paths clear", + "Clear all current image search path substitution " + "pairs from the current target.", + "target modules search-paths clear") {} - ~CommandObjectTargetModulesSearchPathsClear() override = default; + ~CommandObjectTargetModulesSearchPathsClear() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - { - bool notify = true; - target->GetImageSearchPathList().Clear(notify); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) { + bool notify = true; + target->GetImageSearchPathList().Clear(notify); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesSearchPathsInsert -class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed -{ +class CommandObjectTargetModulesSearchPathsInsert : public CommandObjectParsed { public: - CommandObjectTargetModulesSearchPathsInsert (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target modules search-paths insert", - "Insert a new image search path substitution pair into the current target at the specified index.", - nullptr) - { - CommandArgumentEntry arg1; - CommandArgumentEntry arg2; - CommandArgumentData index_arg; - CommandArgumentData old_prefix_arg; - CommandArgumentData new_prefix_arg; - - // Define the first and only variant of this arg. - index_arg.arg_type = eArgTypeIndex; - index_arg.arg_repetition = eArgRepeatPlain; - - // Put the one and only variant into the first arg for m_arguments: - arg1.push_back (index_arg); - - // Define the first variant of this arg pair. - old_prefix_arg.arg_type = eArgTypeOldPathPrefix; - old_prefix_arg.arg_repetition = eArgRepeatPairPlus; - - // Define the first variant of this arg pair. - new_prefix_arg.arg_type = eArgTypeNewPathPrefix; - new_prefix_arg.arg_repetition = eArgRepeatPairPlus; - - // There are two required arguments that must always occur together, i.e. an argument "pair". Because they - // must always occur together, they are treated as two variants of one argument rather than two independent - // arguments. Push them both into the same argument position for m_arguments... - - arg2.push_back (old_prefix_arg); - arg2.push_back (new_prefix_arg); - - // Add arguments to m_arguments. - m_arguments.push_back (arg1); - m_arguments.push_back (arg2); - } - - ~CommandObjectTargetModulesSearchPathsInsert() override = default; + CommandObjectTargetModulesSearchPathsInsert(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules search-paths insert", + "Insert a new image search path substitution pair " + "into the current target at the specified index.", + nullptr) { + CommandArgumentEntry arg1; + CommandArgumentEntry arg2; + CommandArgumentData index_arg; + CommandArgumentData old_prefix_arg; + CommandArgumentData new_prefix_arg; + + // Define the first and only variant of this arg. + index_arg.arg_type = eArgTypeIndex; + index_arg.arg_repetition = eArgRepeatPlain; + + // Put the one and only variant into the first arg for m_arguments: + arg1.push_back(index_arg); + + // Define the first variant of this arg pair. + old_prefix_arg.arg_type = eArgTypeOldPathPrefix; + old_prefix_arg.arg_repetition = eArgRepeatPairPlus; + + // Define the first variant of this arg pair. + new_prefix_arg.arg_type = eArgTypeNewPathPrefix; + new_prefix_arg.arg_repetition = eArgRepeatPairPlus; + + // There are two required arguments that must always occur together, i.e. an + // argument "pair". Because they + // must always occur together, they are treated as two variants of one + // argument rather than two independent + // arguments. Push them both into the same argument position for + // m_arguments... + + arg2.push_back(old_prefix_arg); + arg2.push_back(new_prefix_arg); + + // Add arguments to m_arguments. + m_arguments.push_back(arg1); + m_arguments.push_back(arg2); + } + + ~CommandObjectTargetModulesSearchPathsInsert() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - { - size_t argc = command.GetArgumentCount(); - // check for at least 3 arguments and an odd number of parameters - if (argc >= 3 && argc & 1) - { - bool success = false; - - uint32_t insert_idx = StringConvert::ToUInt32(command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success); - - if (!success) - { - result.AppendErrorWithFormat(" parameter is not an integer: '%s'.\n", command.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) { + size_t argc = command.GetArgumentCount(); + // check for at least 3 arguments and an odd number of parameters + if (argc >= 3 && argc & 1) { + bool success = false; + + uint32_t insert_idx = StringConvert::ToUInt32( + command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success); + + if (!success) { + result.AppendErrorWithFormat( + " parameter is not an integer: '%s'.\n", + command.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + return result.Succeeded(); + } - // shift off the index - command.Shift(); - argc = command.GetArgumentCount(); - - for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) - { - const char *from = command.GetArgumentAtIndex(i); - const char *to = command.GetArgumentAtIndex(i+1); - - if (from[0] && to[0]) - { - bool last_pair = ((argc - i) == 2); - target->GetImageSearchPathList().Insert (ConstString(from), - ConstString(to), - insert_idx, - last_pair); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - if (from[0]) - result.AppendError (" can't be empty\n"); - else - result.AppendError (" can't be empty\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } + // shift off the index + command.Shift(); + argc = command.GetArgumentCount(); + + for (uint32_t i = 0; i < argc; i += 2, ++insert_idx) { + const char *from = command.GetArgumentAtIndex(i); + const char *to = command.GetArgumentAtIndex(i + 1); + + if (from[0] && to[0]) { + bool last_pair = ((argc - i) == 2); + target->GetImageSearchPathList().Insert( + ConstString(from), ConstString(to), insert_idx, last_pair); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + if (from[0]) + result.AppendError(" can't be empty\n"); else - { - result.AppendError ("insert requires at least three arguments\n"); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } - - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); + result.AppendError(" can't be empty\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } } + } else { + result.AppendError("insert requires at least three arguments\n"); + result.SetStatus(eReturnStatusFailed); return result.Succeeded(); + } + + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesSearchPathsList -class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed -{ +class CommandObjectTargetModulesSearchPathsList : public CommandObjectParsed { public: - CommandObjectTargetModulesSearchPathsList (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target modules search-paths list", - "List all current image search path substitution pairs in the current target.", - "target modules search-paths list") - { - } + CommandObjectTargetModulesSearchPathsList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules search-paths list", + "List all current image search path substitution " + "pairs in the current target.", + "target modules search-paths list") {} - ~CommandObjectTargetModulesSearchPathsList() override = default; + ~CommandObjectTargetModulesSearchPathsList() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - { - if (command.GetArgumentCount() != 0) - { - result.AppendError ("list takes no arguments\n"); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } - - target->GetImageSearchPathList().Dump(&result.GetOutputStream()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) { + if (command.GetArgumentCount() != 0) { + result.AppendError("list takes no arguments\n"); + result.SetStatus(eReturnStatusFailed); return result.Succeeded(); + } + + target->GetImageSearchPathList().Dump(&result.GetOutputStream()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesSearchPathsQuery -class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed -{ +class CommandObjectTargetModulesSearchPathsQuery : public CommandObjectParsed { public: - CommandObjectTargetModulesSearchPathsQuery (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target modules search-paths query", - "Transform a path using the first applicable image search path.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData path_arg; - - // Define the first (and only) variant of this arg. - path_arg.arg_type = eArgTypeDirectoryName; - path_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (path_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectTargetModulesSearchPathsQuery(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target modules search-paths query", + "Transform a path using the first applicable image search path.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData path_arg; - ~CommandObjectTargetModulesSearchPathsQuery() override = default; + // Define the first (and only) variant of this arg. + path_arg.arg_type = eArgTypeDirectoryName; + path_arg.arg_repetition = eArgRepeatPlain; -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - { - if (command.GetArgumentCount() != 1) - { - result.AppendError ("query requires one argument\n"); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(path_arg); - ConstString orig(command.GetArgumentAtIndex(0)); - ConstString transformed; - if (target->GetImageSearchPathList().RemapPath(orig, transformed)) - result.GetOutputStream().Printf("%s\n", transformed.GetCString()); - else - result.GetOutputStream().Printf("%s\n", orig.GetCString()); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); - } + ~CommandObjectTargetModulesSearchPathsQuery() override = default; + +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) { + if (command.GetArgumentCount() != 1) { + result.AppendError("query requires one argument\n"); + result.SetStatus(eReturnStatusFailed); return result.Succeeded(); + } + + ConstString orig(command.GetArgumentAtIndex(0)); + ConstString transformed; + if (target->GetImageSearchPathList().RemapPath(orig, transformed)) + result.GetOutputStream().Printf("%s\n", transformed.GetCString()); + else + result.GetOutputStream().Printf("%s\n", orig.GetCString()); + + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; //---------------------------------------------------------------------- // Static Helper functions //---------------------------------------------------------------------- -static void -DumpModuleArchitecture (Stream &strm, Module *module, bool full_triple, uint32_t width) -{ - if (module) - { - StreamString arch_strm; - - if (full_triple) - module->GetArchitecture().DumpTriple(arch_strm); - else - arch_strm.PutCString(module->GetArchitecture().GetArchitectureName()); - std::string arch_str = arch_strm.GetString(); +static void DumpModuleArchitecture(Stream &strm, Module *module, + bool full_triple, uint32_t width) { + if (module) { + StreamString arch_strm; - if (width) - strm.Printf("%-*s", width, arch_str.c_str()); - else - strm.PutCString(arch_str.c_str()); - } -} + if (full_triple) + module->GetArchitecture().DumpTriple(arch_strm); + else + arch_strm.PutCString(module->GetArchitecture().GetArchitectureName()); + std::string arch_str = arch_strm.GetString(); -static void -DumpModuleUUID (Stream &strm, Module *module) -{ - if (module && module->GetUUID().IsValid()) - module->GetUUID().Dump (&strm); + if (width) + strm.Printf("%-*s", width, arch_str.c_str()); else - strm.PutCString(" "); + strm.PutCString(arch_str.c_str()); + } } -static uint32_t -DumpCompileUnitLineTable (CommandInterpreter &interpreter, - Stream &strm, - Module *module, - const FileSpec &file_spec, - bool load_addresses) -{ - uint32_t num_matches = 0; - if (module) - { - SymbolContextList sc_list; - num_matches = module->ResolveSymbolContextsForFileSpec (file_spec, - 0, - false, - eSymbolContextCompUnit, - sc_list); - - for (uint32_t i = 0; i < num_matches; ++i) - { - SymbolContext sc; - if (sc_list.GetContextAtIndex(i, sc)) - { - if (i > 0) - strm << "\n\n"; - - strm << "Line table for " << *static_cast (sc.comp_unit) << " in `" - << module->GetFileSpec().GetFilename() << "\n"; - LineTable *line_table = sc.comp_unit->GetLineTable(); - if (line_table) - line_table->GetDescription (&strm, - interpreter.GetExecutionContext().GetTargetPtr(), - lldb::eDescriptionLevelBrief); - else - strm << "No line table"; - } - } - } - return num_matches; +static void DumpModuleUUID(Stream &strm, Module *module) { + if (module && module->GetUUID().IsValid()) + module->GetUUID().Dump(&strm); + else + strm.PutCString(" "); } -static void -DumpFullpath (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width) -{ - if (file_spec_ptr) - { - if (width > 0) - { - std::string fullpath = file_spec_ptr->GetPath(); - strm.Printf("%-*s", width, fullpath.c_str()); - return; - } +static uint32_t DumpCompileUnitLineTable(CommandInterpreter &interpreter, + Stream &strm, Module *module, + const FileSpec &file_spec, + bool load_addresses) { + uint32_t num_matches = 0; + if (module) { + SymbolContextList sc_list; + num_matches = module->ResolveSymbolContextsForFileSpec( + file_spec, 0, false, eSymbolContextCompUnit, sc_list); + + for (uint32_t i = 0; i < num_matches; ++i) { + SymbolContext sc; + if (sc_list.GetContextAtIndex(i, sc)) { + if (i > 0) + strm << "\n\n"; + + strm << "Line table for " << *static_cast(sc.comp_unit) + << " in `" << module->GetFileSpec().GetFilename() << "\n"; + LineTable *line_table = sc.comp_unit->GetLineTable(); + if (line_table) + line_table->GetDescription( + &strm, interpreter.GetExecutionContext().GetTargetPtr(), + lldb::eDescriptionLevelBrief); else - { - file_spec_ptr->Dump(&strm); - return; - } + strm << "No line table"; + } } - // Keep the width spacing correct if things go wrong... - if (width > 0) - strm.Printf("%-*s", width, ""); + } + return num_matches; } -static void -DumpDirectory (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width) -{ - if (file_spec_ptr) - { - if (width > 0) - strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString("")); - else - file_spec_ptr->GetDirectory().Dump(&strm); - return; +static void DumpFullpath(Stream &strm, const FileSpec *file_spec_ptr, + uint32_t width) { + if (file_spec_ptr) { + if (width > 0) { + std::string fullpath = file_spec_ptr->GetPath(); + strm.Printf("%-*s", width, fullpath.c_str()); + return; + } else { + file_spec_ptr->Dump(&strm); + return; } - // Keep the width spacing correct if things go wrong... - if (width > 0) - strm.Printf("%-*s", width, ""); + } + // Keep the width spacing correct if things go wrong... + if (width > 0) + strm.Printf("%-*s", width, ""); } -static void -DumpBasename (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width) -{ - if (file_spec_ptr) - { - if (width > 0) - strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString("")); - else - file_spec_ptr->GetFilename().Dump(&strm); - return; - } - // Keep the width spacing correct if things go wrong... +static void DumpDirectory(Stream &strm, const FileSpec *file_spec_ptr, + uint32_t width) { + if (file_spec_ptr) { if (width > 0) - strm.Printf("%-*s", width, ""); + strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString("")); + else + file_spec_ptr->GetDirectory().Dump(&strm); + return; + } + // Keep the width spacing correct if things go wrong... + if (width > 0) + strm.Printf("%-*s", width, ""); } -static size_t -DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) -{ - size_t num_dumped = 0; - std::lock_guard guard(module_list.GetMutex()); - const size_t num_modules = module_list.GetSize(); - if (num_modules > 0) - { - strm.Printf("Dumping headers for %" PRIu64 " module(s).\n", static_cast(num_modules)); - strm.IndentMore(); - for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) - { - Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx); - if (module) - { - if (num_dumped++ > 0) - { - strm.EOL(); - strm.EOL(); - } - ObjectFile *objfile = module->GetObjectFile(); - objfile->Dump(&strm); - } - } - strm.IndentLess(); - } - return num_dumped; +static void DumpBasename(Stream &strm, const FileSpec *file_spec_ptr, + uint32_t width) { + if (file_spec_ptr) { + if (width > 0) + strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString("")); + else + file_spec_ptr->GetFilename().Dump(&strm); + return; + } + // Keep the width spacing correct if things go wrong... + if (width > 0) + strm.Printf("%-*s", width, ""); } -static void -DumpModuleSymtab (CommandInterpreter &interpreter, Stream &strm, Module *module, SortOrder sort_order) -{ - if (module) - { - SymbolVendor *sym_vendor = module->GetSymbolVendor (); - if (sym_vendor) - { - Symtab *symtab = sym_vendor->GetSymtab(); - if (symtab) - symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(), sort_order); +static size_t DumpModuleObjfileHeaders(Stream &strm, ModuleList &module_list) { + size_t num_dumped = 0; + std::lock_guard guard(module_list.GetMutex()); + const size_t num_modules = module_list.GetSize(); + if (num_modules > 0) { + strm.Printf("Dumping headers for %" PRIu64 " module(s).\n", + static_cast(num_modules)); + strm.IndentMore(); + for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { + Module *module = module_list.GetModulePointerAtIndexUnlocked(image_idx); + if (module) { + if (num_dumped++ > 0) { + strm.EOL(); + strm.EOL(); } + ObjectFile *objfile = module->GetObjectFile(); + objfile->Dump(&strm); + } } + strm.IndentLess(); + } + return num_dumped; } -static void -DumpModuleSections (CommandInterpreter &interpreter, Stream &strm, Module *module) -{ - if (module) - { - SectionList *section_list = module->GetSectionList(); - if (section_list) - { - strm.Printf ("Sections for '%s' (%s):\n", - module->GetSpecificationDescription().c_str(), - module->GetArchitecture().GetArchitectureName()); - strm.IndentMore(); - section_list->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(), true, UINT32_MAX); - strm.IndentLess(); - } +static void DumpModuleSymtab(CommandInterpreter &interpreter, Stream &strm, + Module *module, SortOrder sort_order) { + if (module) { + SymbolVendor *sym_vendor = module->GetSymbolVendor(); + if (sym_vendor) { + Symtab *symtab = sym_vendor->GetSymtab(); + if (symtab) + symtab->Dump(&strm, interpreter.GetExecutionContext().GetTargetPtr(), + sort_order); } + } } -static bool -DumpModuleSymbolVendor (Stream &strm, Module *module) -{ - if (module) - { - SymbolVendor *symbol_vendor = module->GetSymbolVendor(true); - if (symbol_vendor) - { - symbol_vendor->Dump(&strm); - return true; - } +static void DumpModuleSections(CommandInterpreter &interpreter, Stream &strm, + Module *module) { + if (module) { + SectionList *section_list = module->GetSectionList(); + if (section_list) { + strm.Printf("Sections for '%s' (%s):\n", + module->GetSpecificationDescription().c_str(), + module->GetArchitecture().GetArchitectureName()); + strm.IndentMore(); + section_list->Dump(&strm, + interpreter.GetExecutionContext().GetTargetPtr(), true, + UINT32_MAX); + strm.IndentLess(); } - return false; + } } -static void -DumpAddress (ExecutionContextScope *exe_scope, const Address &so_addr, bool verbose, Stream &strm) -{ - strm.IndentMore(); - strm.Indent (" Address: "); - so_addr.Dump (&strm, exe_scope, Address::DumpStyleModuleWithFileAddress); - strm.PutCString (" ("); - so_addr.Dump (&strm, exe_scope, Address::DumpStyleSectionNameOffset); - strm.PutCString (")\n"); - strm.Indent (" Summary: "); - const uint32_t save_indent = strm.GetIndentLevel (); - strm.SetIndentLevel (save_indent + 13); - so_addr.Dump (&strm, exe_scope, Address::DumpStyleResolvedDescription); - strm.SetIndentLevel (save_indent); - // Print out detailed address information when verbose is enabled - if (verbose) - { - strm.EOL(); - so_addr.Dump (&strm, exe_scope, Address::DumpStyleDetailedSymbolContext); +static bool DumpModuleSymbolVendor(Stream &strm, Module *module) { + if (module) { + SymbolVendor *symbol_vendor = module->GetSymbolVendor(true); + if (symbol_vendor) { + symbol_vendor->Dump(&strm); + return true; } - strm.IndentLess(); + } + return false; } -static bool -LookupAddressInModule (CommandInterpreter &interpreter, - Stream &strm, - Module *module, - uint32_t resolve_mask, - lldb::addr_t raw_addr, - lldb::addr_t offset, - bool verbose) -{ - if (module) - { - lldb::addr_t addr = raw_addr - offset; - Address so_addr; - SymbolContext sc; - Target *target = interpreter.GetExecutionContext().GetTargetPtr(); - if (target && !target->GetSectionLoadList().IsEmpty()) - { - if (!target->GetSectionLoadList().ResolveLoadAddress (addr, so_addr)) - return false; - else if (so_addr.GetModule().get() != module) - return false; - } - else - { - if (!module->ResolveFileAddress (addr, so_addr)) - return false; - } +static void DumpAddress(ExecutionContextScope *exe_scope, + const Address &so_addr, bool verbose, Stream &strm) { + strm.IndentMore(); + strm.Indent(" Address: "); + so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress); + strm.PutCString(" ("); + so_addr.Dump(&strm, exe_scope, Address::DumpStyleSectionNameOffset); + strm.PutCString(")\n"); + strm.Indent(" Summary: "); + const uint32_t save_indent = strm.GetIndentLevel(); + strm.SetIndentLevel(save_indent + 13); + so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription); + strm.SetIndentLevel(save_indent); + // Print out detailed address information when verbose is enabled + if (verbose) { + strm.EOL(); + so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext); + } + strm.IndentLess(); +} - ExecutionContextScope *exe_scope = interpreter.GetExecutionContext().GetBestExecutionContextScope(); - DumpAddress (exe_scope, so_addr, verbose, strm); -// strm.IndentMore(); -// strm.Indent (" Address: "); -// so_addr.Dump (&strm, exe_scope, Address::DumpStyleModuleWithFileAddress); -// strm.PutCString (" ("); -// so_addr.Dump (&strm, exe_scope, Address::DumpStyleSectionNameOffset); -// strm.PutCString (")\n"); -// strm.Indent (" Summary: "); -// const uint32_t save_indent = strm.GetIndentLevel (); -// strm.SetIndentLevel (save_indent + 13); -// so_addr.Dump (&strm, exe_scope, Address::DumpStyleResolvedDescription); -// strm.SetIndentLevel (save_indent); -// // Print out detailed address information when verbose is enabled -// if (verbose) -// { -// strm.EOL(); -// so_addr.Dump (&strm, exe_scope, Address::DumpStyleDetailedSymbolContext); -// } -// strm.IndentLess(); - return true; +static bool LookupAddressInModule(CommandInterpreter &interpreter, Stream &strm, + Module *module, uint32_t resolve_mask, + lldb::addr_t raw_addr, lldb::addr_t offset, + bool verbose) { + if (module) { + lldb::addr_t addr = raw_addr - offset; + Address so_addr; + SymbolContext sc; + Target *target = interpreter.GetExecutionContext().GetTargetPtr(); + if (target && !target->GetSectionLoadList().IsEmpty()) { + if (!target->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) + return false; + else if (so_addr.GetModule().get() != module) + return false; + } else { + if (!module->ResolveFileAddress(addr, so_addr)) + return false; } - return false; + ExecutionContextScope *exe_scope = + interpreter.GetExecutionContext().GetBestExecutionContextScope(); + DumpAddress(exe_scope, so_addr, verbose, strm); + // strm.IndentMore(); + // strm.Indent (" Address: "); + // so_addr.Dump (&strm, exe_scope, + // Address::DumpStyleModuleWithFileAddress); + // strm.PutCString (" ("); + // so_addr.Dump (&strm, exe_scope, + // Address::DumpStyleSectionNameOffset); + // strm.PutCString (")\n"); + // strm.Indent (" Summary: "); + // const uint32_t save_indent = strm.GetIndentLevel (); + // strm.SetIndentLevel (save_indent + 13); + // so_addr.Dump (&strm, exe_scope, + // Address::DumpStyleResolvedDescription); + // strm.SetIndentLevel (save_indent); + // // Print out detailed address information when verbose is enabled + // if (verbose) + // { + // strm.EOL(); + // so_addr.Dump (&strm, exe_scope, + // Address::DumpStyleDetailedSymbolContext); + // } + // strm.IndentLess(); + return true; + } + + return false; } -static uint32_t -LookupSymbolInModule (CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, bool verbose) -{ - if (module) - { - SymbolContext sc; - - SymbolVendor *sym_vendor = module->GetSymbolVendor (); - if (sym_vendor) - { - Symtab *symtab = sym_vendor->GetSymtab(); - if (symtab) - { - std::vector match_indexes; - ConstString symbol_name (name); - uint32_t num_matches = 0; - if (name_is_regex) - { - RegularExpression name_regexp(name); - num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType (name_regexp, - eSymbolTypeAny, - match_indexes); - } - else - { - num_matches = symtab->AppendSymbolIndexesWithName (symbol_name, match_indexes); - } +static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter, + Stream &strm, Module *module, + const char *name, bool name_is_regex, + bool verbose) { + if (module) { + SymbolContext sc; + + SymbolVendor *sym_vendor = module->GetSymbolVendor(); + if (sym_vendor) { + Symtab *symtab = sym_vendor->GetSymtab(); + if (symtab) { + std::vector match_indexes; + ConstString symbol_name(name); + uint32_t num_matches = 0; + if (name_is_regex) { + RegularExpression name_regexp(name); + num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType( + name_regexp, eSymbolTypeAny, match_indexes); + } else { + num_matches = + symtab->AppendSymbolIndexesWithName(symbol_name, match_indexes); + } - if (num_matches > 0) - { - strm.Indent (); - strm.Printf("%u symbols match %s'%s' in ", num_matches, - name_is_regex ? "the regular expression " : "", name); - DumpFullpath (strm, &module->GetFileSpec(), 0); - strm.PutCString(":\n"); - strm.IndentMore (); - for (uint32_t i = 0; i < num_matches; ++i) - { - Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]); - if (symbol && symbol->ValueIsAddress()) - { - DumpAddress (interpreter.GetExecutionContext().GetBestExecutionContextScope(), - symbol->GetAddressRef(), - verbose, - strm); - } - } - strm.IndentLess (); - return num_matches; - } + if (num_matches > 0) { + strm.Indent(); + strm.Printf("%u symbols match %s'%s' in ", num_matches, + name_is_regex ? "the regular expression " : "", name); + DumpFullpath(strm, &module->GetFileSpec(), 0); + strm.PutCString(":\n"); + strm.IndentMore(); + for (uint32_t i = 0; i < num_matches; ++i) { + Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]); + if (symbol && symbol->ValueIsAddress()) { + DumpAddress(interpreter.GetExecutionContext() + .GetBestExecutionContextScope(), + symbol->GetAddressRef(), verbose, strm); } + } + strm.IndentLess(); + return num_matches; } + } } - return 0; + } + return 0; } -static void -DumpSymbolContextList (ExecutionContextScope *exe_scope, Stream &strm, SymbolContextList &sc_list, bool verbose) -{ - strm.IndentMore (); +static void DumpSymbolContextList(ExecutionContextScope *exe_scope, + Stream &strm, SymbolContextList &sc_list, + bool verbose) { + strm.IndentMore(); - const uint32_t num_matches = sc_list.GetSize(); + const uint32_t num_matches = sc_list.GetSize(); - for (uint32_t i = 0; i < num_matches; ++i) - { - SymbolContext sc; - if (sc_list.GetContextAtIndex(i, sc)) - { - AddressRange range; + for (uint32_t i = 0; i < num_matches; ++i) { + SymbolContext sc; + if (sc_list.GetContextAtIndex(i, sc)) { + AddressRange range; - sc.GetAddressRange(eSymbolContextEverything, - 0, - true, - range); + sc.GetAddressRange(eSymbolContextEverything, 0, true, range); - DumpAddress (exe_scope, range.GetBaseAddress(), verbose, strm); - } + DumpAddress(exe_scope, range.GetBaseAddress(), verbose, strm); } - strm.IndentLess (); + } + strm.IndentLess(); } -static size_t -LookupFunctionInModule (CommandInterpreter &interpreter, - Stream &strm, - Module *module, - const char *name, - bool name_is_regex, - bool include_inlines, - bool include_symbols, - bool verbose) -{ - if (module && name && name[0]) - { - SymbolContextList sc_list; - const bool append = true; - size_t num_matches = 0; - if (name_is_regex) - { - RegularExpression function_name_regex (name); - num_matches = module->FindFunctions (function_name_regex, - include_symbols, - include_inlines, - append, - sc_list); - } - else - { - ConstString function_name (name); - num_matches = module->FindFunctions(function_name, - nullptr, - eFunctionNameTypeAuto, - include_symbols, - include_inlines, - append, - sc_list); - } - - if (num_matches) - { - strm.Indent (); - strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, num_matches > 1 ? "es" : ""); - DumpFullpath (strm, &module->GetFileSpec(), 0); - strm.PutCString(":\n"); - DumpSymbolContextList (interpreter.GetExecutionContext().GetBestExecutionContextScope(), strm, sc_list, verbose); - } - return num_matches; +static size_t LookupFunctionInModule(CommandInterpreter &interpreter, + Stream &strm, Module *module, + const char *name, bool name_is_regex, + bool include_inlines, bool include_symbols, + bool verbose) { + if (module && name && name[0]) { + SymbolContextList sc_list; + const bool append = true; + size_t num_matches = 0; + if (name_is_regex) { + RegularExpression function_name_regex(name); + num_matches = module->FindFunctions(function_name_regex, include_symbols, + include_inlines, append, sc_list); + } else { + ConstString function_name(name); + num_matches = module->FindFunctions( + function_name, nullptr, eFunctionNameTypeAuto, include_symbols, + include_inlines, append, sc_list); } - return 0; -} - -static size_t -LookupTypeInModule (CommandInterpreter &interpreter, - Stream &strm, - Module *module, - const char *name_cstr, - bool name_is_regex) -{ - if (module && name_cstr && name_cstr[0]) - { - TypeList type_list; - const uint32_t max_num_matches = UINT32_MAX; - size_t num_matches = 0; - bool name_is_fully_qualified = false; - SymbolContext sc; - - ConstString name(name_cstr); - llvm::DenseSet searched_symbol_files; - num_matches = module->FindTypes(sc, name, name_is_fully_qualified, max_num_matches, searched_symbol_files, type_list); - if (num_matches) - { - strm.Indent (); - strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, num_matches > 1 ? "es" : ""); - DumpFullpath (strm, &module->GetFileSpec(), 0); - strm.PutCString(":\n"); - for (TypeSP type_sp : type_list.Types()) - { - if (type_sp) - { - // Resolve the clang type so that any forward references - // to types that haven't yet been parsed will get parsed. - type_sp->GetFullCompilerType (); - type_sp->GetDescription (&strm, eDescriptionLevelFull, true); - // Print all typedef chains - TypeSP typedef_type_sp (type_sp); - TypeSP typedefed_type_sp (typedef_type_sp->GetTypedefType()); - while (typedefed_type_sp) - { - strm.EOL(); - strm.Printf(" typedef '%s': ", typedef_type_sp->GetName().GetCString()); - typedefed_type_sp->GetFullCompilerType (); - typedefed_type_sp->GetDescription (&strm, eDescriptionLevelFull, true); - typedef_type_sp = typedefed_type_sp; - typedefed_type_sp = typedef_type_sp->GetTypedefType(); - } - } - strm.EOL(); - } - } - return num_matches; + if (num_matches) { + strm.Indent(); + strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, + num_matches > 1 ? "es" : ""); + DumpFullpath(strm, &module->GetFileSpec(), 0); + strm.PutCString(":\n"); + DumpSymbolContextList( + interpreter.GetExecutionContext().GetBestExecutionContextScope(), + strm, sc_list, verbose); } - return 0; + return num_matches; + } + return 0; } -static size_t -LookupTypeHere (CommandInterpreter &interpreter, - Stream &strm, - const SymbolContext &sym_ctx, - const char *name_cstr, - bool name_is_regex) -{ - if (!sym_ctx.module_sp) - return 0; - +static size_t LookupTypeInModule(CommandInterpreter &interpreter, Stream &strm, + Module *module, const char *name_cstr, + bool name_is_regex) { + if (module && name_cstr && name_cstr[0]) { TypeList type_list; const uint32_t max_num_matches = UINT32_MAX; - size_t num_matches = 1; + size_t num_matches = 0; bool name_is_fully_qualified = false; + SymbolContext sc; ConstString name(name_cstr); - llvm::DenseSet searched_symbol_files; - num_matches = sym_ctx.module_sp->FindTypes(sym_ctx, name, name_is_fully_qualified, max_num_matches, searched_symbol_files, type_list); - - if (num_matches) - { - strm.Indent (); - strm.PutCString("Best match found in "); - DumpFullpath (strm, &sym_ctx.module_sp->GetFileSpec(), 0); - strm.PutCString(":\n"); - - TypeSP type_sp (type_list.GetTypeAtIndex(0)); - if (type_sp) - { - // Resolve the clang type so that any forward references - // to types that haven't yet been parsed will get parsed. - type_sp->GetFullCompilerType (); - type_sp->GetDescription (&strm, eDescriptionLevelFull, true); - // Print all typedef chains - TypeSP typedef_type_sp (type_sp); - TypeSP typedefed_type_sp (typedef_type_sp->GetTypedefType()); - while (typedefed_type_sp) - { - strm.EOL(); - strm.Printf(" typedef '%s': ", typedef_type_sp->GetName().GetCString()); - typedefed_type_sp->GetFullCompilerType (); - typedefed_type_sp->GetDescription (&strm, eDescriptionLevelFull, true); - typedef_type_sp = typedefed_type_sp; - typedefed_type_sp = typedef_type_sp->GetTypedefType(); - } + llvm::DenseSet searched_symbol_files; + num_matches = + module->FindTypes(sc, name, name_is_fully_qualified, max_num_matches, + searched_symbol_files, type_list); + + if (num_matches) { + strm.Indent(); + strm.Printf("%" PRIu64 " match%s found in ", (uint64_t)num_matches, + num_matches > 1 ? "es" : ""); + DumpFullpath(strm, &module->GetFileSpec(), 0); + strm.PutCString(":\n"); + for (TypeSP type_sp : type_list.Types()) { + if (type_sp) { + // Resolve the clang type so that any forward references + // to types that haven't yet been parsed will get parsed. + type_sp->GetFullCompilerType(); + type_sp->GetDescription(&strm, eDescriptionLevelFull, true); + // Print all typedef chains + TypeSP typedef_type_sp(type_sp); + TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType()); + while (typedefed_type_sp) { + strm.EOL(); + strm.Printf(" typedef '%s': ", + typedef_type_sp->GetName().GetCString()); + typedefed_type_sp->GetFullCompilerType(); + typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, + true); + typedef_type_sp = typedefed_type_sp; + typedefed_type_sp = typedef_type_sp->GetTypedefType(); + } } strm.EOL(); + } } return num_matches; + } + return 0; } -static uint32_t -LookupFileAndLineInModule (CommandInterpreter &interpreter, - Stream &strm, - Module *module, - const FileSpec &file_spec, - uint32_t line, - bool check_inlines, - bool verbose) -{ - if (module && file_spec) - { - SymbolContextList sc_list; - const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines, - eSymbolContextEverything, sc_list); - if (num_matches > 0) - { - strm.Indent (); - strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : ""); - strm << file_spec; - if (line > 0) - strm.Printf (":%u", line); - strm << " in "; - DumpFullpath (strm, &module->GetFileSpec(), 0); - strm.PutCString(":\n"); - DumpSymbolContextList (interpreter.GetExecutionContext().GetBestExecutionContextScope(), strm, sc_list, verbose); - return num_matches; - } - } +static size_t LookupTypeHere(CommandInterpreter &interpreter, Stream &strm, + const SymbolContext &sym_ctx, + const char *name_cstr, bool name_is_regex) { + if (!sym_ctx.module_sp) return 0; + + TypeList type_list; + const uint32_t max_num_matches = UINT32_MAX; + size_t num_matches = 1; + bool name_is_fully_qualified = false; + + ConstString name(name_cstr); + llvm::DenseSet searched_symbol_files; + num_matches = sym_ctx.module_sp->FindTypes( + sym_ctx, name, name_is_fully_qualified, max_num_matches, + searched_symbol_files, type_list); + + if (num_matches) { + strm.Indent(); + strm.PutCString("Best match found in "); + DumpFullpath(strm, &sym_ctx.module_sp->GetFileSpec(), 0); + strm.PutCString(":\n"); + + TypeSP type_sp(type_list.GetTypeAtIndex(0)); + if (type_sp) { + // Resolve the clang type so that any forward references + // to types that haven't yet been parsed will get parsed. + type_sp->GetFullCompilerType(); + type_sp->GetDescription(&strm, eDescriptionLevelFull, true); + // Print all typedef chains + TypeSP typedef_type_sp(type_sp); + TypeSP typedefed_type_sp(typedef_type_sp->GetTypedefType()); + while (typedefed_type_sp) { + strm.EOL(); + strm.Printf(" typedef '%s': ", + typedef_type_sp->GetName().GetCString()); + typedefed_type_sp->GetFullCompilerType(); + typedefed_type_sp->GetDescription(&strm, eDescriptionLevelFull, true); + typedef_type_sp = typedefed_type_sp; + typedefed_type_sp = typedef_type_sp->GetTypedefType(); + } + } + strm.EOL(); + } + return num_matches; } -static size_t -FindModulesByName (Target *target, - const char *module_name, - ModuleList &module_list, - bool check_global_list) -{ - FileSpec module_file_spec(module_name, false); - ModuleSpec module_spec (module_file_spec); - - const size_t initial_size = module_list.GetSize (); - - if (check_global_list) - { - // Check the global list - std::lock_guard guard(Module::GetAllocationModuleCollectionMutex()); - const size_t num_modules = Module::GetNumberAllocatedModules(); - ModuleSP module_sp; - for (size_t image_idx = 0; image_idxMatchesModuleSpec (module_spec)) - { - module_sp = module->shared_from_this(); - module_list.AppendIfNeeded(module_sp); - } - } - } +static uint32_t LookupFileAndLineInModule(CommandInterpreter &interpreter, + Stream &strm, Module *module, + const FileSpec &file_spec, + uint32_t line, bool check_inlines, + bool verbose) { + if (module && file_spec) { + SymbolContextList sc_list; + const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec( + file_spec, line, check_inlines, eSymbolContextEverything, sc_list); + if (num_matches > 0) { + strm.Indent(); + strm.Printf("%u match%s found in ", num_matches, + num_matches > 1 ? "es" : ""); + strm << file_spec; + if (line > 0) + strm.Printf(":%u", line); + strm << " in "; + DumpFullpath(strm, &module->GetFileSpec(), 0); + strm.PutCString(":\n"); + DumpSymbolContextList( + interpreter.GetExecutionContext().GetBestExecutionContextScope(), + strm, sc_list, verbose); + return num_matches; } - else - { - if (target) - { - const size_t num_matches = target->GetImages().FindModules (module_spec, module_list); + } + return 0; +} - // Not found in our module list for our target, check the main - // shared module list in case it is a extra file used somewhere - // else - if (num_matches == 0) - { - module_spec.GetArchitecture() = target->GetArchitecture(); - ModuleList::FindSharedModules (module_spec, module_list); - } - } - else - { - ModuleList::FindSharedModules (module_spec,module_list); +static size_t FindModulesByName(Target *target, const char *module_name, + ModuleList &module_list, + bool check_global_list) { + FileSpec module_file_spec(module_name, false); + ModuleSpec module_spec(module_file_spec); + + const size_t initial_size = module_list.GetSize(); + + if (check_global_list) { + // Check the global list + std::lock_guard guard( + Module::GetAllocationModuleCollectionMutex()); + const size_t num_modules = Module::GetNumberAllocatedModules(); + ModuleSP module_sp; + for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { + Module *module = Module::GetAllocatedModuleAtIndex(image_idx); + + if (module) { + if (module->MatchesModuleSpec(module_spec)) { + module_sp = module->shared_from_this(); + module_list.AppendIfNeeded(module_sp); } + } + } + } else { + if (target) { + const size_t num_matches = + target->GetImages().FindModules(module_spec, module_list); + + // Not found in our module list for our target, check the main + // shared module list in case it is a extra file used somewhere + // else + if (num_matches == 0) { + module_spec.GetArchitecture() = target->GetArchitecture(); + ModuleList::FindSharedModules(module_spec, module_list); + } + } else { + ModuleList::FindSharedModules(module_spec, module_list); } + } - return module_list.GetSize () - initial_size; + return module_list.GetSize() - initial_size; } #pragma mark CommandObjectTargetModulesModuleAutoComplete @@ -2029,55 +1780,47 @@ FindModulesByName (Target *target, // paths //---------------------------------------------------------------------- -class CommandObjectTargetModulesModuleAutoComplete : public CommandObjectParsed -{ +class CommandObjectTargetModulesModuleAutoComplete + : public CommandObjectParsed { public: - CommandObjectTargetModulesModuleAutoComplete (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax) : - CommandObjectParsed (interpreter, name, help, syntax) - { - CommandArgumentEntry arg; - CommandArgumentData file_arg; - - // Define the first (and only) variant of this arg. - file_arg.arg_type = eArgTypeFilename; - file_arg.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (file_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectTargetModulesModuleAutoComplete() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - // Arguments are the standard module completer. - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eModuleCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + CommandObjectTargetModulesModuleAutoComplete(CommandInterpreter &interpreter, + const char *name, + const char *help, + const char *syntax) + : CommandObjectParsed(interpreter, name, help, syntax) { + CommandArgumentEntry arg; + CommandArgumentData file_arg; + + // Define the first (and only) variant of this arg. + file_arg.arg_type = eArgTypeFilename; + file_arg.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(file_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectTargetModulesModuleAutoComplete() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + // Arguments are the standard module completer. + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eModuleCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } }; #pragma mark CommandObjectTargetModulesSourceFileAutoComplete @@ -2087,311 +1830,260 @@ public: // file paths //---------------------------------------------------------------------- -class CommandObjectTargetModulesSourceFileAutoComplete : public CommandObjectParsed -{ +class CommandObjectTargetModulesSourceFileAutoComplete + : public CommandObjectParsed { public: - CommandObjectTargetModulesSourceFileAutoComplete (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax, - uint32_t flags) : - CommandObjectParsed (interpreter, name, help, syntax, flags) - { - CommandArgumentEntry arg; - CommandArgumentData source_file_arg; - - // Define the first (and only) variant of this arg. - source_file_arg.arg_type = eArgTypeSourceFile; - source_file_arg.arg_repetition = eArgRepeatPlus; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (source_file_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectTargetModulesSourceFileAutoComplete() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - // Arguments are the standard source file completer. - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eSourceFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + CommandObjectTargetModulesSourceFileAutoComplete( + CommandInterpreter &interpreter, const char *name, const char *help, + const char *syntax, uint32_t flags) + : CommandObjectParsed(interpreter, name, help, syntax, flags) { + CommandArgumentEntry arg; + CommandArgumentData source_file_arg; + + // Define the first (and only) variant of this arg. + source_file_arg.arg_type = eArgTypeSourceFile; + source_file_arg.arg_repetition = eArgRepeatPlus; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(source_file_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectTargetModulesSourceFileAutoComplete() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + // Arguments are the standard source file completer. + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eSourceFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } }; #pragma mark CommandObjectTargetModulesDumpObjfile -class CommandObjectTargetModulesDumpObjfile : public CommandObjectTargetModulesModuleAutoComplete -{ +class CommandObjectTargetModulesDumpObjfile + : public CommandObjectTargetModulesModuleAutoComplete { public: - CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter) - : CommandObjectTargetModulesModuleAutoComplete(interpreter, "target modules dump objfile", - "Dump the object file headers from one or more target modules.", - nullptr) - { - } + CommandObjectTargetModulesDumpObjfile(CommandInterpreter &interpreter) + : CommandObjectTargetModulesModuleAutoComplete( + interpreter, "target modules dump objfile", + "Dump the object file headers from one or more target modules.", + nullptr) {} - ~CommandObjectTargetModulesDumpObjfile() override = default; + ~CommandObjectTargetModulesDumpObjfile() override = default; protected: - bool - DoExecute(Args &command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError("invalid target, create a debug target using the 'target create' command"); - result.SetStatus(eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); - size_t num_dumped = 0; - if (command.GetArgumentCount() == 0) - { - // Dump all headers for all modules images - num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(), target->GetImages()); - if (num_dumped == 0) - { - result.AppendError("the target has no associated executable images"); - result.SetStatus(eReturnStatusFailed); - } - } - else - { - // Find the modules that match the basename or full path. - ModuleList module_list; - const char *arg_cstr; - for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) - { - size_t num_matched = FindModulesByName(target, arg_cstr, module_list, true); - if (num_matched == 0) - { - result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr); - } - } - // Dump all the modules we found. - num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(), module_list); + size_t num_dumped = 0; + if (command.GetArgumentCount() == 0) { + // Dump all headers for all modules images + num_dumped = DumpModuleObjfileHeaders(result.GetOutputStream(), + target->GetImages()); + if (num_dumped == 0) { + result.AppendError("the target has no associated executable images"); + result.SetStatus(eReturnStatusFailed); + } + } else { + // Find the modules that match the basename or full path. + ModuleList module_list; + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + size_t num_matched = + FindModulesByName(target, arg_cstr, module_list, true); + if (num_matched == 0) { + result.AppendWarningWithFormat( + "Unable to find an image that matches '%s'.\n", arg_cstr); } + } + // Dump all the modules we found. + num_dumped = + DumpModuleObjfileHeaders(result.GetOutputStream(), module_list); + } - if (num_dumped > 0) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError("no matching executable images found"); - result.SetStatus(eReturnStatusFailed); - } - return result.Succeeded(); + if (num_dumped > 0) { + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("no matching executable images found"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesDumpSymtab -class CommandObjectTargetModulesDumpSymtab : public CommandObjectTargetModulesModuleAutoComplete -{ +class CommandObjectTargetModulesDumpSymtab + : public CommandObjectTargetModulesModuleAutoComplete { public: - CommandObjectTargetModulesDumpSymtab (CommandInterpreter &interpreter) : - CommandObjectTargetModulesModuleAutoComplete(interpreter, - "target modules dump symtab", - "Dump the symbol table from one or more target modules.", - nullptr), - m_options() - { + CommandObjectTargetModulesDumpSymtab(CommandInterpreter &interpreter) + : CommandObjectTargetModulesModuleAutoComplete( + interpreter, "target modules dump symtab", + "Dump the symbol table from one or more target modules.", nullptr), + m_options() {} + + ~CommandObjectTargetModulesDumpSymtab() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_sort_order(eSortOrderNone) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 's': + m_sort_order = (SortOrder)Args::StringToOptionEnum( + option_arg, g_option_table[option_idx].enum_values, eSortOrderNone, + error); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; } - ~CommandObjectTargetModulesDumpSymtab() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_sort_order = eSortOrderNone; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_sort_order(eSortOrderNone) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 's': - m_sort_order = (SortOrder) Args::StringToOptionEnum (option_arg, - g_option_table[option_idx].enum_values, - eSortOrderNone, - error); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_sort_order = eSortOrderNone; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + // Options table: Required for subclasses of Options. + static OptionDefinition g_option_table[]; - SortOrder m_sort_order; - }; + SortOrder m_sort_order; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - uint32_t num_dumped = 0; - - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - - if (command.GetArgumentCount() == 0) - { - // Dump all sections for all modules images - std::lock_guard guard(target->GetImages().GetMutex()); - const size_t num_modules = target->GetImages().GetSize(); - if (num_modules > 0) - { - result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64 " modules.\n", (uint64_t)num_modules); - for (size_t image_idx = 0; image_idx 0) - { - result.GetOutputStream().EOL(); - result.GetOutputStream().EOL(); - } - num_dumped++; - DumpModuleSymtab (m_interpreter, - result.GetOutputStream(), - target->GetImages().GetModulePointerAtIndexUnlocked(image_idx), - m_options.m_sort_order); - } - } - else - { - result.AppendError ("the target has no associated executable images"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + uint32_t num_dumped = 0; + + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + + if (command.GetArgumentCount() == 0) { + // Dump all sections for all modules images + std::lock_guard guard( + target->GetImages().GetMutex()); + const size_t num_modules = target->GetImages().GetSize(); + if (num_modules > 0) { + result.GetOutputStream().Printf("Dumping symbol table for %" PRIu64 + " modules.\n", + (uint64_t)num_modules); + for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { + if (num_dumped > 0) { + result.GetOutputStream().EOL(); + result.GetOutputStream().EOL(); } - else - { - // Dump specified images (by basename or fullpath) - const char *arg_cstr; - for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) - { - ModuleList module_list; - const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, true); - if (num_matches > 0) - { - for (size_t i = 0; i < num_matches; ++i) - { - Module *module = module_list.GetModulePointerAtIndex(i); - if (module) - { - if (num_dumped > 0) - { - result.GetOutputStream().EOL(); - result.GetOutputStream().EOL(); - } - num_dumped++; - DumpModuleSymtab (m_interpreter, result.GetOutputStream(), module, m_options.m_sort_order); - } - } - } - else - result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr); + num_dumped++; + DumpModuleSymtab( + m_interpreter, result.GetOutputStream(), + target->GetImages().GetModulePointerAtIndexUnlocked(image_idx), + m_options.m_sort_order); + } + } else { + result.AppendError("the target has no associated executable images"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + // Dump specified images (by basename or fullpath) + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + ModuleList module_list; + const size_t num_matches = + FindModulesByName(target, arg_cstr, module_list, true); + if (num_matches > 0) { + for (size_t i = 0; i < num_matches; ++i) { + Module *module = module_list.GetModulePointerAtIndex(i); + if (module) { + if (num_dumped > 0) { + result.GetOutputStream().EOL(); + result.GetOutputStream().EOL(); } + num_dumped++; + DumpModuleSymtab(m_interpreter, result.GetOutputStream(), + module, m_options.m_sort_order); + } } - - if (num_dumped > 0) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - { - result.AppendError ("no matching executable images found"); - result.SetStatus (eReturnStatusFailed); - } + } else + result.AppendWarningWithFormat( + "Unable to find an image that matches '%s'.\n", arg_cstr); } - return result.Succeeded(); + } + + if (num_dumped > 0) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.AppendError("no matching executable images found"); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -static OptionEnumValueElement -g_sort_option_enumeration[4] = -{ - { eSortOrderNone, "none", "No sorting, use the original symbol table order."}, - { eSortOrderByAddress, "address", "Sort output by symbol address."}, - { eSortOrderByName, "name", "Sort output by symbol name."}, - { 0, nullptr, nullptr } -}; +static OptionEnumValueElement g_sort_option_enumeration[4] = { + {eSortOrderNone, "none", + "No sorting, use the original symbol table order."}, + {eSortOrderByAddress, "address", "Sort output by symbol address."}, + {eSortOrderByName, "name", "Sort output by symbol name."}, + {0, nullptr, nullptr}}; OptionDefinition -CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "sort", 's', OptionParser::eRequiredArgument, nullptr, g_sort_option_enumeration, 0, eArgTypeSortOrder, "Supply a sort order when dumping the symbol table."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectTargetModulesDumpSections @@ -2400,99 +2092,89 @@ CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] = // Image section dumping command //---------------------------------------------------------------------- -class CommandObjectTargetModulesDumpSections : public CommandObjectTargetModulesModuleAutoComplete -{ +class CommandObjectTargetModulesDumpSections + : public CommandObjectTargetModulesModuleAutoComplete { public: - CommandObjectTargetModulesDumpSections (CommandInterpreter &interpreter) : - CommandObjectTargetModulesModuleAutoComplete(interpreter, - "target modules dump sections", - "Dump the sections from one or more target modules.", - //"target modules dump sections [ ...]") - nullptr) - { - } + CommandObjectTargetModulesDumpSections(CommandInterpreter &interpreter) + : CommandObjectTargetModulesModuleAutoComplete( + interpreter, "target modules dump sections", + "Dump the sections from one or more target modules.", + //"target modules dump sections [ ...]") + nullptr) {} - ~CommandObjectTargetModulesDumpSections() override = default; + ~CommandObjectTargetModulesDumpSections() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + uint32_t num_dumped = 0; + + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + + if (command.GetArgumentCount() == 0) { + // Dump all sections for all modules images + const size_t num_modules = target->GetImages().GetSize(); + if (num_modules > 0) { + result.GetOutputStream().Printf("Dumping sections for %" PRIu64 + " modules.\n", + (uint64_t)num_modules); + for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) { + num_dumped++; + DumpModuleSections( + m_interpreter, result.GetOutputStream(), + target->GetImages().GetModulePointerAtIndex(image_idx)); + } + } else { + result.AppendError("the target has no associated executable images"); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - uint32_t num_dumped = 0; - - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - - if (command.GetArgumentCount() == 0) - { - // Dump all sections for all modules images - const size_t num_modules = target->GetImages().GetSize(); - if (num_modules > 0) - { - result.GetOutputStream().Printf("Dumping sections for %" PRIu64 " modules.\n", (uint64_t)num_modules); - for (size_t image_idx = 0; image_idxGetImages().GetModulePointerAtIndex(image_idx)); - } - } - else - { - result.AppendError ("the target has no associated executable images"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - // Dump specified images (by basename or fullpath) - const char *arg_cstr; - for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) - { - ModuleList module_list; - const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, true); - if (num_matches > 0) - { - for (size_t i = 0; i < num_matches; ++i) - { - Module *module = module_list.GetModulePointerAtIndex(i); - if (module) - { - num_dumped++; - DumpModuleSections (m_interpreter, result.GetOutputStream(), module); - } - } - } - else - { - // Check the global list - std::lock_guard guard(Module::GetAllocationModuleCollectionMutex()); - - result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr); - } - } - } - - if (num_dumped > 0) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - { - result.AppendError ("no matching executable images found"); - result.SetStatus (eReturnStatusFailed); + } else { + // Dump specified images (by basename or fullpath) + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + ModuleList module_list; + const size_t num_matches = + FindModulesByName(target, arg_cstr, module_list, true); + if (num_matches > 0) { + for (size_t i = 0; i < num_matches; ++i) { + Module *module = module_list.GetModulePointerAtIndex(i); + if (module) { + num_dumped++; + DumpModuleSections(m_interpreter, result.GetOutputStream(), + module); + } } + } else { + // Check the global list + std::lock_guard guard( + Module::GetAllocationModuleCollectionMutex()); + + result.AppendWarningWithFormat( + "Unable to find an image that matches '%s'.\n", arg_cstr); + } } - return result.Succeeded(); + } + + if (num_dumped > 0) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.AppendError("no matching executable images found"); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesDumpSymfile @@ -2501,96 +2183,85 @@ protected: // Image debug symbol dumping command //---------------------------------------------------------------------- -class CommandObjectTargetModulesDumpSymfile : public CommandObjectTargetModulesModuleAutoComplete -{ +class CommandObjectTargetModulesDumpSymfile + : public CommandObjectTargetModulesModuleAutoComplete { public: - CommandObjectTargetModulesDumpSymfile (CommandInterpreter &interpreter) : - CommandObjectTargetModulesModuleAutoComplete(interpreter, - "target modules dump symfile", - "Dump the debug symbol file for one or more target modules.", - //"target modules dump symfile [ ...]") - nullptr) - { - } + CommandObjectTargetModulesDumpSymfile(CommandInterpreter &interpreter) + : CommandObjectTargetModulesModuleAutoComplete( + interpreter, "target modules dump symfile", + "Dump the debug symbol file for one or more target modules.", + //"target modules dump symfile [ ...]") + nullptr) {} - ~CommandObjectTargetModulesDumpSymfile() override = default; + ~CommandObjectTargetModulesDumpSymfile() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + uint32_t num_dumped = 0; + + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + + if (command.GetArgumentCount() == 0) { + // Dump all sections for all modules images + const ModuleList &target_modules = target->GetImages(); + std::lock_guard guard(target_modules.GetMutex()); + const size_t num_modules = target_modules.GetSize(); + if (num_modules > 0) { + result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64 + " modules.\n", + (uint64_t)num_modules); + for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) { + if (DumpModuleSymbolVendor( + result.GetOutputStream(), + target_modules.GetModulePointerAtIndexUnlocked(image_idx))) + num_dumped++; + } + } else { + result.AppendError("the target has no associated executable images"); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - uint32_t num_dumped = 0; - - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - - if (command.GetArgumentCount() == 0) - { - // Dump all sections for all modules images - const ModuleList &target_modules = target->GetImages(); - std::lock_guard guard(target_modules.GetMutex()); - const size_t num_modules = target_modules.GetSize(); - if (num_modules > 0) - { - result.GetOutputStream().Printf("Dumping debug symbols for %" PRIu64 " modules.\n", (uint64_t)num_modules); - for (uint32_t image_idx = 0; image_idx 0) - { - for (size_t i = 0; i < num_matches; ++i) - { - Module *module = module_list.GetModulePointerAtIndex(i); - if (module) - { - if (DumpModuleSymbolVendor (result.GetOutputStream(), module)) - num_dumped++; - } - } - } - else - result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr); - } - } - - if (num_dumped > 0) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - { - result.AppendError ("no matching executable images found"); - result.SetStatus (eReturnStatusFailed); + } else { + // Dump specified images (by basename or fullpath) + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + ModuleList module_list; + const size_t num_matches = + FindModulesByName(target, arg_cstr, module_list, true); + if (num_matches > 0) { + for (size_t i = 0; i < num_matches; ++i) { + Module *module = module_list.GetModulePointerAtIndex(i); + if (module) { + if (DumpModuleSymbolVendor(result.GetOutputStream(), module)) + num_dumped++; + } } + } else + result.AppendWarningWithFormat( + "Unable to find an image that matches '%s'.\n", arg_cstr); } - return result.Succeeded(); + } + + if (num_dumped > 0) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.AppendError("no matching executable images found"); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesDumpLineTable @@ -2599,77 +2270,68 @@ protected: // Image debug line table dumping command //---------------------------------------------------------------------- -class CommandObjectTargetModulesDumpLineTable : public CommandObjectTargetModulesSourceFileAutoComplete -{ +class CommandObjectTargetModulesDumpLineTable + : public CommandObjectTargetModulesSourceFileAutoComplete { public: - CommandObjectTargetModulesDumpLineTable (CommandInterpreter &interpreter) : - CommandObjectTargetModulesSourceFileAutoComplete(interpreter, - "target modules dump line-table", - "Dump the line table for one or more compilation units.", - nullptr, - eCommandRequiresTarget) - { - } + CommandObjectTargetModulesDumpLineTable(CommandInterpreter &interpreter) + : CommandObjectTargetModulesSourceFileAutoComplete( + interpreter, "target modules dump line-table", + "Dump the line table for one or more compilation units.", nullptr, + eCommandRequiresTarget) {} - ~CommandObjectTargetModulesDumpLineTable() override = default; + ~CommandObjectTargetModulesDumpLineTable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_exe_ctx.GetTargetPtr(); - uint32_t total_num_dumped = 0; - - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - - if (command.GetArgumentCount() == 0) - { - result.AppendError ("file option must be specified."); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } - else - { - // Dump specified images (by basename or fullpath) - const char *arg_cstr; - for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) - { - FileSpec file_spec(arg_cstr, false); - - const ModuleList &target_modules = target->GetImages(); - std::lock_guard guard(target_modules.GetMutex()); - const size_t num_modules = target_modules.GetSize(); - if (num_modules > 0) - { - uint32_t num_dumped = 0; - for (uint32_t i = 0; iGetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + + if (command.GetArgumentCount() == 0) { + result.AppendError("file option must be specified."); + result.SetStatus(eReturnStatusFailed); + return result.Succeeded(); + } else { + // Dump specified images (by basename or fullpath) + const char *arg_cstr; + for (int arg_idx = 0; + (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; + ++arg_idx) { + FileSpec file_spec(arg_cstr, false); + + const ModuleList &target_modules = target->GetImages(); + std::lock_guard guard(target_modules.GetMutex()); + const size_t num_modules = target_modules.GetSize(); + if (num_modules > 0) { + uint32_t num_dumped = 0; + for (uint32_t i = 0; i < num_modules; ++i) { + if (DumpCompileUnitLineTable( + m_interpreter, result.GetOutputStream(), + target_modules.GetModulePointerAtIndexUnlocked(i), + file_spec, m_exe_ctx.GetProcessPtr() && + m_exe_ctx.GetProcessRef().IsAlive())) + num_dumped++; + } + if (num_dumped == 0) + result.AppendWarningWithFormat( + "No source filenames matched '%s'.\n", arg_cstr); + else + total_num_dumped += num_dumped; } + } + } - if (total_num_dumped > 0) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - { - result.AppendError ("no source filenames matched any command arguments"); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + if (total_num_dumped > 0) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.AppendError("no source filenames matched any command arguments"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetModulesDump @@ -2678,889 +2340,784 @@ protected: // Dump multi-word command for target modules //---------------------------------------------------------------------- -class CommandObjectTargetModulesDump : public CommandObjectMultiword -{ +class CommandObjectTargetModulesDump : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectTargetModulesDump(CommandInterpreter &interpreter) - : CommandObjectMultiword( - interpreter, "target modules dump", "Commands for dumping information about one or more target modules.", - "target modules dump [headers|symtab|sections|symfile|line-table] [ ...]") - { - LoadSubCommand("objfile", CommandObjectSP(new CommandObjectTargetModulesDumpObjfile(interpreter))); - LoadSubCommand ("symtab", CommandObjectSP (new CommandObjectTargetModulesDumpSymtab (interpreter))); - LoadSubCommand ("sections", CommandObjectSP (new CommandObjectTargetModulesDumpSections (interpreter))); - LoadSubCommand ("symfile", CommandObjectSP (new CommandObjectTargetModulesDumpSymfile (interpreter))); - LoadSubCommand ("line-table", CommandObjectSP (new CommandObjectTargetModulesDumpLineTable (interpreter))); - } - - ~CommandObjectTargetModulesDump() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectTargetModulesDump(CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "target modules dump", + "Commands for dumping information about one or " + "more target modules.", + "target modules dump " + "[headers|symtab|sections|symfile|line-table] " + "[ ...]") { + LoadSubCommand("objfile", + CommandObjectSP( + new CommandObjectTargetModulesDumpObjfile(interpreter))); + LoadSubCommand( + "symtab", + CommandObjectSP(new CommandObjectTargetModulesDumpSymtab(interpreter))); + LoadSubCommand("sections", + CommandObjectSP(new CommandObjectTargetModulesDumpSections( + interpreter))); + LoadSubCommand("symfile", + CommandObjectSP( + new CommandObjectTargetModulesDumpSymfile(interpreter))); + LoadSubCommand("line-table", + CommandObjectSP(new CommandObjectTargetModulesDumpLineTable( + interpreter))); + } + + ~CommandObjectTargetModulesDump() override = default; }; -class CommandObjectTargetModulesAdd : public CommandObjectParsed -{ +class CommandObjectTargetModulesAdd : public CommandObjectParsed { public: - CommandObjectTargetModulesAdd (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target modules add", - "Add a new module to the current target's modules.", - "target modules add []"), + CommandObjectTargetModulesAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules add", + "Add a new module to the current target's modules.", + "target modules add []"), m_option_group(), - m_symbol_file (LLDB_OPT_SET_1, false, "symfile", 's', 0, eArgTypeFilename, "Fullpath to a stand alone debug symbols file for when debug symbols are not in the executable.") - { - m_option_group.Append (&m_uuid_option_group, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } - - ~CommandObjectTargetModulesAdd() override = default; - - Options * - GetOptions () override - { - return &m_option_group; - } - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } + m_symbol_file(LLDB_OPT_SET_1, false, "symfile", 's', 0, + eArgTypeFilename, "Fullpath to a stand alone debug " + "symbols file for when debug symbols " + "are not in the executable.") { + m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Append(&m_symbol_file, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectTargetModulesAdd() override = default; + + Options *GetOptions() override { return &m_option_group; } + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } protected: - OptionGroupOptions m_option_group; - OptionGroupUUID m_uuid_option_group; - OptionGroupFile m_symbol_file; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); + OptionGroupOptions m_option_group; + OptionGroupUUID m_uuid_option_group; + OptionGroupFile m_symbol_file; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + bool flush = false; + + const size_t argc = args.GetArgumentCount(); + if (argc == 0) { + if (m_uuid_option_group.GetOptionValue().OptionWasSet()) { + // We are given a UUID only, go locate the file + ModuleSpec module_spec; + module_spec.GetUUID() = + m_uuid_option_group.GetOptionValue().GetCurrentValue(); + if (m_symbol_file.GetOptionValue().OptionWasSet()) + module_spec.GetSymbolFileSpec() = + m_symbol_file.GetOptionValue().GetCurrentValue(); + if (Symbols::DownloadObjectAndSymbolFile(module_spec)) { + ModuleSP module_sp(target->GetSharedModule(module_spec)); + if (module_sp) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } else { + StreamString strm; + module_spec.GetUUID().Dump(&strm); + if (module_spec.GetFileSpec()) { + if (module_spec.GetSymbolFileSpec()) { + result.AppendErrorWithFormat( + "Unable to create the executable or symbol file with " + "UUID %s with path %s and symbol file %s", + strm.GetString().c_str(), + module_spec.GetFileSpec().GetPath().c_str(), + module_spec.GetSymbolFileSpec().GetPath().c_str()); + } else { + result.AppendErrorWithFormat( + "Unable to create the executable or symbol file with " + "UUID %s with path %s", + strm.GetString().c_str(), + module_spec.GetFileSpec().GetPath().c_str()); + } + } else { + result.AppendErrorWithFormat("Unable to create the executable " + "or symbol file with UUID %s", + strm.GetString().c_str()); + } + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + StreamString strm; + module_spec.GetUUID().Dump(&strm); + result.AppendErrorWithFormat( + "Unable to locate the executable or symbol file with UUID %s", + strm.GetString().c_str()); + result.SetStatus(eReturnStatusFailed); return false; + } + } else { + result.AppendError( + "one or more executable image paths must be specified"); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - bool flush = false; - - const size_t argc = args.GetArgumentCount(); - if (argc == 0) - { - if (m_uuid_option_group.GetOptionValue ().OptionWasSet()) - { - // We are given a UUID only, go locate the file - ModuleSpec module_spec; - module_spec.GetUUID() = m_uuid_option_group.GetOptionValue ().GetCurrentValue(); - if (m_symbol_file.GetOptionValue().OptionWasSet()) - module_spec.GetSymbolFileSpec() = m_symbol_file.GetOptionValue().GetCurrentValue(); - if (Symbols::DownloadObjectAndSymbolFile (module_spec)) - { - ModuleSP module_sp (target->GetSharedModule (module_spec)); - if (module_sp) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - return true; - } - else - { - StreamString strm; - module_spec.GetUUID().Dump (&strm); - if (module_spec.GetFileSpec()) - { - if (module_spec.GetSymbolFileSpec()) - { - result.AppendErrorWithFormat ("Unable to create the executable or symbol file with UUID %s with path %s and symbol file %s", - strm.GetString().c_str(), - module_spec.GetFileSpec().GetPath().c_str(), - module_spec.GetSymbolFileSpec().GetPath().c_str()); - } - else - { - result.AppendErrorWithFormat ("Unable to create the executable or symbol file with UUID %s with path %s", - strm.GetString().c_str(), - module_spec.GetFileSpec().GetPath().c_str()); - } - } - else - { - result.AppendErrorWithFormat ("Unable to create the executable or symbol file with UUID %s", - strm.GetString().c_str()); - } - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - StreamString strm; - module_spec.GetUUID().Dump (&strm); - result.AppendErrorWithFormat ("Unable to locate the executable or symbol file with UUID %s", strm.GetString().c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } + } else { + for (size_t i = 0; i < argc; ++i) { + const char *path = args.GetArgumentAtIndex(i); + if (path) { + FileSpec file_spec(path, true); + if (file_spec.Exists()) { + ModuleSpec module_spec(file_spec); + if (m_uuid_option_group.GetOptionValue().OptionWasSet()) + module_spec.GetUUID() = + m_uuid_option_group.GetOptionValue().GetCurrentValue(); + if (m_symbol_file.GetOptionValue().OptionWasSet()) + module_spec.GetSymbolFileSpec() = + m_symbol_file.GetOptionValue().GetCurrentValue(); + if (!module_spec.GetArchitecture().IsValid()) + module_spec.GetArchitecture() = target->GetArchitecture(); + Error error; + ModuleSP module_sp(target->GetSharedModule(module_spec, &error)); + if (!module_sp) { + const char *error_cstr = error.AsCString(); + if (error_cstr) + result.AppendError(error_cstr); else - { - result.AppendError ("one or more executable image paths must be specified"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - for (size_t i = 0; i < argc; ++i) - { - const char *path = args.GetArgumentAtIndex(i); - if (path) - { - FileSpec file_spec(path, true); - if (file_spec.Exists()) - { - ModuleSpec module_spec (file_spec); - if (m_uuid_option_group.GetOptionValue ().OptionWasSet()) - module_spec.GetUUID() = m_uuid_option_group.GetOptionValue ().GetCurrentValue(); - if (m_symbol_file.GetOptionValue().OptionWasSet()) - module_spec.GetSymbolFileSpec() = m_symbol_file.GetOptionValue().GetCurrentValue(); - if (!module_spec.GetArchitecture().IsValid()) - module_spec.GetArchitecture() = target->GetArchitecture(); - Error error; - ModuleSP module_sp (target->GetSharedModule (module_spec, &error)); - if (!module_sp) - { - const char *error_cstr = error.AsCString(); - if (error_cstr) - result.AppendError (error_cstr); - else - result.AppendErrorWithFormat ("unsupported module: %s", path); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - flush = true; - } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - char resolved_path[PATH_MAX]; - result.SetStatus (eReturnStatusFailed); - if (file_spec.GetPath (resolved_path, sizeof(resolved_path))) - { - if (strcmp (resolved_path, path) != 0) - { - result.AppendErrorWithFormat ("invalid module path '%s' with resolved path '%s'\n", path, resolved_path); - break; - } - } - result.AppendErrorWithFormat ("invalid module path '%s'\n", path); - break; - } - } + result.AppendErrorWithFormat("unsupported module: %s", path); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + flush = true; + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + char resolved_path[PATH_MAX]; + result.SetStatus(eReturnStatusFailed); + if (file_spec.GetPath(resolved_path, sizeof(resolved_path))) { + if (strcmp(resolved_path, path) != 0) { + result.AppendErrorWithFormat( + "invalid module path '%s' with resolved path '%s'\n", + path, resolved_path); + break; } + } + result.AppendErrorWithFormat("invalid module path '%s'\n", path); + break; } - - if (flush) - { - ProcessSP process = target->GetProcessSP(); - if (process) - process->Flush(); - } + } } + } - return result.Succeeded(); + if (flush) { + ProcessSP process = target->GetProcessSP(); + if (process) + process->Flush(); + } } + + return result.Succeeded(); + } }; -class CommandObjectTargetModulesLoad : public CommandObjectTargetModulesModuleAutoComplete -{ +class CommandObjectTargetModulesLoad + : public CommandObjectTargetModulesModuleAutoComplete { public: - CommandObjectTargetModulesLoad (CommandInterpreter &interpreter) : - CommandObjectTargetModulesModuleAutoComplete (interpreter, - "target modules load", - "Set the load addresses for one or more sections in a target module.", - "target modules load [--file --uuid ]
[
....]"), + CommandObjectTargetModulesLoad(CommandInterpreter &interpreter) + : CommandObjectTargetModulesModuleAutoComplete( + interpreter, "target modules load", "Set the load addresses for " + "one or more sections in a " + "target module.", + "target modules load [--file --uuid ] " + "
[
....]"), m_option_group(), - m_file_option (LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName, "Fullpath or basename for module to load.", ""), - m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset, "Set the load address for all sections to be the virtual address in the file plus the offset.", 0) - { - m_option_group.Append (&m_uuid_option_group, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } - - ~CommandObjectTargetModulesLoad() override = default; - - Options * - GetOptions () override - { - return &m_option_group; - } + m_file_option(LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypeName, + "Fullpath or basename for module to load.", ""), + m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset, + "Set the load address for all sections to be the " + "virtual address in the file plus the offset.", + 0) { + m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectTargetModulesLoad() override = default; + + Options *GetOptions() override { return &m_option_group; } protected: - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + const size_t argc = args.GetArgumentCount(); + ModuleSpec module_spec; + bool search_using_module_spec = false; + if (m_file_option.GetOptionValue().OptionWasSet()) { + search_using_module_spec = true; + const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue(); + const bool use_global_module_list = true; + ModuleList module_list; + const size_t num_matches = FindModulesByName( + target, arg_cstr, module_list, use_global_module_list); + if (num_matches == 1) { + module_spec.GetFileSpec() = + module_list.GetModuleAtIndex(0)->GetFileSpec(); + } else if (num_matches > 1) { + search_using_module_spec = false; + result.AppendErrorWithFormat( + "more than 1 module matched by name '%s'\n", arg_cstr); + result.SetStatus(eReturnStatusFailed); + } else { + search_using_module_spec = false; + result.AppendErrorWithFormat("no object file for module '%s'\n", + arg_cstr); + result.SetStatus(eReturnStatusFailed); } - else - { - const size_t argc = args.GetArgumentCount(); - ModuleSpec module_spec; - bool search_using_module_spec = false; - if (m_file_option.GetOptionValue().OptionWasSet()) - { - search_using_module_spec = true; - const char *arg_cstr = m_file_option.GetOptionValue().GetCurrentValue(); - const bool use_global_module_list = true; - ModuleList module_list; - const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, use_global_module_list); - if (num_matches == 1) - { - module_spec.GetFileSpec() = module_list.GetModuleAtIndex(0)->GetFileSpec(); - } - else if (num_matches > 1 ) - { - search_using_module_spec = false; - result.AppendErrorWithFormat ("more than 1 module matched by name '%s'\n", arg_cstr); - result.SetStatus (eReturnStatusFailed); - } - else - { - search_using_module_spec = false; - result.AppendErrorWithFormat ("no object file for module '%s'\n", arg_cstr); - result.SetStatus (eReturnStatusFailed); - } - } - - if (m_uuid_option_group.GetOptionValue().OptionWasSet()) - { - search_using_module_spec = true; - module_spec.GetUUID() = m_uuid_option_group.GetOptionValue().GetCurrentValue(); - } - - if (search_using_module_spec) - { - ModuleList matching_modules; - const size_t num_matches = target->GetImages().FindModules (module_spec, matching_modules); - - char path[PATH_MAX]; - if (num_matches == 1) - { - Module *module = matching_modules.GetModulePointerAtIndex(0); - if (module) - { - ObjectFile *objfile = module->GetObjectFile(); - if (objfile) - { - SectionList *section_list = module->GetSectionList(); - if (section_list) - { - bool changed = false; - if (argc == 0) - { - if (m_slide_option.GetOptionValue().OptionWasSet()) - { - const addr_t slide = m_slide_option.GetOptionValue().GetCurrentValue(); - const bool slide_is_offset = true; - module->SetLoadAddress (*target, slide, slide_is_offset, changed); - } - else - { - result.AppendError ("one or more section name + load address pair must be specified"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - if (m_slide_option.GetOptionValue().OptionWasSet()) - { - result.AppendError ("The \"--slide \" option can't be used in conjunction with setting section load addresses.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - for (size_t i = 0; i < argc; i += 2) - { - const char *sect_name = args.GetArgumentAtIndex(i); - const char *load_addr_cstr = args.GetArgumentAtIndex(i+1); - if (sect_name && load_addr_cstr) - { - ConstString const_sect_name(sect_name); - bool success = false; - addr_t load_addr = StringConvert::ToUInt64(load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success); - if (success) - { - SectionSP section_sp (section_list->FindSectionByName(const_sect_name)); - if (section_sp) - { - if (section_sp->IsThreadSpecific()) - { - result.AppendErrorWithFormat ("thread specific sections are not yet supported (section '%s')\n", sect_name); - result.SetStatus (eReturnStatusFailed); - break; - } - else - { - if (target->GetSectionLoadList().SetSectionLoadAddress (section_sp, load_addr)) - changed = true; - result.AppendMessageWithFormat("section '%s' loaded at 0x%" PRIx64 "\n", sect_name, load_addr); - } - } - else - { - result.AppendErrorWithFormat ("no section found that matches the section name '%s'\n", sect_name); - result.SetStatus (eReturnStatusFailed); - break; - } - } - else - { - result.AppendErrorWithFormat ("invalid load address string '%s'\n", load_addr_cstr); - result.SetStatus (eReturnStatusFailed); - break; - } - } - else - { - if (sect_name) - result.AppendError ("section names must be followed by a load address.\n"); - else - result.AppendError ("one or more section name + load address pair must be specified.\n"); - result.SetStatus (eReturnStatusFailed); - break; - } - } - } - - if (changed) - { - target->ModulesDidLoad (matching_modules); - Process *process = m_exe_ctx.GetProcessPtr(); - if (process) - process->Flush(); - } - } - else - { - module->GetFileSpec().GetPath (path, sizeof(path)); - result.AppendErrorWithFormat ("no sections in object file '%s'\n", path); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - module->GetFileSpec().GetPath (path, sizeof(path)); - result.AppendErrorWithFormat ("no object file for module '%s'\n", path); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - FileSpec *module_spec_file = module_spec.GetFileSpecPtr(); - if (module_spec_file) - { - module_spec_file->GetPath (path, sizeof(path)); - result.AppendErrorWithFormat ("invalid module '%s'.\n", path); + } + + if (m_uuid_option_group.GetOptionValue().OptionWasSet()) { + search_using_module_spec = true; + module_spec.GetUUID() = + m_uuid_option_group.GetOptionValue().GetCurrentValue(); + } + + if (search_using_module_spec) { + ModuleList matching_modules; + const size_t num_matches = + target->GetImages().FindModules(module_spec, matching_modules); + + char path[PATH_MAX]; + if (num_matches == 1) { + Module *module = matching_modules.GetModulePointerAtIndex(0); + if (module) { + ObjectFile *objfile = module->GetObjectFile(); + if (objfile) { + SectionList *section_list = module->GetSectionList(); + if (section_list) { + bool changed = false; + if (argc == 0) { + if (m_slide_option.GetOptionValue().OptionWasSet()) { + const addr_t slide = + m_slide_option.GetOptionValue().GetCurrentValue(); + const bool slide_is_offset = true; + module->SetLoadAddress(*target, slide, slide_is_offset, + changed); + } else { + result.AppendError("one or more section name + load " + "address pair must be specified"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + if (m_slide_option.GetOptionValue().OptionWasSet()) { + result.AppendError("The \"--slide \" option can't " + "be used in conjunction with setting " + "section load addresses.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + for (size_t i = 0; i < argc; i += 2) { + const char *sect_name = args.GetArgumentAtIndex(i); + const char *load_addr_cstr = args.GetArgumentAtIndex(i + 1); + if (sect_name && load_addr_cstr) { + ConstString const_sect_name(sect_name); + bool success = false; + addr_t load_addr = StringConvert::ToUInt64( + load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success); + if (success) { + SectionSP section_sp( + section_list->FindSectionByName(const_sect_name)); + if (section_sp) { + if (section_sp->IsThreadSpecific()) { + result.AppendErrorWithFormat( + "thread specific sections are not yet " + "supported (section '%s')\n", + sect_name); + result.SetStatus(eReturnStatusFailed); + break; + } else { + if (target->GetSectionLoadList() + .SetSectionLoadAddress(section_sp, + load_addr)) + changed = true; + result.AppendMessageWithFormat( + "section '%s' loaded at 0x%" PRIx64 "\n", + sect_name, load_addr); + } + } else { + result.AppendErrorWithFormat("no section found that " + "matches the section " + "name '%s'\n", + sect_name); + result.SetStatus(eReturnStatusFailed); + break; } - else - result.AppendError ("no module spec"); - result.SetStatus (eReturnStatusFailed); + } else { + result.AppendErrorWithFormat( + "invalid load address string '%s'\n", + load_addr_cstr); + result.SetStatus(eReturnStatusFailed); + break; + } + } else { + if (sect_name) + result.AppendError("section names must be followed by " + "a load address.\n"); + else + result.AppendError("one or more section name + load " + "address pair must be specified.\n"); + result.SetStatus(eReturnStatusFailed); + break; } + } } - else - { - std::string uuid_str; - - if (module_spec.GetFileSpec()) - module_spec.GetFileSpec().GetPath (path, sizeof(path)); - else - path[0] = '\0'; - - if (module_spec.GetUUIDPtr()) - uuid_str = module_spec.GetUUID().GetAsString(); - if (num_matches > 1) - { - result.AppendErrorWithFormat ("multiple modules match%s%s%s%s:\n", - path[0] ? " file=" : "", - path, - !uuid_str.empty() ? " uuid=" : "", - uuid_str.c_str()); - for (size_t i = 0; i < num_matches; ++i) - { - if (matching_modules.GetModulePointerAtIndex(i)->GetFileSpec().GetPath (path, sizeof(path))) - result.AppendMessageWithFormat("%s\n", path); - } - } - else - { - result.AppendErrorWithFormat ("no modules were found that match%s%s%s%s.\n", - path[0] ? " file=" : "", - path, - !uuid_str.empty() ? " uuid=" : "", - uuid_str.c_str()); - } - result.SetStatus (eReturnStatusFailed); + + if (changed) { + target->ModulesDidLoad(matching_modules); + Process *process = m_exe_ctx.GetProcessPtr(); + if (process) + process->Flush(); } + } else { + module->GetFileSpec().GetPath(path, sizeof(path)); + result.AppendErrorWithFormat( + "no sections in object file '%s'\n", path); + result.SetStatus(eReturnStatusFailed); + } + } else { + module->GetFileSpec().GetPath(path, sizeof(path)); + result.AppendErrorWithFormat("no object file for module '%s'\n", + path); + result.SetStatus(eReturnStatusFailed); } - else - { - result.AppendError ("either the \"--file \" or the \"--uuid \" option must be specified.\n"); - result.SetStatus (eReturnStatusFailed); - return false; + } else { + FileSpec *module_spec_file = module_spec.GetFileSpecPtr(); + if (module_spec_file) { + module_spec_file->GetPath(path, sizeof(path)); + result.AppendErrorWithFormat("invalid module '%s'.\n", path); + } else + result.AppendError("no module spec"); + result.SetStatus(eReturnStatusFailed); + } + } else { + std::string uuid_str; + + if (module_spec.GetFileSpec()) + module_spec.GetFileSpec().GetPath(path, sizeof(path)); + else + path[0] = '\0'; + + if (module_spec.GetUUIDPtr()) + uuid_str = module_spec.GetUUID().GetAsString(); + if (num_matches > 1) { + result.AppendErrorWithFormat( + "multiple modules match%s%s%s%s:\n", path[0] ? " file=" : "", + path, !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str()); + for (size_t i = 0; i < num_matches; ++i) { + if (matching_modules.GetModulePointerAtIndex(i) + ->GetFileSpec() + .GetPath(path, sizeof(path))) + result.AppendMessageWithFormat("%s\n", path); } + } else { + result.AppendErrorWithFormat( + "no modules were found that match%s%s%s%s.\n", + path[0] ? " file=" : "", path, + !uuid_str.empty() ? " uuid=" : "", uuid_str.c_str()); + } + result.SetStatus(eReturnStatusFailed); } - return result.Succeeded(); + } else { + result.AppendError("either the \"--file \" or the \"--uuid " + "\" option must be specified.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } } + return result.Succeeded(); + } - OptionGroupOptions m_option_group; - OptionGroupUUID m_uuid_option_group; - OptionGroupString m_file_option; - OptionGroupUInt64 m_slide_option; + OptionGroupOptions m_option_group; + OptionGroupUUID m_uuid_option_group; + OptionGroupString m_file_option; + OptionGroupUInt64 m_slide_option; }; //---------------------------------------------------------------------- // List images with associated information //---------------------------------------------------------------------- -class CommandObjectTargetModulesList : public CommandObjectParsed -{ +class CommandObjectTargetModulesList : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_format_array(), - m_use_global_module_list (false), - m_module_addr (LLDB_INVALID_ADDRESS) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = m_getopt_table[option_idx].val; - if (short_option == 'g') - { - m_use_global_module_list = true; - } - else if (short_option == 'a') - { - m_module_addr = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - } - else - { - unsigned long width = 0; - if (option_arg) - width = strtoul(option_arg, nullptr, 0); - m_format_array.push_back(std::make_pair(short_option, width)); - } - return error; - } + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_format_array(), m_use_global_module_list(false), + m_module_addr(LLDB_INVALID_ADDRESS) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + + const int short_option = m_getopt_table[option_idx].val; + if (short_option == 'g') { + m_use_global_module_list = true; + } else if (short_option == 'a') { + m_module_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + } else { + unsigned long width = 0; + if (option_arg) + width = strtoul(option_arg, nullptr, 0); + m_format_array.push_back(std::make_pair(short_option, width)); + } + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_format_array.clear(); - m_use_global_module_list = false; - m_module_addr = LLDB_INVALID_ADDRESS; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_format_array.clear(); + m_use_global_module_list = false; + m_module_addr = LLDB_INVALID_ADDRESS; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. - typedef std::vector< std::pair > FormatWidthCollection; - FormatWidthCollection m_format_array; - bool m_use_global_module_list; - lldb::addr_t m_module_addr; - }; + // Instance variables to hold the values for command options. + typedef std::vector> FormatWidthCollection; + FormatWidthCollection m_format_array; + bool m_use_global_module_list; + lldb::addr_t m_module_addr; + }; - CommandObjectTargetModulesList (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target modules list", - "List current executable and dependent shared library images.", - "target modules list []"), - m_options() - { - } + CommandObjectTargetModulesList(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target modules list", + "List current executable and dependent shared library images.", + "target modules list []"), + m_options() {} - ~CommandObjectTargetModulesList() override = default; + ~CommandObjectTargetModulesList() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - const bool use_global_module_list = m_options.m_use_global_module_list; - // Define a local module list here to ensure it lives longer than any "locker" - // object which might lock its contents below (through the "module_list_ptr" - // variable). - ModuleList module_list; - if (target == nullptr && !use_global_module_list) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - if (target) - { - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - } - // Dump all sections for all modules images - Stream &strm = result.GetOutputStream(); - - if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) - { - if (target) - { - Address module_address; - if (module_address.SetLoadAddress(m_options.m_module_addr, target)) - { - ModuleSP module_sp (module_address.GetModule()); - if (module_sp) - { - PrintModule (target, module_sp.get(), 0, strm); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Couldn't find module matching address: 0x%" PRIx64 ".", m_options.m_module_addr); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendErrorWithFormat ("Couldn't find module containing address: 0x%" PRIx64 ".", m_options.m_module_addr); - result.SetStatus (eReturnStatusFailed); - } - } - else - { - result.AppendError ("Can only look up modules by address with a valid target."); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); - } - - size_t num_modules = 0; - - // This locker will be locked on the mutex in module_list_ptr if it is non-nullptr. - // Otherwise it will lock the AllocationModuleCollectionMutex when accessing - // the global module list directly. - std::unique_lock guard(Module::GetAllocationModuleCollectionMutex(), std::defer_lock); - - const ModuleList *module_list_ptr = nullptr; - const size_t argc = command.GetArgumentCount(); - if (argc == 0) - { - if (use_global_module_list) - { - guard.lock(); - num_modules = Module::GetNumberAllocatedModules(); - } - else - { - module_list_ptr = &target->GetImages(); - } - } - else - { - for (size_t i = 0; i < argc; ++i) - { - // Dump specified images (by basename or fullpath) - const char *arg_cstr = command.GetArgumentAtIndex(i); - const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, use_global_module_list); - if (num_matches == 0) - { - if (argc == 1) - { - result.AppendErrorWithFormat ("no modules found that match '%s'", arg_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - - module_list_ptr = &module_list; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + const bool use_global_module_list = m_options.m_use_global_module_list; + // Define a local module list here to ensure it lives longer than any + // "locker" + // object which might lock its contents below (through the "module_list_ptr" + // variable). + ModuleList module_list; + if (target == nullptr && !use_global_module_list) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + if (target) { + uint32_t addr_byte_size = + target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + } + // Dump all sections for all modules images + Stream &strm = result.GetOutputStream(); + + if (m_options.m_module_addr != LLDB_INVALID_ADDRESS) { + if (target) { + Address module_address; + if (module_address.SetLoadAddress(m_options.m_module_addr, target)) { + ModuleSP module_sp(module_address.GetModule()); + if (module_sp) { + PrintModule(target, module_sp.get(), 0, strm); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "Couldn't find module matching address: 0x%" PRIx64 ".", + m_options.m_module_addr); + result.SetStatus(eReturnStatusFailed); } - - std::unique_lock lock; - if (module_list_ptr != nullptr) - { - lock = std::unique_lock(module_list_ptr->GetMutex()); - - num_modules = module_list_ptr->GetSize(); + } else { + result.AppendErrorWithFormat( + "Couldn't find module containing address: 0x%" PRIx64 ".", + m_options.m_module_addr); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendError( + "Can only look up modules by address with a valid target."); + result.SetStatus(eReturnStatusFailed); + } + return result.Succeeded(); + } + + size_t num_modules = 0; + + // This locker will be locked on the mutex in module_list_ptr if it is + // non-nullptr. + // Otherwise it will lock the AllocationModuleCollectionMutex when + // accessing + // the global module list directly. + std::unique_lock guard( + Module::GetAllocationModuleCollectionMutex(), std::defer_lock); + + const ModuleList *module_list_ptr = nullptr; + const size_t argc = command.GetArgumentCount(); + if (argc == 0) { + if (use_global_module_list) { + guard.lock(); + num_modules = Module::GetNumberAllocatedModules(); + } else { + module_list_ptr = &target->GetImages(); + } + } else { + for (size_t i = 0; i < argc; ++i) { + // Dump specified images (by basename or fullpath) + const char *arg_cstr = command.GetArgumentAtIndex(i); + const size_t num_matches = FindModulesByName( + target, arg_cstr, module_list, use_global_module_list); + if (num_matches == 0) { + if (argc == 1) { + result.AppendErrorWithFormat("no modules found that match '%s'", + arg_cstr); + result.SetStatus(eReturnStatusFailed); + return false; } + } + } - if (num_modules > 0) - { - for (uint32_t image_idx = 0; image_idxGetModuleAtIndexUnlocked(image_idx); - module = module_sp.get(); - } - else - { - module = Module::GetAllocatedModuleAtIndex(image_idx); - module_sp = module->shared_from_this(); - } + module_list_ptr = &module_list; + } + + std::unique_lock lock; + if (module_list_ptr != nullptr) { + lock = + std::unique_lock(module_list_ptr->GetMutex()); + + num_modules = module_list_ptr->GetSize(); + } + + if (num_modules > 0) { + for (uint32_t image_idx = 0; image_idx < num_modules; ++image_idx) { + ModuleSP module_sp; + Module *module; + if (module_list_ptr) { + module_sp = module_list_ptr->GetModuleAtIndexUnlocked(image_idx); + module = module_sp.get(); + } else { + module = Module::GetAllocatedModuleAtIndex(image_idx); + module_sp = module->shared_from_this(); + } + + const size_t indent = strm.Printf("[%3u] ", image_idx); + PrintModule(target, module, indent, strm); + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + if (argc) { + if (use_global_module_list) + result.AppendError( + "the global module list has no matching modules"); + else + result.AppendError("the target has no matching modules"); + } else { + if (use_global_module_list) + result.AppendError("the global module list is empty"); + else + result.AppendError( + "the target has no associated executable images"); + } + result.SetStatus(eReturnStatusFailed); + return false; + } + } + return result.Succeeded(); + } - const size_t indent = strm.Printf("[%3u] ", image_idx); - PrintModule (target, module, indent, strm); + void PrintModule(Target *target, Module *module, int indent, Stream &strm) { + if (module == nullptr) { + strm.PutCString("Null module"); + return; + } + bool dump_object_name = false; + if (m_options.m_format_array.empty()) { + m_options.m_format_array.push_back(std::make_pair('u', 0)); + m_options.m_format_array.push_back(std::make_pair('h', 0)); + m_options.m_format_array.push_back(std::make_pair('f', 0)); + m_options.m_format_array.push_back(std::make_pair('S', 0)); + } + const size_t num_entries = m_options.m_format_array.size(); + bool print_space = false; + for (size_t i = 0; i < num_entries; ++i) { + if (print_space) + strm.PutChar(' '); + print_space = true; + const char format_char = m_options.m_format_array[i].first; + uint32_t width = m_options.m_format_array[i].second; + switch (format_char) { + case 'A': + DumpModuleArchitecture(strm, module, false, width); + break; + + case 't': + DumpModuleArchitecture(strm, module, true, width); + break; + + case 'f': + DumpFullpath(strm, &module->GetFileSpec(), width); + dump_object_name = true; + break; + + case 'd': + DumpDirectory(strm, &module->GetFileSpec(), width); + break; + + case 'b': + DumpBasename(strm, &module->GetFileSpec(), width); + dump_object_name = true; + break; + + case 'h': + case 'o': + // Image header address + { + uint32_t addr_nibble_width = + target ? (target->GetArchitecture().GetAddressByteSize() * 2) + : 16; + + ObjectFile *objfile = module->GetObjectFile(); + if (objfile) { + Address header_addr(objfile->GetHeaderAddress()); + if (header_addr.IsValid()) { + if (target && !target->GetSectionLoadList().IsEmpty()) { + lldb::addr_t header_load_addr = + header_addr.GetLoadAddress(target); + if (header_load_addr == LLDB_INVALID_ADDRESS) { + header_addr.Dump(&strm, target, + Address::DumpStyleModuleWithFileAddress, + Address::DumpStyleFileAddress); + } else { + if (format_char == 'o') { + // Show the offset of slide for the image + strm.Printf( + "0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width, + header_load_addr - header_addr.GetFileAddress()); + } else { + // Show the load address of the image + strm.Printf("0x%*.*" PRIx64, addr_nibble_width, + addr_nibble_width, header_load_addr); + } } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - if (argc) - { - if (use_global_module_list) - result.AppendError ("the global module list has no matching modules"); - else - result.AppendError ("the target has no matching modules"); - } - else - { - if (use_global_module_list) - result.AppendError ("the global module list is empty"); - else - result.AppendError ("the target has no associated executable images"); - } - result.SetStatus (eReturnStatusFailed); - return false; + break; + } + // The address was valid, but the image isn't loaded, output the + // address in an appropriate format + header_addr.Dump(&strm, target, Address::DumpStyleFileAddress); + break; } + } + strm.Printf("%*s", addr_nibble_width + 2, ""); } - return result.Succeeded(); - } - - void - PrintModule (Target *target, Module *module, int indent, Stream &strm) - { - if (module == nullptr) - { - strm.PutCString("Null module"); - return; + break; + + case 'r': { + size_t ref_count = 0; + ModuleSP module_sp(module->shared_from_this()); + if (module_sp) { + // Take one away to make sure we don't count our local "module_sp" + ref_count = module_sp.use_count() - 1; } - - bool dump_object_name = false; - if (m_options.m_format_array.empty()) - { - m_options.m_format_array.push_back(std::make_pair('u', 0)); - m_options.m_format_array.push_back(std::make_pair('h', 0)); - m_options.m_format_array.push_back(std::make_pair('f', 0)); - m_options.m_format_array.push_back(std::make_pair('S', 0)); + if (width) + strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count); + else + strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count); + } break; + + case 's': + case 'S': { + const SymbolVendor *symbol_vendor = module->GetSymbolVendor(); + if (symbol_vendor) { + const FileSpec symfile_spec = symbol_vendor->GetMainFileSpec(); + if (format_char == 'S') { + // Dump symbol file only if different from module file + if (!symfile_spec || symfile_spec == module->GetFileSpec()) { + print_space = false; + break; + } + // Add a newline and indent past the index + strm.Printf("\n%*s", indent, ""); + } + DumpFullpath(strm, &symfile_spec, width); + dump_object_name = true; + break; } - const size_t num_entries = m_options.m_format_array.size(); - bool print_space = false; - for (size_t i = 0; i < num_entries; ++i) - { - if (print_space) - strm.PutChar(' '); - print_space = true; - const char format_char = m_options.m_format_array[i].first; - uint32_t width = m_options.m_format_array[i].second; - switch (format_char) - { - case 'A': - DumpModuleArchitecture (strm, module, false, width); - break; - - case 't': - DumpModuleArchitecture (strm, module, true, width); - break; - - case 'f': - DumpFullpath (strm, &module->GetFileSpec(), width); - dump_object_name = true; - break; - - case 'd': - DumpDirectory (strm, &module->GetFileSpec(), width); - break; - - case 'b': - DumpBasename (strm, &module->GetFileSpec(), width); - dump_object_name = true; - break; - - case 'h': - case 'o': - // Image header address - { - uint32_t addr_nibble_width = target ? (target->GetArchitecture().GetAddressByteSize() * 2) : 16; - - ObjectFile *objfile = module->GetObjectFile (); - if (objfile) - { - Address header_addr(objfile->GetHeaderAddress()); - if (header_addr.IsValid()) - { - if (target && !target->GetSectionLoadList().IsEmpty()) - { - lldb::addr_t header_load_addr = header_addr.GetLoadAddress (target); - if (header_load_addr == LLDB_INVALID_ADDRESS) - { - header_addr.Dump (&strm, target, Address::DumpStyleModuleWithFileAddress, Address::DumpStyleFileAddress); - } - else - { - if (format_char == 'o') - { - // Show the offset of slide for the image - strm.Printf ("0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width, header_load_addr - header_addr.GetFileAddress()); - } - else - { - // Show the load address of the image - strm.Printf ("0x%*.*" PRIx64, addr_nibble_width, addr_nibble_width, header_load_addr); - } - } - break; - } - // The address was valid, but the image isn't loaded, output the address in an appropriate format - header_addr.Dump (&strm, target, Address::DumpStyleFileAddress); - break; - } - } - strm.Printf ("%*s", addr_nibble_width + 2, ""); - } - break; - - case 'r': - { - size_t ref_count = 0; - ModuleSP module_sp (module->shared_from_this()); - if (module_sp) - { - // Take one away to make sure we don't count our local "module_sp" - ref_count = module_sp.use_count() - 1; - } - if (width) - strm.Printf("{%*" PRIu64 "}", width, (uint64_t)ref_count); - else - strm.Printf("{%" PRIu64 "}", (uint64_t)ref_count); - } - break; - - case 's': - case 'S': - { - const SymbolVendor *symbol_vendor = module->GetSymbolVendor(); - if (symbol_vendor) - { - const FileSpec symfile_spec = symbol_vendor->GetMainFileSpec(); - if (format_char == 'S') - { - // Dump symbol file only if different from module file - if (!symfile_spec || symfile_spec == module->GetFileSpec()) - { - print_space = false; - break; - } - // Add a newline and indent past the index - strm.Printf ("\n%*s", indent, ""); - } - DumpFullpath (strm, &symfile_spec, width); - dump_object_name = true; - break; - } - strm.Printf("%.*s", width, ""); - } - break; + strm.Printf("%.*s", width, ""); + } break; - case 'm': - module->GetModificationTime().Dump(&strm, width); - break; + case 'm': + module->GetModificationTime().Dump(&strm, width); + break; - case 'p': - strm.Printf("%p", static_cast(module)); - break; + case 'p': + strm.Printf("%p", static_cast(module)); + break; - case 'u': - DumpModuleUUID(strm, module); - break; + case 'u': + DumpModuleUUID(strm, module); + break; - default: - break; - } - } - if (dump_object_name) - { - const char *object_name = module->GetObjectName().GetCString(); - if (object_name) - strm.Printf ("(%s)", object_name); - } - strm.EOL(); + default: + break; + } } + if (dump_object_name) { + const char *object_name = module->GetObjectName().GetCString(); + if (object_name) + strm.Printf("(%s)", object_name); + } + strm.EOL(); + } - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectTargetModulesList::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTargetModulesList::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Display the image at this address."}, {LLDB_OPT_SET_1, false, "arch", 'A', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the architecture when listing images."}, {LLDB_OPT_SET_1, false, "triple", 't', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeWidth, "Display the triple when listing images."}, @@ -3577,7 +3134,7 @@ CommandObjectTargetModulesList::CommandOptions::g_option_table[] = {LLDB_OPT_SET_1, false, "pointer", 'p', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the module pointer."}, {LLDB_OPT_SET_1, false, "global", 'g', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the modules from the global module list, not just the current target."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectTargetModulesShowUnwind @@ -3586,746 +3143,668 @@ CommandObjectTargetModulesList::CommandOptions::g_option_table[] = // Lookup unwind information in images //---------------------------------------------------------------------- -class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed -{ +class CommandObjectTargetModulesShowUnwind : public CommandObjectParsed { public: - enum - { - eLookupTypeInvalid = -1, - eLookupTypeAddress = 0, - eLookupTypeSymbol, - eLookupTypeFunction, - eLookupTypeFunctionOrSymbol, - kNumLookupTypes - }; - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_type(eLookupTypeInvalid), - m_str(), - m_addr(LLDB_INVALID_ADDRESS) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - { - m_str = option_arg; - m_type = eLookupTypeAddress; - m_addr = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - if (m_addr == LLDB_INVALID_ADDRESS) - error.SetErrorStringWithFormat ("invalid address string '%s'", option_arg); - break; - } + enum { + eLookupTypeInvalid = -1, + eLookupTypeAddress = 0, + eLookupTypeSymbol, + eLookupTypeFunction, + eLookupTypeFunctionOrSymbol, + kNumLookupTypes + }; + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_type(eLookupTypeInvalid), m_str(), + m_addr(LLDB_INVALID_ADDRESS) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': { + m_str = option_arg; + m_type = eLookupTypeAddress; + m_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + if (m_addr == LLDB_INVALID_ADDRESS) + error.SetErrorStringWithFormat("invalid address string '%s'", + option_arg); + break; + } + + case 'n': + m_str = option_arg; + m_type = eLookupTypeFunctionOrSymbol; + break; + + default: + error.SetErrorStringWithFormat("unrecognized option %c.", short_option); + break; + } + + return error; + } - case 'n': - m_str = option_arg; - m_type = eLookupTypeFunctionOrSymbol; - break; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_type = eLookupTypeInvalid; + m_str.clear(); + m_addr = LLDB_INVALID_ADDRESS; + } - default: - error.SetErrorStringWithFormat ("unrecognized option %c.", short_option); - break; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - return error; - } + // Options table: Required for subclasses of Options. - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_type = eLookupTypeInvalid; - m_str.clear(); - m_addr = LLDB_INVALID_ADDRESS; - } + static OptionDefinition g_option_table[]; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + // Instance variables to hold the values for command options. - // Options table: Required for subclasses of Options. + int m_type; // Should be a eLookupTypeXXX enum after parsing options + std::string m_str; // Holds name lookup + lldb::addr_t m_addr; // Holds the address to lookup + }; - static OptionDefinition g_option_table[]; + CommandObjectTargetModulesShowUnwind(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target modules show-unwind", + "Show synthesized unwind instructions for a function.", nullptr, + eCommandRequiresTarget | eCommandRequiresProcess | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() {} - // Instance variables to hold the values for command options. + ~CommandObjectTargetModulesShowUnwind() override = default; - int m_type; // Should be a eLookupTypeXXX enum after parsing options - std::string m_str; // Holds name lookup - lldb::addr_t m_addr; // Holds the address to lookup - }; + Options *GetOptions() override { return &m_options; } - CommandObjectTargetModulesShowUnwind (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target modules show-unwind", - "Show synthesized unwind instructions for a function.", - nullptr, - eCommandRequiresTarget | - eCommandRequiresProcess | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_options() - { +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_exe_ctx.GetTargetPtr(); + Process *process = m_exe_ctx.GetProcessPtr(); + ABI *abi = nullptr; + if (process) + abi = process->GetABI().get(); + + if (process == nullptr) { + result.AppendError( + "You must have a process running to use this command."); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectTargetModulesShowUnwind() override = default; + ThreadList threads(process->GetThreadList()); + if (threads.GetSize() == 0) { + result.AppendError("The process must be paused to use this command."); + result.SetStatus(eReturnStatusFailed); + return false; + } - Options * - GetOptions () override - { - return &m_options; + ThreadSP thread(threads.GetThreadAtIndex(0)); + if (!thread) { + result.AppendError("The process must be paused to use this command."); + result.SetStatus(eReturnStatusFailed); + return false; } -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_exe_ctx.GetTargetPtr(); - Process *process = m_exe_ctx.GetProcessPtr(); - ABI *abi = nullptr; - if (process) - abi = process->GetABI().get(); + SymbolContextList sc_list; - if (process == nullptr) - { - result.AppendError ("You must have a process running to use this command."); - result.SetStatus (eReturnStatusFailed); - return false; + if (m_options.m_type == eLookupTypeFunctionOrSymbol) { + ConstString function_name(m_options.m_str.c_str()); + target->GetImages().FindFunctions(function_name, eFunctionNameTypeAuto, + true, false, true, sc_list); + } else if (m_options.m_type == eLookupTypeAddress && target) { + Address addr; + if (target->GetSectionLoadList().ResolveLoadAddress(m_options.m_addr, + addr)) { + SymbolContext sc; + ModuleSP module_sp(addr.GetModule()); + module_sp->ResolveSymbolContextForAddress(addr, + eSymbolContextEverything, sc); + if (sc.function || sc.symbol) { + sc_list.Append(sc); } + } + } else { + result.AppendError( + "address-expression or function name option must be specified."); + result.SetStatus(eReturnStatusFailed); + return false; + } - ThreadList threads(process->GetThreadList()); - if (threads.GetSize() == 0) - { - result.AppendError ("The process must be paused to use this command."); - result.SetStatus (eReturnStatusFailed); - return false; - } + size_t num_matches = sc_list.GetSize(); + if (num_matches == 0) { + result.AppendErrorWithFormat("no unwind data found that matches '%s'.", + m_options.m_str.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } - ThreadSP thread(threads.GetThreadAtIndex(0)); - if (!thread) - { - result.AppendError ("The process must be paused to use this command."); - result.SetStatus (eReturnStatusFailed); - return false; + for (uint32_t idx = 0; idx < num_matches; idx++) { + SymbolContext sc; + sc_list.GetContextAtIndex(idx, sc); + if (sc.symbol == nullptr && sc.function == nullptr) + continue; + if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr) + continue; + AddressRange range; + if (!sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, + false, range)) + continue; + if (!range.GetBaseAddress().IsValid()) + continue; + ConstString funcname(sc.GetFunctionName()); + if (funcname.IsEmpty()) + continue; + addr_t start_addr = range.GetBaseAddress().GetLoadAddress(target); + if (abi) + start_addr = abi->FixCodeAddress(start_addr); + + FuncUnwindersSP func_unwinders_sp( + sc.module_sp->GetObjectFile() + ->GetUnwindTable() + .GetUncachedFuncUnwindersContainingAddress(start_addr, sc)); + if (!func_unwinders_sp) + continue; + + result.GetOutputStream().Printf( + "UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n\n", + sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(), + funcname.AsCString(), start_addr); + + UnwindPlanSP non_callsite_unwind_plan = + func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread, -1); + if (non_callsite_unwind_plan) { + result.GetOutputStream().Printf( + "Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n", + non_callsite_unwind_plan->GetSourceName().AsCString()); + } + UnwindPlanSP callsite_unwind_plan = + func_unwinders_sp->GetUnwindPlanAtCallSite(*target, -1); + if (callsite_unwind_plan) { + result.GetOutputStream().Printf( + "Synchronous (restricted to call-sites) UnwindPlan is '%s'\n", + callsite_unwind_plan->GetSourceName().AsCString()); + } + UnwindPlanSP fast_unwind_plan = + func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread); + if (fast_unwind_plan) { + result.GetOutputStream().Printf( + "Fast UnwindPlan is '%s'\n", + fast_unwind_plan->GetSourceName().AsCString()); + } + + result.GetOutputStream().Printf("\n"); + + UnwindPlanSP assembly_sp = + func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread, 0); + if (assembly_sp) { + result.GetOutputStream().Printf( + "Assembly language inspection UnwindPlan:\n"); + assembly_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + UnwindPlanSP ehframe_sp = + func_unwinders_sp->GetEHFrameUnwindPlan(*target, 0); + if (ehframe_sp) { + result.GetOutputStream().Printf("eh_frame UnwindPlan:\n"); + ehframe_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + UnwindPlanSP ehframe_augmented_sp = + func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread, 0); + if (ehframe_augmented_sp) { + result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n"); + ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + UnwindPlanSP arm_unwind_sp = + func_unwinders_sp->GetArmUnwindUnwindPlan(*target, 0); + if (arm_unwind_sp) { + result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n"); + arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + UnwindPlanSP compact_unwind_sp = + func_unwinders_sp->GetCompactUnwindUnwindPlan(*target, 0); + if (compact_unwind_sp) { + result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n"); + compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + if (fast_unwind_plan) { + result.GetOutputStream().Printf("Fast UnwindPlan:\n"); + fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); + } + + ABISP abi_sp = process->GetABI(); + if (abi_sp) { + UnwindPlan arch_default(lldb::eRegisterKindGeneric); + if (abi_sp->CreateDefaultUnwindPlan(arch_default)) { + result.GetOutputStream().Printf("Arch default UnwindPlan:\n"); + arch_default.Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); } - SymbolContextList sc_list; - - if (m_options.m_type == eLookupTypeFunctionOrSymbol) - { - ConstString function_name (m_options.m_str.c_str()); - target->GetImages().FindFunctions (function_name, eFunctionNameTypeAuto, true, false, true, sc_list); + UnwindPlan arch_entry(lldb::eRegisterKindGeneric); + if (abi_sp->CreateFunctionEntryUnwindPlan(arch_entry)) { + result.GetOutputStream().Printf( + "Arch default at entry point UnwindPlan:\n"); + arch_entry.Dump(result.GetOutputStream(), thread.get(), + LLDB_INVALID_ADDRESS); + result.GetOutputStream().Printf("\n"); } - else if (m_options.m_type == eLookupTypeAddress && target) - { - Address addr; - if (target->GetSectionLoadList().ResolveLoadAddress (m_options.m_addr, addr)) - { - SymbolContext sc; - ModuleSP module_sp (addr.GetModule()); - module_sp->ResolveSymbolContextForAddress (addr, eSymbolContextEverything, sc); - if (sc.function || sc.symbol) - { - sc_list.Append(sc); - } - } - } - else - { - result.AppendError ("address-expression or function name option must be specified."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - size_t num_matches = sc_list.GetSize(); - if (num_matches == 0) - { - result.AppendErrorWithFormat ("no unwind data found that matches '%s'.", m_options.m_str.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } - - for (uint32_t idx = 0; idx < num_matches; idx++) - { - SymbolContext sc; - sc_list.GetContextAtIndex(idx, sc); - if (sc.symbol == nullptr && sc.function == nullptr) - continue; - if (!sc.module_sp || sc.module_sp->GetObjectFile() == nullptr) - continue; - AddressRange range; - if (!sc.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, range)) - continue; - if (!range.GetBaseAddress().IsValid()) - continue; - ConstString funcname(sc.GetFunctionName()); - if (funcname.IsEmpty()) - continue; - addr_t start_addr = range.GetBaseAddress().GetLoadAddress(target); - if (abi) - start_addr = abi->FixCodeAddress(start_addr); - - FuncUnwindersSP func_unwinders_sp (sc.module_sp->GetObjectFile()->GetUnwindTable().GetUncachedFuncUnwindersContainingAddress(start_addr, sc)); - if (!func_unwinders_sp) - continue; - - result.GetOutputStream().Printf("UNWIND PLANS for %s`%s (start addr 0x%" PRIx64 ")\n\n", sc.module_sp->GetPlatformFileSpec().GetFilename().AsCString(), funcname.AsCString(), start_addr); - - UnwindPlanSP non_callsite_unwind_plan = func_unwinders_sp->GetUnwindPlanAtNonCallSite(*target, *thread, -1); - if (non_callsite_unwind_plan) - { - result.GetOutputStream().Printf("Asynchronous (not restricted to call-sites) UnwindPlan is '%s'\n", non_callsite_unwind_plan->GetSourceName().AsCString()); - } - UnwindPlanSP callsite_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite(*target, -1); - if (callsite_unwind_plan) - { - result.GetOutputStream().Printf("Synchronous (restricted to call-sites) UnwindPlan is '%s'\n", callsite_unwind_plan->GetSourceName().AsCString()); - } - UnwindPlanSP fast_unwind_plan = func_unwinders_sp->GetUnwindPlanFastUnwind(*target, *thread); - if (fast_unwind_plan) - { - result.GetOutputStream().Printf("Fast UnwindPlan is '%s'\n", fast_unwind_plan->GetSourceName().AsCString()); - } - - result.GetOutputStream().Printf("\n"); + } - UnwindPlanSP assembly_sp = func_unwinders_sp->GetAssemblyUnwindPlan(*target, *thread, 0); - if (assembly_sp) - { - result.GetOutputStream().Printf("Assembly language inspection UnwindPlan:\n"); - assembly_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - UnwindPlanSP ehframe_sp = func_unwinders_sp->GetEHFrameUnwindPlan(*target, 0); - if (ehframe_sp) - { - result.GetOutputStream().Printf("eh_frame UnwindPlan:\n"); - ehframe_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - UnwindPlanSP ehframe_augmented_sp = func_unwinders_sp->GetEHFrameAugmentedUnwindPlan(*target, *thread, 0); - if (ehframe_augmented_sp) - { - result.GetOutputStream().Printf("eh_frame augmented UnwindPlan:\n"); - ehframe_augmented_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - UnwindPlanSP arm_unwind_sp = func_unwinders_sp->GetArmUnwindUnwindPlan(*target, 0); - if (arm_unwind_sp) - { - result.GetOutputStream().Printf("ARM.exidx unwind UnwindPlan:\n"); - arm_unwind_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - UnwindPlanSP compact_unwind_sp = func_unwinders_sp->GetCompactUnwindUnwindPlan(*target, 0); - if (compact_unwind_sp) - { - result.GetOutputStream().Printf("Compact unwind UnwindPlan:\n"); - compact_unwind_sp->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - if (fast_unwind_plan) - { - result.GetOutputStream().Printf("Fast UnwindPlan:\n"); - fast_unwind_plan->Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - ABISP abi_sp = process->GetABI(); - if (abi_sp) - { - UnwindPlan arch_default(lldb::eRegisterKindGeneric); - if (abi_sp->CreateDefaultUnwindPlan (arch_default)) - { - result.GetOutputStream().Printf("Arch default UnwindPlan:\n"); - arch_default.Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - - UnwindPlan arch_entry(lldb::eRegisterKindGeneric); - if (abi_sp->CreateFunctionEntryUnwindPlan (arch_entry)) - { - result.GetOutputStream().Printf("Arch default at entry point UnwindPlan:\n"); - arch_entry.Dump(result.GetOutputStream(), thread.get(), LLDB_INVALID_ADDRESS); - result.GetOutputStream().Printf("\n"); - } - } - - result.GetOutputStream().Printf ("\n"); - } - return result.Succeeded(); + result.GetOutputStream().Printf("\n"); } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectTargetModulesShowUnwind::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTargetModulesShowUnwind::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName, "Show unwind instructions for a function or symbol name."}, {LLDB_OPT_SET_2, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Show unwind instructions for a function or symbol containing an address"}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // Lookup information in images //---------------------------------------------------------------------- -class CommandObjectTargetModulesLookup : public CommandObjectParsed -{ +class CommandObjectTargetModulesLookup : public CommandObjectParsed { public: - enum - { - eLookupTypeInvalid = -1, - eLookupTypeAddress = 0, - eLookupTypeSymbol, - eLookupTypeFileLine, // Line is optional - eLookupTypeFunction, - eLookupTypeFunctionOrSymbol, - eLookupTypeType, - kNumLookupTypes - }; - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - { - m_type = eLookupTypeAddress; - m_addr = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - } - break; - - case 'o': - m_offset = StringConvert::ToUInt64(option_arg, LLDB_INVALID_ADDRESS); - if (m_offset == LLDB_INVALID_ADDRESS) - error.SetErrorStringWithFormat ("invalid offset string '%s'", option_arg); - break; - - case 's': - m_str = option_arg; - m_type = eLookupTypeSymbol; - break; - - case 'f': - m_file.SetFile (option_arg, false); - m_type = eLookupTypeFileLine; - break; - - case 'i': - m_include_inlines = false; - break; - - case 'l': - m_line_number = StringConvert::ToUInt32(option_arg, UINT32_MAX); - if (m_line_number == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid line number string '%s'", option_arg); - else if (m_line_number == 0) - error.SetErrorString ("zero is an invalid line number"); - m_type = eLookupTypeFileLine; - break; - - case 'F': - m_str = option_arg; - m_type = eLookupTypeFunction; - break; - - case 'n': - m_str = option_arg; - m_type = eLookupTypeFunctionOrSymbol; - break; - - case 't': - m_str = option_arg; - m_type = eLookupTypeType; - break; - - case 'v': - m_verbose = 1; - break; - - case 'A': - m_print_all = true; - break; - - case 'r': - m_use_regex = true; - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_type = eLookupTypeInvalid; - m_str.clear(); - m_file.Clear(); - m_addr = LLDB_INVALID_ADDRESS; - m_offset = 0; - m_line_number = 0; - m_use_regex = false; - m_include_inlines = true; - m_verbose = false; - m_print_all = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - int m_type; // Should be a eLookupTypeXXX enum after parsing options - std::string m_str; // Holds name lookup - FileSpec m_file; // Files for file lookups - lldb::addr_t m_addr; // Holds the address to lookup - lldb::addr_t m_offset; // Subtract this offset from m_addr before doing lookups. - uint32_t m_line_number; // Line number for file+line lookups - bool m_use_regex; // Name lookups in m_str are regular expressions. - bool m_include_inlines;// Check for inline entries when looking up by file/line. - bool m_verbose; // Enable verbose lookup info - bool m_print_all; // Print all matches, even in cases where there's a best match. - }; - - CommandObjectTargetModulesLookup (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "target modules lookup", - "Look up information within executable and dependent shared library images.", - nullptr, - eCommandRequiresTarget), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData file_arg; - - // Define the first (and only) variant of this arg. - file_arg.arg_type = eArgTypeFilename; - file_arg.arg_repetition = eArgRepeatStar; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (file_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } - - ~CommandObjectTargetModulesLookup() override = default; - - Options * - GetOptions () override - { - return &m_options; - } - - bool - LookupHere (CommandInterpreter &interpreter, CommandReturnObject &result, bool &syntax_error) - { - switch (m_options.m_type) - { - case eLookupTypeAddress: - case eLookupTypeFileLine: - case eLookupTypeFunction: - case eLookupTypeFunctionOrSymbol: - case eLookupTypeSymbol: - default: - return false; - case eLookupTypeType: - break; - } - - StackFrameSP frame = m_exe_ctx.GetFrameSP(); - - if (!frame) - return false; - - const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule)); - - if (!sym_ctx.module_sp) - return false; - - switch (m_options.m_type) - { - default: - return false; - case eLookupTypeType: - if (!m_options.m_str.empty()) - { - if (LookupTypeHere (m_interpreter, - result.GetOutputStream(), - sym_ctx, - m_options.m_str.c_str(), - m_options.m_use_regex)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; - } - - return true; - } - - bool - LookupInModule (CommandInterpreter &interpreter, Module *module, CommandReturnObject &result, bool &syntax_error) - { - switch (m_options.m_type) - { - case eLookupTypeAddress: - if (m_options.m_addr != LLDB_INVALID_ADDRESS) - { - if (LookupAddressInModule (m_interpreter, - result.GetOutputStream(), - module, - eSymbolContextEverything | (m_options.m_verbose ? static_cast(eSymbolContextVariable) : 0), - m_options.m_addr, - m_options.m_offset, - m_options.m_verbose)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; + enum { + eLookupTypeInvalid = -1, + eLookupTypeAddress = 0, + eLookupTypeSymbol, + eLookupTypeFileLine, // Line is optional + eLookupTypeFunction, + eLookupTypeFunctionOrSymbol, + eLookupTypeType, + kNumLookupTypes + }; + + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': { + m_type = eLookupTypeAddress; + m_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + } break; + + case 'o': + m_offset = StringConvert::ToUInt64(option_arg, LLDB_INVALID_ADDRESS); + if (m_offset == LLDB_INVALID_ADDRESS) + error.SetErrorStringWithFormat("invalid offset string '%s'", + option_arg); + break; + + case 's': + m_str = option_arg; + m_type = eLookupTypeSymbol; + break; + + case 'f': + m_file.SetFile(option_arg, false); + m_type = eLookupTypeFileLine; + break; + + case 'i': + m_include_inlines = false; + break; + + case 'l': + m_line_number = StringConvert::ToUInt32(option_arg, UINT32_MAX); + if (m_line_number == UINT32_MAX) + error.SetErrorStringWithFormat("invalid line number string '%s'", + option_arg); + else if (m_line_number == 0) + error.SetErrorString("zero is an invalid line number"); + m_type = eLookupTypeFileLine; + break; + + case 'F': + m_str = option_arg; + m_type = eLookupTypeFunction; + break; + + case 'n': + m_str = option_arg; + m_type = eLookupTypeFunctionOrSymbol; + break; + + case 't': + m_str = option_arg; + m_type = eLookupTypeType; + break; + + case 'v': + m_verbose = 1; + break; + + case 'A': + m_print_all = true; + break; + + case 'r': + m_use_regex = true; + break; + } + + return error; + } - case eLookupTypeSymbol: - if (!m_options.m_str.empty()) - { - if (LookupSymbolInModule (m_interpreter, - result.GetOutputStream(), - module, - m_options.m_str.c_str(), - m_options.m_use_regex, - m_options.m_verbose)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_type = eLookupTypeInvalid; + m_str.clear(); + m_file.Clear(); + m_addr = LLDB_INVALID_ADDRESS; + m_offset = 0; + m_line_number = 0; + m_use_regex = false; + m_include_inlines = true; + m_verbose = false; + m_print_all = false; + } - case eLookupTypeFileLine: - if (m_options.m_file) - { - if (LookupFileAndLineInModule (m_interpreter, - result.GetOutputStream(), - module, - m_options.m_file, - m_options.m_line_number, - m_options.m_include_inlines, - m_options.m_verbose)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + int m_type; // Should be a eLookupTypeXXX enum after parsing options + std::string m_str; // Holds name lookup + FileSpec m_file; // Files for file lookups + lldb::addr_t m_addr; // Holds the address to lookup + lldb::addr_t + m_offset; // Subtract this offset from m_addr before doing lookups. + uint32_t m_line_number; // Line number for file+line lookups + bool m_use_regex; // Name lookups in m_str are regular expressions. + bool m_include_inlines; // Check for inline entries when looking up by + // file/line. + bool m_verbose; // Enable verbose lookup info + bool m_print_all; // Print all matches, even in cases where there's a best + // match. + }; + + CommandObjectTargetModulesLookup(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target modules lookup", + "Look up information within executable and " + "dependent shared library images.", + nullptr, eCommandRequiresTarget), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData file_arg; + + // Define the first (and only) variant of this arg. + file_arg.arg_type = eArgTypeFilename; + file_arg.arg_repetition = eArgRepeatStar; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(file_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectTargetModulesLookup() override = default; + + Options *GetOptions() override { return &m_options; } + + bool LookupHere(CommandInterpreter &interpreter, CommandReturnObject &result, + bool &syntax_error) { + switch (m_options.m_type) { + case eLookupTypeAddress: + case eLookupTypeFileLine: + case eLookupTypeFunction: + case eLookupTypeFunctionOrSymbol: + case eLookupTypeSymbol: + default: + return false; + case eLookupTypeType: + break; + } - case eLookupTypeFunctionOrSymbol: - case eLookupTypeFunction: - if (!m_options.m_str.empty()) - { - if (LookupFunctionInModule (m_interpreter, - result.GetOutputStream(), - module, - m_options.m_str.c_str(), - m_options.m_use_regex, - m_options.m_include_inlines, - m_options.m_type == eLookupTypeFunctionOrSymbol, // include symbols - m_options.m_verbose)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; + StackFrameSP frame = m_exe_ctx.GetFrameSP(); - case eLookupTypeType: - if (!m_options.m_str.empty()) - { - if (LookupTypeInModule (m_interpreter, - result.GetOutputStream(), - module, - m_options.m_str.c_str(), - m_options.m_use_regex)) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - } - break; + if (!frame) + return false; - default: - m_options.GenerateOptionUsage(result.GetErrorStream(), this, - GetCommandInterpreter() - .GetDebugger() - .GetTerminalWidth()); - syntax_error = true; - break; + const SymbolContext &sym_ctx(frame->GetSymbolContext(eSymbolContextModule)); + + if (!sym_ctx.module_sp) + return false; + + switch (m_options.m_type) { + default: + return false; + case eLookupTypeType: + if (!m_options.m_str.empty()) { + if (LookupTypeHere(m_interpreter, result.GetOutputStream(), sym_ctx, + m_options.m_str.c_str(), m_options.m_use_regex)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; } + } + break; + } - result.SetStatus (eReturnStatusFailed); - return false; + return true; + } + + bool LookupInModule(CommandInterpreter &interpreter, Module *module, + CommandReturnObject &result, bool &syntax_error) { + switch (m_options.m_type) { + case eLookupTypeAddress: + if (m_options.m_addr != LLDB_INVALID_ADDRESS) { + if (LookupAddressInModule( + m_interpreter, result.GetOutputStream(), module, + eSymbolContextEverything | + (m_options.m_verbose + ? static_cast(eSymbolContextVariable) + : 0), + m_options.m_addr, m_options.m_offset, m_options.m_verbose)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + } + break; + + case eLookupTypeSymbol: + if (!m_options.m_str.empty()) { + if (LookupSymbolInModule(m_interpreter, result.GetOutputStream(), + module, m_options.m_str.c_str(), + m_options.m_use_regex, m_options.m_verbose)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + } + break; + + case eLookupTypeFileLine: + if (m_options.m_file) { + if (LookupFileAndLineInModule( + m_interpreter, result.GetOutputStream(), module, + m_options.m_file, m_options.m_line_number, + m_options.m_include_inlines, m_options.m_verbose)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + } + break; + + case eLookupTypeFunctionOrSymbol: + case eLookupTypeFunction: + if (!m_options.m_str.empty()) { + if (LookupFunctionInModule( + m_interpreter, result.GetOutputStream(), module, + m_options.m_str.c_str(), m_options.m_use_regex, + m_options.m_include_inlines, + m_options.m_type == + eLookupTypeFunctionOrSymbol, // include symbols + m_options.m_verbose)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + } + break; + + case eLookupTypeType: + if (!m_options.m_str.empty()) { + if (LookupTypeInModule(m_interpreter, result.GetOutputStream(), module, + m_options.m_str.c_str(), + m_options.m_use_regex)) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + } + break; + + default: + m_options.GenerateOptionUsage( + result.GetErrorStream(), this, + GetCommandInterpreter().GetDebugger().GetTerminalWidth()); + syntax_error = true; + break; } + result.SetStatus(eReturnStatusFailed); + return false; + } + protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + bool syntax_error = false; + uint32_t i; + uint32_t num_successful_lookups = 0; + uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); + result.GetOutputStream().SetAddressByteSize(addr_byte_size); + result.GetErrorStream().SetAddressByteSize(addr_byte_size); + // Dump all sections for all modules images + + if (command.GetArgumentCount() == 0) { + ModuleSP current_module; + + // Where it is possible to look in the current symbol context + // first, try that. If this search was successful and --all + // was not passed, don't print anything else. + if (LookupHere(m_interpreter, result, syntax_error)) { + result.GetOutputStream().EOL(); + num_successful_lookups++; + if (!m_options.m_print_all) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } } - else - { - bool syntax_error = false; - uint32_t i; - uint32_t num_successful_lookups = 0; - uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize(); - result.GetOutputStream().SetAddressByteSize(addr_byte_size); - result.GetErrorStream().SetAddressByteSize(addr_byte_size); - // Dump all sections for all modules images - - if (command.GetArgumentCount() == 0) - { - ModuleSP current_module; - - // Where it is possible to look in the current symbol context - // first, try that. If this search was successful and --all - // was not passed, don't print anything else. - if (LookupHere (m_interpreter, result, syntax_error)) - { - result.GetOutputStream().EOL(); - num_successful_lookups++; - if (!m_options.m_print_all) - { - result.SetStatus (eReturnStatusSuccessFinishResult); - return result.Succeeded(); - } - } - // Dump all sections for all other modules - - const ModuleList &target_modules = target->GetImages(); - std::lock_guard guard(target_modules.GetMutex()); - const size_t num_modules = target_modules.GetSize(); - if (num_modules > 0) - { - for (i = 0; i < num_modules && !syntax_error; ++i) - { - Module *module_pointer = target_modules.GetModulePointerAtIndexUnlocked(i); - - if (module_pointer != current_module.get() && - LookupInModule (m_interpreter, target_modules.GetModulePointerAtIndexUnlocked(i), result, syntax_error)) - { - result.GetOutputStream().EOL(); - num_successful_lookups++; - } - } - } - else - { - result.AppendError ("the target has no associated executable images"); - result.SetStatus (eReturnStatusFailed); - return false; - } + // Dump all sections for all other modules + + const ModuleList &target_modules = target->GetImages(); + std::lock_guard guard(target_modules.GetMutex()); + const size_t num_modules = target_modules.GetSize(); + if (num_modules > 0) { + for (i = 0; i < num_modules && !syntax_error; ++i) { + Module *module_pointer = + target_modules.GetModulePointerAtIndexUnlocked(i); + + if (module_pointer != current_module.get() && + LookupInModule( + m_interpreter, + target_modules.GetModulePointerAtIndexUnlocked(i), result, + syntax_error)) { + result.GetOutputStream().EOL(); + num_successful_lookups++; } - else - { - // Dump specified images (by basename or fullpath) - const char *arg_cstr; - for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != nullptr && !syntax_error; ++i) - { - ModuleList module_list; - const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, false); - if (num_matches > 0) - { - for (size_t j=0; j 0) { + for (size_t j = 0; j < num_matches; ++j) { + Module *module = module_list.GetModulePointerAtIndex(j); + if (module) { + if (LookupInModule(m_interpreter, module, result, + syntax_error)) { + result.GetOutputStream().EOL(); + num_successful_lookups++; } + } } - - if (num_successful_lookups > 0) - result.SetStatus (eReturnStatusSuccessFinishResult); - else - result.SetStatus (eReturnStatusFailed); + } else + result.AppendWarningWithFormat( + "Unable to find an image that matches '%s'.\n", arg_cstr); } - return result.Succeeded(); + } + + if (num_successful_lookups > 0) + result.SetStatus(eReturnStatusSuccessFinishResult); + else + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; OptionDefinition -CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Lookup an address in one or more target modules."}, {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "When looking up an address subtract from any addresses before doing the lookup."}, /* FIXME: re-enable regex for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_6 */ @@ -4340,7 +3819,7 @@ CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] = {LLDB_OPT_SET_ALL, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose lookup information."}, {LLDB_OPT_SET_ALL, false, "all", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Print all matches, not just the best match, if a best match is available."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #pragma mark CommandObjectMultiwordImageSearchPaths @@ -4349,22 +3828,33 @@ CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] = // CommandObjectMultiwordImageSearchPaths //------------------------------------------------------------------------- -class CommandObjectTargetModulesImageSearchPaths : public CommandObjectMultiword -{ +class CommandObjectTargetModulesImageSearchPaths + : public CommandObjectMultiword { public: - CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "target modules search-paths", - "Commands for managing module search paths for a target.", - "target modules search-paths []") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTargetModulesSearchPathsAdd (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectTargetModulesSearchPathsClear (interpreter))); - LoadSubCommand ("insert", CommandObjectSP (new CommandObjectTargetModulesSearchPathsInsert (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTargetModulesSearchPathsList (interpreter))); - LoadSubCommand ("query", CommandObjectSP (new CommandObjectTargetModulesSearchPathsQuery (interpreter))); - } - - ~CommandObjectTargetModulesImageSearchPaths() override = default; + CommandObjectTargetModulesImageSearchPaths(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "target modules search-paths", + "Commands for managing module search paths for a target.", + "target modules search-paths []") { + LoadSubCommand( + "add", CommandObjectSP( + new CommandObjectTargetModulesSearchPathsAdd(interpreter))); + LoadSubCommand( + "clear", CommandObjectSP(new CommandObjectTargetModulesSearchPathsClear( + interpreter))); + LoadSubCommand( + "insert", + CommandObjectSP( + new CommandObjectTargetModulesSearchPathsInsert(interpreter))); + LoadSubCommand( + "list", CommandObjectSP(new CommandObjectTargetModulesSearchPathsList( + interpreter))); + LoadSubCommand( + "query", CommandObjectSP(new CommandObjectTargetModulesSearchPathsQuery( + interpreter))); + } + + ~CommandObjectTargetModulesImageSearchPaths() override = default; }; #pragma mark CommandObjectTargetModules @@ -4373,455 +3863,431 @@ public: // CommandObjectTargetModules //------------------------------------------------------------------------- -class CommandObjectTargetModules : public CommandObjectMultiword -{ +class CommandObjectTargetModules : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectTargetModules(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "target modules", - "Commands for accessing information for one or more target modules.", - "target modules ...") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTargetModulesAdd (interpreter))); - LoadSubCommand ("load", CommandObjectSP (new CommandObjectTargetModulesLoad (interpreter))); - LoadSubCommand ("dump", CommandObjectSP (new CommandObjectTargetModulesDump (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTargetModulesList (interpreter))); - LoadSubCommand ("lookup", CommandObjectSP (new CommandObjectTargetModulesLookup (interpreter))); - LoadSubCommand ("search-paths", CommandObjectSP (new CommandObjectTargetModulesImageSearchPaths (interpreter))); - LoadSubCommand ("show-unwind", CommandObjectSP (new CommandObjectTargetModulesShowUnwind (interpreter))); - - } - - ~CommandObjectTargetModules() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectTargetModules(CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "target modules", + "Commands for accessing information for one or " + "more target modules.", + "target modules ...") { + LoadSubCommand( + "add", CommandObjectSP(new CommandObjectTargetModulesAdd(interpreter))); + LoadSubCommand("load", CommandObjectSP(new CommandObjectTargetModulesLoad( + interpreter))); + LoadSubCommand("dump", CommandObjectSP(new CommandObjectTargetModulesDump( + interpreter))); + LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetModulesList( + interpreter))); + LoadSubCommand( + "lookup", + CommandObjectSP(new CommandObjectTargetModulesLookup(interpreter))); + LoadSubCommand( + "search-paths", + CommandObjectSP( + new CommandObjectTargetModulesImageSearchPaths(interpreter))); + LoadSubCommand( + "show-unwind", + CommandObjectSP(new CommandObjectTargetModulesShowUnwind(interpreter))); + } + + ~CommandObjectTargetModules() override = default; private: - //------------------------------------------------------------------ - // For CommandObjectTargetModules only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetModules); + //------------------------------------------------------------------ + // For CommandObjectTargetModules only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetModules); }; -class CommandObjectTargetSymbolsAdd : public CommandObjectParsed -{ +class CommandObjectTargetSymbolsAdd : public CommandObjectParsed { public: - CommandObjectTargetSymbolsAdd (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target symbols add", - "Add a debug symbol file to one of the target's current modules by specifying a path to a debug symbols file, or using the options to specify a module to download symbols for.", - "target symbols add []", eCommandRequiresTarget), + CommandObjectTargetSymbolsAdd(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "target symbols add", + "Add a debug symbol file to one of the target's current modules by " + "specifying a path to a debug symbols file, or using the options " + "to specify a module to download symbols for.", + "target symbols add []", eCommandRequiresTarget), m_option_group(), - m_file_option (LLDB_OPT_SET_1, false, "shlib", 's', CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Fullpath or basename for module to find debug symbols for."), - m_current_frame_option (LLDB_OPT_SET_2, false, "frame", 'F', "Locate the debug symbols the currently selected frame.", false, true) - - { - m_option_group.Append (&m_uuid_option_group, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Append (&m_current_frame_option, LLDB_OPT_SET_2, LLDB_OPT_SET_2); - m_option_group.Finalize(); - } - - ~CommandObjectTargetSymbolsAdd() override = default; - - int - HandleArgumentCompletion (Args &input, - int &cursor_index, - int &cursor_char_position, - OptionElementVector &opt_element_vector, - int match_start_point, - int max_return_elements, - bool &word_complete, - StringList &matches) override - { - std::string completion_str (input.GetArgumentAtIndex(cursor_index)); - completion_str.erase (cursor_char_position); - - CommandCompletions::InvokeCommonCompletionCallbacks(GetCommandInterpreter(), - CommandCompletions::eDiskFileCompletion, - completion_str.c_str(), - match_start_point, - max_return_elements, - nullptr, - word_complete, - matches); - return matches.GetSize(); - } - - Options * - GetOptions () override - { - return &m_option_group; - } + m_file_option( + LLDB_OPT_SET_1, false, "shlib", 's', + CommandCompletions::eModuleCompletion, eArgTypeShlibName, + "Fullpath or basename for module to find debug symbols for."), + m_current_frame_option( + LLDB_OPT_SET_2, false, "frame", 'F', + "Locate the debug symbols the currently selected frame.", false, + true) + + { + m_option_group.Append(&m_uuid_option_group, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Append(&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); + m_option_group.Append(&m_current_frame_option, LLDB_OPT_SET_2, + LLDB_OPT_SET_2); + m_option_group.Finalize(); + } + + ~CommandObjectTargetSymbolsAdd() override = default; + + int HandleArgumentCompletion(Args &input, int &cursor_index, + int &cursor_char_position, + OptionElementVector &opt_element_vector, + int match_start_point, int max_return_elements, + bool &word_complete, + StringList &matches) override { + std::string completion_str(input.GetArgumentAtIndex(cursor_index)); + completion_str.erase(cursor_char_position); + + CommandCompletions::InvokeCommonCompletionCallbacks( + GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, + completion_str.c_str(), match_start_point, max_return_elements, nullptr, + word_complete, matches); + return matches.GetSize(); + } + + Options *GetOptions() override { return &m_option_group; } protected: - bool - AddModuleSymbols (Target *target, - ModuleSpec &module_spec, - bool &flush, - CommandReturnObject &result) - { - const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec(); - if (symbol_fspec) - { - char symfile_path[PATH_MAX]; - symbol_fspec.GetPath (symfile_path, sizeof(symfile_path)); - - if (!module_spec.GetUUID().IsValid()) - { - if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec()) - module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename(); - } - // We now have a module that represents a symbol file - // that can be used for a module that might exist in the - // current target, so we need to find that module in the - // target - ModuleList matching_module_list; - - size_t num_matches = 0; - // First extract all module specs from the symbol file - lldb_private::ModuleSpecList symfile_module_specs; - if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(), 0, 0, symfile_module_specs)) - { - // Now extract the module spec that matches the target architecture - ModuleSpec target_arch_module_spec; - ModuleSpec symfile_module_spec; - target_arch_module_spec.GetArchitecture() = target->GetArchitecture(); - if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec, symfile_module_spec)) - { - // See if it has a UUID? - if (symfile_module_spec.GetUUID().IsValid()) - { - // It has a UUID, look for this UUID in the target modules - ModuleSpec symfile_uuid_module_spec; - symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID(); - num_matches = target->GetImages().FindModules (symfile_uuid_module_spec, matching_module_list); - } - } - - if (num_matches == 0) - { - // No matches yet, iterate through the module specs to find a UUID value that - // we can match up to an image in our target - const size_t num_symfile_module_specs = symfile_module_specs.GetSize(); - for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0; ++i) - { - if (symfile_module_specs.GetModuleSpecAtIndex(i, symfile_module_spec)) - { - if (symfile_module_spec.GetUUID().IsValid()) - { - // It has a UUID, look for this UUID in the target modules - ModuleSpec symfile_uuid_module_spec; - symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID(); - num_matches = target->GetImages().FindModules (symfile_uuid_module_spec, matching_module_list); - } - } - } - } - } - - // Just try to match up the file by basename if we have no matches at this point - if (num_matches == 0) - num_matches = target->GetImages().FindModules (module_spec, matching_module_list); - - while (num_matches == 0) - { - ConstString filename_no_extension(module_spec.GetFileSpec().GetFileNameStrippingExtension()); - // Empty string returned, lets bail - if (!filename_no_extension) - break; - - // Check if there was no extension to strip and the basename is the same - if (filename_no_extension == module_spec.GetFileSpec().GetFilename()) - break; - - // Replace basename with one less extension - module_spec.GetFileSpec().GetFilename() = filename_no_extension; + bool AddModuleSymbols(Target *target, ModuleSpec &module_spec, bool &flush, + CommandReturnObject &result) { + const FileSpec &symbol_fspec = module_spec.GetSymbolFileSpec(); + if (symbol_fspec) { + char symfile_path[PATH_MAX]; + symbol_fspec.GetPath(symfile_path, sizeof(symfile_path)); + + if (!module_spec.GetUUID().IsValid()) { + if (!module_spec.GetFileSpec() && !module_spec.GetPlatformFileSpec()) + module_spec.GetFileSpec().GetFilename() = symbol_fspec.GetFilename(); + } + // We now have a module that represents a symbol file + // that can be used for a module that might exist in the + // current target, so we need to find that module in the + // target + ModuleList matching_module_list; + + size_t num_matches = 0; + // First extract all module specs from the symbol file + lldb_private::ModuleSpecList symfile_module_specs; + if (ObjectFile::GetModuleSpecifications(module_spec.GetSymbolFileSpec(), + 0, 0, symfile_module_specs)) { + // Now extract the module spec that matches the target architecture + ModuleSpec target_arch_module_spec; + ModuleSpec symfile_module_spec; + target_arch_module_spec.GetArchitecture() = target->GetArchitecture(); + if (symfile_module_specs.FindMatchingModuleSpec(target_arch_module_spec, + symfile_module_spec)) { + // See if it has a UUID? + if (symfile_module_spec.GetUUID().IsValid()) { + // It has a UUID, look for this UUID in the target modules + ModuleSpec symfile_uuid_module_spec; + symfile_uuid_module_spec.GetUUID() = symfile_module_spec.GetUUID(); + num_matches = target->GetImages().FindModules( + symfile_uuid_module_spec, matching_module_list); + } + } - num_matches = target->GetImages().FindModules (module_spec, matching_module_list); + if (num_matches == 0) { + // No matches yet, iterate through the module specs to find a UUID + // value that + // we can match up to an image in our target + const size_t num_symfile_module_specs = + symfile_module_specs.GetSize(); + for (size_t i = 0; i < num_symfile_module_specs && num_matches == 0; + ++i) { + if (symfile_module_specs.GetModuleSpecAtIndex( + i, symfile_module_spec)) { + if (symfile_module_spec.GetUUID().IsValid()) { + // It has a UUID, look for this UUID in the target modules + ModuleSpec symfile_uuid_module_spec; + symfile_uuid_module_spec.GetUUID() = + symfile_module_spec.GetUUID(); + num_matches = target->GetImages().FindModules( + symfile_uuid_module_spec, matching_module_list); + } } - - if (num_matches > 1) - { - result.AppendErrorWithFormat ("multiple modules match symbol file '%s', use the --uuid option to resolve the ambiguity.\n", symfile_path); + } + } + } + + // Just try to match up the file by basename if we have no matches at this + // point + if (num_matches == 0) + num_matches = + target->GetImages().FindModules(module_spec, matching_module_list); + + while (num_matches == 0) { + ConstString filename_no_extension( + module_spec.GetFileSpec().GetFileNameStrippingExtension()); + // Empty string returned, lets bail + if (!filename_no_extension) + break; + + // Check if there was no extension to strip and the basename is the same + if (filename_no_extension == module_spec.GetFileSpec().GetFilename()) + break; + + // Replace basename with one less extension + module_spec.GetFileSpec().GetFilename() = filename_no_extension; + + num_matches = + target->GetImages().FindModules(module_spec, matching_module_list); + } + + if (num_matches > 1) { + result.AppendErrorWithFormat("multiple modules match symbol file '%s', " + "use the --uuid option to resolve the " + "ambiguity.\n", + symfile_path); + } else if (num_matches == 1) { + ModuleSP module_sp(matching_module_list.GetModuleAtIndex(0)); + + // The module has not yet created its symbol vendor, we can just + // give the existing target module the symfile path to use for + // when it decides to create it! + module_sp->SetSymbolFileFileSpec(symbol_fspec); + + SymbolVendor *symbol_vendor = + module_sp->GetSymbolVendor(true, &result.GetErrorStream()); + if (symbol_vendor) { + SymbolFile *symbol_file = symbol_vendor->GetSymbolFile(); + + if (symbol_file) { + ObjectFile *object_file = symbol_file->GetObjectFile(); + + if (object_file && object_file->GetFileSpec() == symbol_fspec) { + // Provide feedback that the symfile has been successfully added. + const FileSpec &module_fs = module_sp->GetFileSpec(); + result.AppendMessageWithFormat( + "symbol file '%s' has been added to '%s'\n", symfile_path, + module_fs.GetPath().c_str()); + + // Let clients know something changed in the module + // if it is currently loaded + ModuleList module_list; + module_list.Append(module_sp); + target->SymbolsDidLoad(module_list); + + // Make sure we load any scripting resources that may be embedded + // in the debug info files in case the platform supports that. + Error error; + StreamString feedback_stream; + module_sp->LoadScriptingResourceInTarget(target, error, + &feedback_stream); + if (error.Fail() && error.AsCString()) + result.AppendWarningWithFormat( + "unable to load scripting data for module %s - error " + "reported was %s", + module_sp->GetFileSpec() + .GetFileNameStrippingExtension() + .GetCString(), + error.AsCString()); + else if (feedback_stream.GetSize()) + result.AppendWarningWithFormat("%s", feedback_stream.GetData()); + + flush = true; + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; } - else if (num_matches == 1) - { - ModuleSP module_sp (matching_module_list.GetModuleAtIndex(0)); - - // The module has not yet created its symbol vendor, we can just - // give the existing target module the symfile path to use for - // when it decides to create it! - module_sp->SetSymbolFileFileSpec (symbol_fspec); - - SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor(true, &result.GetErrorStream()); - if (symbol_vendor) - { - SymbolFile *symbol_file = symbol_vendor->GetSymbolFile(); - - if (symbol_file) - { - ObjectFile *object_file = symbol_file->GetObjectFile(); - - if (object_file && object_file->GetFileSpec() == symbol_fspec) - { - // Provide feedback that the symfile has been successfully added. - const FileSpec &module_fs = module_sp->GetFileSpec(); - result.AppendMessageWithFormat("symbol file '%s' has been added to '%s'\n", - symfile_path, - module_fs.GetPath().c_str()); - - // Let clients know something changed in the module - // if it is currently loaded - ModuleList module_list; - module_list.Append (module_sp); - target->SymbolsDidLoad (module_list); - - // Make sure we load any scripting resources that may be embedded - // in the debug info files in case the platform supports that. - Error error; - StreamString feedback_stream; - module_sp->LoadScriptingResourceInTarget (target, error,&feedback_stream); - if (error.Fail() && error.AsCString()) - result.AppendWarningWithFormat("unable to load scripting data for module %s - error reported was %s", - module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(), - error.AsCString()); - else if (feedback_stream.GetSize()) - result.AppendWarningWithFormat("%s",feedback_stream.GetData()); - - flush = true; - result.SetStatus (eReturnStatusSuccessFinishResult); - return true; - } - } + } + } + // Clear the symbol file spec if anything went wrong + module_sp->SetSymbolFileFileSpec(FileSpec()); + } + + if (module_spec.GetUUID().IsValid()) { + StreamString ss_symfile_uuid; + module_spec.GetUUID().Dump(&ss_symfile_uuid); + result.AppendErrorWithFormat( + "symbol file '%s' (%s) does not match any existing module%s\n", + symfile_path, ss_symfile_uuid.GetData(), + (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular) + ? "\n please specify the full path to the symbol file" + : ""); + } else { + result.AppendErrorWithFormat( + "symbol file '%s' does not match any existing module%s\n", + symfile_path, + (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular) + ? "\n please specify the full path to the symbol file" + : ""); + } + } else { + result.AppendError( + "one or more executable image paths must be specified"); + } + result.SetStatus(eReturnStatusFailed); + return false; + } + + bool DoExecute(Args &args, CommandReturnObject &result) override { + Target *target = m_exe_ctx.GetTargetPtr(); + result.SetStatus(eReturnStatusFailed); + bool flush = false; + ModuleSpec module_spec; + const bool uuid_option_set = + m_uuid_option_group.GetOptionValue().OptionWasSet(); + const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet(); + const bool frame_option_set = + m_current_frame_option.GetOptionValue().OptionWasSet(); + const size_t argc = args.GetArgumentCount(); + + if (argc == 0) { + if (uuid_option_set || file_option_set || frame_option_set) { + bool success = false; + bool error_set = false; + if (frame_option_set) { + Process *process = m_exe_ctx.GetProcessPtr(); + if (process) { + const StateType process_state = process->GetState(); + if (StateIsStoppedState(process_state, true)) { + StackFrame *frame = m_exe_ctx.GetFramePtr(); + if (frame) { + ModuleSP frame_module_sp( + frame->GetSymbolContext(eSymbolContextModule).module_sp); + if (frame_module_sp) { + if (frame_module_sp->GetPlatformFileSpec().Exists()) { + module_spec.GetArchitecture() = + frame_module_sp->GetArchitecture(); + module_spec.GetFileSpec() = + frame_module_sp->GetPlatformFileSpec(); + } + module_spec.GetUUID() = frame_module_sp->GetUUID(); + success = module_spec.GetUUID().IsValid() || + module_spec.GetFileSpec(); + } else { + result.AppendError("frame has no module"); + error_set = true; } - // Clear the symbol file spec if anything went wrong - module_sp->SetSymbolFileFileSpec (FileSpec()); + } else { + result.AppendError("invalid current frame"); + error_set = true; + } + } else { + result.AppendErrorWithFormat("process is not stopped: %s", + StateAsCString(process_state)); + error_set = true; } - - if (module_spec.GetUUID().IsValid()) - { - StreamString ss_symfile_uuid; - module_spec.GetUUID().Dump(&ss_symfile_uuid); - result.AppendErrorWithFormat ("symbol file '%s' (%s) does not match any existing module%s\n", - symfile_path, - ss_symfile_uuid.GetData(), - (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular) - ? "\n please specify the full path to the symbol file" - : ""); - } - else - { - result.AppendErrorWithFormat ("symbol file '%s' does not match any existing module%s\n", - symfile_path, - (symbol_fspec.GetFileType() != FileSpec::eFileTypeRegular) - ? "\n please specify the full path to the symbol file" - : ""); + } else { + result.AppendError( + "a process must exist in order to use the --frame option"); + error_set = true; + } + } else { + if (uuid_option_set) { + module_spec.GetUUID() = + m_uuid_option_group.GetOptionValue().GetCurrentValue(); + success |= module_spec.GetUUID().IsValid(); + } else if (file_option_set) { + module_spec.GetFileSpec() = + m_file_option.GetOptionValue().GetCurrentValue(); + ModuleSP module_sp( + target->GetImages().FindFirstModule(module_spec)); + if (module_sp) { + module_spec.GetFileSpec() = module_sp->GetFileSpec(); + module_spec.GetPlatformFileSpec() = + module_sp->GetPlatformFileSpec(); + module_spec.GetUUID() = module_sp->GetUUID(); + module_spec.GetArchitecture() = module_sp->GetArchitecture(); + } else { + module_spec.GetArchitecture() = target->GetArchitecture(); } + success |= module_spec.GetUUID().IsValid() || + module_spec.GetFileSpec().Exists(); + } } - else - { - result.AppendError ("one or more executable image paths must be specified"); - } - result.SetStatus (eReturnStatusFailed); - return false; - } - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Target *target = m_exe_ctx.GetTargetPtr(); - result.SetStatus (eReturnStatusFailed); - bool flush = false; - ModuleSpec module_spec; - const bool uuid_option_set = m_uuid_option_group.GetOptionValue().OptionWasSet(); - const bool file_option_set = m_file_option.GetOptionValue().OptionWasSet(); - const bool frame_option_set = m_current_frame_option.GetOptionValue().OptionWasSet(); - const size_t argc = args.GetArgumentCount(); - - if (argc == 0) - { - if (uuid_option_set || file_option_set || frame_option_set) - { - bool success = false; - bool error_set = false; - if (frame_option_set) - { - Process *process = m_exe_ctx.GetProcessPtr(); - if (process) - { - const StateType process_state = process->GetState(); - if (StateIsStoppedState (process_state, true)) - { - StackFrame *frame = m_exe_ctx.GetFramePtr(); - if (frame) - { - ModuleSP frame_module_sp (frame->GetSymbolContext(eSymbolContextModule).module_sp); - if (frame_module_sp) - { - if (frame_module_sp->GetPlatformFileSpec().Exists()) - { - module_spec.GetArchitecture() = frame_module_sp->GetArchitecture(); - module_spec.GetFileSpec() = frame_module_sp->GetPlatformFileSpec(); - } - module_spec.GetUUID() = frame_module_sp->GetUUID(); - success = module_spec.GetUUID().IsValid() || module_spec.GetFileSpec(); - } - else - { - result.AppendError ("frame has no module"); - error_set = true; - } - } - else - { - result.AppendError ("invalid current frame"); - error_set = true; - } - } - else - { - result.AppendErrorWithFormat ("process is not stopped: %s", StateAsCString(process_state)); - error_set = true; - } - } - else - { - result.AppendError ("a process must exist in order to use the --frame option"); - error_set = true; - } - } - else - { - if (uuid_option_set) - { - module_spec.GetUUID() = m_uuid_option_group.GetOptionValue().GetCurrentValue(); - success |= module_spec.GetUUID().IsValid(); - } - else if (file_option_set) - { - module_spec.GetFileSpec() = m_file_option.GetOptionValue().GetCurrentValue(); - ModuleSP module_sp (target->GetImages().FindFirstModule(module_spec)); - if (module_sp) - { - module_spec.GetFileSpec() = module_sp->GetFileSpec(); - module_spec.GetPlatformFileSpec() = module_sp->GetPlatformFileSpec(); - module_spec.GetUUID() = module_sp->GetUUID(); - module_spec.GetArchitecture() = module_sp->GetArchitecture(); - } - else - { - module_spec.GetArchitecture() = target->GetArchitecture(); - } - success |= module_spec.GetUUID().IsValid() || module_spec.GetFileSpec().Exists(); - } - } - if (success) - { - if (Symbols::DownloadObjectAndSymbolFile (module_spec)) - { - if (module_spec.GetSymbolFileSpec()) - success = AddModuleSymbols (target, module_spec, flush, result); - } - } + if (success) { + if (Symbols::DownloadObjectAndSymbolFile(module_spec)) { + if (module_spec.GetSymbolFileSpec()) + success = AddModuleSymbols(target, module_spec, flush, result); + } + } - if (!success && !error_set) - { - StreamString error_strm; - if (uuid_option_set) - { - error_strm.PutCString("unable to find debug symbols for UUID "); - module_spec.GetUUID().Dump (&error_strm); - } - else if (file_option_set) - { - error_strm.PutCString("unable to find debug symbols for the executable file "); - error_strm << module_spec.GetFileSpec(); - } - else if (frame_option_set) - { - error_strm.PutCString("unable to find debug symbols for the current frame"); - } - result.AppendError (error_strm.GetData()); - } - } - else - { - result.AppendError ("one or more symbol file paths must be specified, or options must be specified"); - } + if (!success && !error_set) { + StreamString error_strm; + if (uuid_option_set) { + error_strm.PutCString("unable to find debug symbols for UUID "); + module_spec.GetUUID().Dump(&error_strm); + } else if (file_option_set) { + error_strm.PutCString( + "unable to find debug symbols for the executable file "); + error_strm << module_spec.GetFileSpec(); + } else if (frame_option_set) { + error_strm.PutCString( + "unable to find debug symbols for the current frame"); + } + result.AppendError(error_strm.GetData()); } - else - { - if (uuid_option_set) - { - result.AppendError ("specify either one or more paths to symbol files or use the --uuid option without arguments"); - } - else if (file_option_set) - { - result.AppendError ("specify either one or more paths to symbol files or use the --file option without arguments"); + } else { + result.AppendError("one or more symbol file paths must be specified, " + "or options must be specified"); + } + } else { + if (uuid_option_set) { + result.AppendError("specify either one or more paths to symbol files " + "or use the --uuid option without arguments"); + } else if (file_option_set) { + result.AppendError("specify either one or more paths to symbol files " + "or use the --file option without arguments"); + } else if (frame_option_set) { + result.AppendError("specify either one or more paths to symbol files " + "or use the --frame option without arguments"); + } else { + PlatformSP platform_sp(target->GetPlatform()); + + for (size_t i = 0; i < argc; ++i) { + const char *symfile_path = args.GetArgumentAtIndex(i); + if (symfile_path) { + module_spec.GetSymbolFileSpec().SetFile(symfile_path, true); + if (platform_sp) { + FileSpec symfile_spec; + if (platform_sp + ->ResolveSymbolFile(*target, module_spec, symfile_spec) + .Success()) + module_spec.GetSymbolFileSpec() = symfile_spec; } - else if (frame_option_set) - { - result.AppendError ("specify either one or more paths to symbol files or use the --frame option without arguments"); - } - else - { - PlatformSP platform_sp (target->GetPlatform()); - - for (size_t i = 0; i < argc; ++i) - { - const char *symfile_path = args.GetArgumentAtIndex(i); - if (symfile_path) - { - module_spec.GetSymbolFileSpec().SetFile(symfile_path, true); - if (platform_sp) - { - FileSpec symfile_spec; - if (platform_sp->ResolveSymbolFile(*target, module_spec, symfile_spec).Success()) - module_spec.GetSymbolFileSpec() = symfile_spec; - } - ArchSpec arch; - bool symfile_exists = module_spec.GetSymbolFileSpec().Exists(); + ArchSpec arch; + bool symfile_exists = module_spec.GetSymbolFileSpec().Exists(); - if (symfile_exists) - { - if (!AddModuleSymbols (target, module_spec, flush, result)) - break; - } - else - { - char resolved_symfile_path[PATH_MAX]; - if (module_spec.GetSymbolFileSpec().GetPath (resolved_symfile_path, sizeof(resolved_symfile_path))) - { - if (strcmp (resolved_symfile_path, symfile_path) != 0) - { - result.AppendErrorWithFormat ("invalid module path '%s' with resolved path '%s'\n", symfile_path, resolved_symfile_path); - break; - } - } - result.AppendErrorWithFormat ("invalid module path '%s'\n", symfile_path); - break; - } - } + if (symfile_exists) { + if (!AddModuleSymbols(target, module_spec, flush, result)) + break; + } else { + char resolved_symfile_path[PATH_MAX]; + if (module_spec.GetSymbolFileSpec().GetPath( + resolved_symfile_path, sizeof(resolved_symfile_path))) { + if (strcmp(resolved_symfile_path, symfile_path) != 0) { + result.AppendErrorWithFormat( + "invalid module path '%s' with resolved path '%s'\n", + symfile_path, resolved_symfile_path); + break; } + } + result.AppendErrorWithFormat("invalid module path '%s'\n", + symfile_path); + break; } + } } + } + } - if (flush) - { - Process *process = m_exe_ctx.GetProcessPtr(); - if (process) - process->Flush(); - } - return result.Succeeded(); + if (flush) { + Process *process = m_exe_ctx.GetProcessPtr(); + if (process) + process->Flush(); } + return result.Succeeded(); + } - OptionGroupOptions m_option_group; - OptionGroupUUID m_uuid_option_group; - OptionGroupFile m_file_option; - OptionGroupBoolean m_current_frame_option; + OptionGroupOptions m_option_group; + OptionGroupUUID m_uuid_option_group; + OptionGroupFile m_file_option; + OptionGroupBoolean m_current_frame_option; }; #pragma mark CommandObjectTargetSymbols @@ -4830,26 +4296,27 @@ protected: // CommandObjectTargetSymbols //------------------------------------------------------------------------- -class CommandObjectTargetSymbols : public CommandObjectMultiword -{ +class CommandObjectTargetSymbols : public CommandObjectMultiword { public: - //------------------------------------------------------------------ - // Constructors and Destructors - //------------------------------------------------------------------ - CommandObjectTargetSymbols(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "target symbols", "Commands for adding and managing debug symbol files.", - "target symbols ...") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTargetSymbolsAdd (interpreter))); - } - - ~CommandObjectTargetSymbols() override = default; + //------------------------------------------------------------------ + // Constructors and Destructors + //------------------------------------------------------------------ + CommandObjectTargetSymbols(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "target symbols", + "Commands for adding and managing debug symbol files.", + "target symbols ...") { + LoadSubCommand( + "add", CommandObjectSP(new CommandObjectTargetSymbolsAdd(interpreter))); + } + + ~CommandObjectTargetSymbols() override = default; private: - //------------------------------------------------------------------ - // For CommandObjectTargetModules only - //------------------------------------------------------------------ - DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetSymbols); + //------------------------------------------------------------------ + // For CommandObjectTargetModules only + //------------------------------------------------------------------ + DISALLOW_COPY_AND_ASSIGN(CommandObjectTargetSymbols); }; #pragma mark CommandObjectTargetStopHookAdd @@ -4858,339 +4325,308 @@ private: // CommandObjectTargetStopHookAdd //------------------------------------------------------------------------- -class CommandObjectTargetStopHookAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectTargetStopHookAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_line_start(0), - m_line_end (UINT_MAX), - m_func_name_type_mask (eFunctionNameTypeAuto), - m_sym_ctx_specified (false), - m_thread_specified (false), - m_use_one_liner (false), - m_one_liner() - { - } - - ~CommandOptions() override = default; - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success; - - switch (short_option) - { - case 'c': - m_class_name = option_arg; - m_sym_ctx_specified = true; - break; - - case 'e': - m_line_end = StringConvert::ToUInt32 (option_arg, UINT_MAX, 0, &success); - if (!success) - { - error.SetErrorStringWithFormat ("invalid end line number: \"%s\"", option_arg); - break; - } - m_sym_ctx_specified = true; - break; - - case 'l': - m_line_start = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success) - { - error.SetErrorStringWithFormat ("invalid start line number: \"%s\"", option_arg); - break; - } - m_sym_ctx_specified = true; - break; - - case 'i': - m_no_inlines = true; - break; - - case 'n': - m_function_name = option_arg; - m_func_name_type_mask |= eFunctionNameTypeAuto; - m_sym_ctx_specified = true; - break; - - case 'f': - m_file_name = option_arg; - m_sym_ctx_specified = true; - break; - - case 's': - m_module_name = option_arg; - m_sym_ctx_specified = true; - break; - - case 't' : - m_thread_id = StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); - if (m_thread_id == LLDB_INVALID_THREAD_ID) - error.SetErrorStringWithFormat ("invalid thread id string '%s'", option_arg); - m_thread_specified = true; - break; - - case 'T': - m_thread_name = option_arg; - m_thread_specified = true; - break; - - case 'q': - m_queue_name = option_arg; - m_thread_specified = true; - break; - - case 'x': - m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_thread_id == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid thread index string '%s'", option_arg); - m_thread_specified = true; - break; - - case 'o': - m_use_one_liner = true; - m_one_liner = option_arg; - break; - - default: - error.SetErrorStringWithFormat ("unrecognized option %c.", short_option); - break; - } - return error; + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_line_start(0), m_line_end(UINT_MAX), + m_func_name_type_mask(eFunctionNameTypeAuto), + m_sym_ctx_specified(false), m_thread_specified(false), + m_use_one_liner(false), m_one_liner() {} + + ~CommandOptions() override = default; + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success; + + switch (short_option) { + case 'c': + m_class_name = option_arg; + m_sym_ctx_specified = true; + break; + + case 'e': + m_line_end = StringConvert::ToUInt32(option_arg, UINT_MAX, 0, &success); + if (!success) { + error.SetErrorStringWithFormat("invalid end line number: \"%s\"", + option_arg); + break; } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_class_name.clear(); - m_function_name.clear(); - m_line_start = 0; - m_line_end = UINT_MAX; - m_file_name.clear(); - m_module_name.clear(); - m_func_name_type_mask = eFunctionNameTypeAuto; - m_thread_id = LLDB_INVALID_THREAD_ID; - m_thread_index = UINT32_MAX; - m_thread_name.clear(); - m_queue_name.clear(); - - m_no_inlines = false; - m_sym_ctx_specified = false; - m_thread_specified = false; - - m_use_one_liner = false; - m_one_liner.clear(); + m_sym_ctx_specified = true; + break; + + case 'l': + m_line_start = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) { + error.SetErrorStringWithFormat("invalid start line number: \"%s\"", + option_arg); + break; } - - static OptionDefinition g_option_table[]; - - std::string m_class_name; - std::string m_function_name; - uint32_t m_line_start; - uint32_t m_line_end; - std::string m_file_name; - std::string m_module_name; - uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType. - lldb::tid_t m_thread_id; - uint32_t m_thread_index; - std::string m_thread_name; - std::string m_queue_name; - bool m_sym_ctx_specified; - bool m_no_inlines; - bool m_thread_specified; - // Instance variables to hold the values for one_liner options. - bool m_use_one_liner; - std::string m_one_liner; - }; - - CommandObjectTargetStopHookAdd (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target stop-hook add", - "Add a hook to be executed when the target stops.", - "target stop-hook add"), - IOHandlerDelegateMultiline ("DONE", IOHandlerDelegate::Completion::LLDBCommand), - m_options() - { + m_sym_ctx_specified = true; + break; + + case 'i': + m_no_inlines = true; + break; + + case 'n': + m_function_name = option_arg; + m_func_name_type_mask |= eFunctionNameTypeAuto; + m_sym_ctx_specified = true; + break; + + case 'f': + m_file_name = option_arg; + m_sym_ctx_specified = true; + break; + + case 's': + m_module_name = option_arg; + m_sym_ctx_specified = true; + break; + + case 't': + m_thread_id = + StringConvert::ToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0); + if (m_thread_id == LLDB_INVALID_THREAD_ID) + error.SetErrorStringWithFormat("invalid thread id string '%s'", + option_arg); + m_thread_specified = true; + break; + + case 'T': + m_thread_name = option_arg; + m_thread_specified = true; + break; + + case 'q': + m_queue_name = option_arg; + m_thread_specified = true; + break; + + case 'x': + m_thread_index = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_thread_id == UINT32_MAX) + error.SetErrorStringWithFormat("invalid thread index string '%s'", + option_arg); + m_thread_specified = true; + break; + + case 'o': + m_use_one_liner = true; + m_one_liner = option_arg; + break; + + default: + error.SetErrorStringWithFormat("unrecognized option %c.", short_option); + break; + } + return error; } - ~CommandObjectTargetStopHookAdd() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_class_name.clear(); + m_function_name.clear(); + m_line_start = 0; + m_line_end = UINT_MAX; + m_file_name.clear(); + m_module_name.clear(); + m_func_name_type_mask = eFunctionNameTypeAuto; + m_thread_id = LLDB_INVALID_THREAD_ID; + m_thread_index = UINT32_MAX; + m_thread_name.clear(); + m_queue_name.clear(); + + m_no_inlines = false; + m_sym_ctx_specified = false; + m_thread_specified = false; + + m_use_one_liner = false; + m_one_liner.clear(); } + static OptionDefinition g_option_table[]; + + std::string m_class_name; + std::string m_function_name; + uint32_t m_line_start; + uint32_t m_line_end; + std::string m_file_name; + std::string m_module_name; + uint32_t m_func_name_type_mask; // A pick from lldb::FunctionNameType. + lldb::tid_t m_thread_id; + uint32_t m_thread_index; + std::string m_thread_name; + std::string m_queue_name; + bool m_sym_ctx_specified; + bool m_no_inlines; + bool m_thread_specified; + // Instance variables to hold the values for one_liner options. + bool m_use_one_liner; + std::string m_one_liner; + }; + + CommandObjectTargetStopHookAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target stop-hook add", + "Add a hook to be executed when the target stops.", + "target stop-hook add"), + IOHandlerDelegateMultiline("DONE", + IOHandlerDelegate::Completion::LLDBCommand), + m_options() {} + + ~CommandObjectTargetStopHookAdd() override = default; + + Options *GetOptions() override { return &m_options; } + protected: - void - IOHandlerActivated (IOHandler &io_handler) override - { + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString( + "Enter your stop hook command(s). Type 'DONE' to end.\n"); + output_sp->Flush(); + } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &line) override { + if (m_stop_hook_sp) { + if (line.empty()) { + StreamFileSP error_sp(io_handler.GetErrorStreamFile()); + if (error_sp) { + error_sp->Printf("error: stop hook #%" PRIu64 + " aborted, no commands.\n", + m_stop_hook_sp->GetID()); + error_sp->Flush(); + } + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target) + target->RemoveStopHookByID(m_stop_hook_sp->GetID()); + } else { + m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line); StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString("Enter your stop hook command(s). Type 'DONE' to end.\n"); - output_sp->Flush(); + if (output_sp) { + output_sp->Printf("Stop hook #%" PRIu64 " added.\n", + m_stop_hook_sp->GetID()); + output_sp->Flush(); } + } + m_stop_hook_sp.reset(); } - - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &line) override - { - if (m_stop_hook_sp) - { - if (line.empty()) - { - StreamFileSP error_sp(io_handler.GetErrorStreamFile()); - if (error_sp) - { - error_sp->Printf("error: stop hook #%" PRIu64 " aborted, no commands.\n", m_stop_hook_sp->GetID()); - error_sp->Flush(); - } - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target) - target->RemoveStopHookByID(m_stop_hook_sp->GetID()); - } - else - { - m_stop_hook_sp->GetCommandPointer()->SplitIntoLines(line); - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->Printf("Stop hook #%" PRIu64 " added.\n", m_stop_hook_sp->GetID()); - output_sp->Flush(); - } - } - m_stop_hook_sp.reset(); + io_handler.SetIsDone(true); + } + + bool DoExecute(Args &command, CommandReturnObject &result) override { + m_stop_hook_sp.reset(); + + Target *target = GetSelectedOrDummyTarget(); + if (target) { + Target::StopHookSP new_hook_sp = target->CreateStopHook(); + + // First step, make the specifier. + std::unique_ptr specifier_ap; + if (m_options.m_sym_ctx_specified) { + specifier_ap.reset(new SymbolContextSpecifier( + m_interpreter.GetDebugger().GetSelectedTarget())); + + if (!m_options.m_module_name.empty()) { + specifier_ap->AddSpecification( + m_options.m_module_name.c_str(), + SymbolContextSpecifier::eModuleSpecified); } - io_handler.SetIsDone(true); - } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - m_stop_hook_sp.reset(); - - Target *target = GetSelectedOrDummyTarget(); - if (target) - { - Target::StopHookSP new_hook_sp = target->CreateStopHook(); - - // First step, make the specifier. - std::unique_ptr specifier_ap; - if (m_options.m_sym_ctx_specified) - { - specifier_ap.reset(new SymbolContextSpecifier(m_interpreter.GetDebugger().GetSelectedTarget())); - - if (!m_options.m_module_name.empty()) - { - specifier_ap->AddSpecification (m_options.m_module_name.c_str(), SymbolContextSpecifier::eModuleSpecified); - } - - if (!m_options.m_class_name.empty()) - { - specifier_ap->AddSpecification (m_options.m_class_name.c_str(), SymbolContextSpecifier::eClassOrNamespaceSpecified); - } - - if (!m_options.m_file_name.empty()) - { - specifier_ap->AddSpecification (m_options.m_file_name.c_str(), SymbolContextSpecifier::eFileSpecified); - } - - if (m_options.m_line_start != 0) - { - specifier_ap->AddLineSpecification (m_options.m_line_start, SymbolContextSpecifier::eLineStartSpecified); - } - if (m_options.m_line_end != UINT_MAX) - { - specifier_ap->AddLineSpecification (m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified); - } - - if (!m_options.m_function_name.empty()) - { - specifier_ap->AddSpecification (m_options.m_function_name.c_str(), SymbolContextSpecifier::eFunctionSpecified); - } - } - - if (specifier_ap) - new_hook_sp->SetSpecifier (specifier_ap.release()); - - // Next see if any of the thread options have been entered: + if (!m_options.m_class_name.empty()) { + specifier_ap->AddSpecification( + m_options.m_class_name.c_str(), + SymbolContextSpecifier::eClassOrNamespaceSpecified); + } - if (m_options.m_thread_specified) - { - ThreadSpec *thread_spec = new ThreadSpec(); + if (!m_options.m_file_name.empty()) { + specifier_ap->AddSpecification( + m_options.m_file_name.c_str(), + SymbolContextSpecifier::eFileSpecified); + } - if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) - { - thread_spec->SetTID (m_options.m_thread_id); - } + if (m_options.m_line_start != 0) { + specifier_ap->AddLineSpecification( + m_options.m_line_start, + SymbolContextSpecifier::eLineStartSpecified); + } - if (m_options.m_thread_index != UINT32_MAX) - thread_spec->SetIndex (m_options.m_thread_index); + if (m_options.m_line_end != UINT_MAX) { + specifier_ap->AddLineSpecification( + m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified); + } - if (!m_options.m_thread_name.empty()) - thread_spec->SetName (m_options.m_thread_name.c_str()); + if (!m_options.m_function_name.empty()) { + specifier_ap->AddSpecification( + m_options.m_function_name.c_str(), + SymbolContextSpecifier::eFunctionSpecified); + } + } - if (!m_options.m_queue_name.empty()) - thread_spec->SetQueueName (m_options.m_queue_name.c_str()); + if (specifier_ap) + new_hook_sp->SetSpecifier(specifier_ap.release()); - new_hook_sp->SetThreadSpecifier (thread_spec); + // Next see if any of the thread options have been entered: - } - if (m_options.m_use_one_liner) - { - // Use one-liner. - new_hook_sp->GetCommandPointer()->AppendString (m_options.m_one_liner.c_str()); - result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n", new_hook_sp->GetID()); - } - else - { - m_stop_hook_sp = new_hook_sp; - m_interpreter.GetLLDBCommandsFromIOHandler("> ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - nullptr); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions + if (m_options.m_thread_specified) { + ThreadSpec *thread_spec = new ThreadSpec(); - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); + if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID) { + thread_spec->SetTID(m_options.m_thread_id); } - return result.Succeeded(); + if (m_options.m_thread_index != UINT32_MAX) + thread_spec->SetIndex(m_options.m_thread_index); + + if (!m_options.m_thread_name.empty()) + thread_spec->SetName(m_options.m_thread_name.c_str()); + + if (!m_options.m_queue_name.empty()) + thread_spec->SetQueueName(m_options.m_queue_name.c_str()); + + new_hook_sp->SetThreadSpecifier(thread_spec); + } + if (m_options.m_use_one_liner) { + // Use one-liner. + new_hook_sp->GetCommandPointer()->AppendString( + m_options.m_one_liner.c_str()); + result.AppendMessageWithFormat("Stop hook #%" PRIu64 " added.\n", + new_hook_sp->GetID()); + } else { + m_stop_hook_sp = new_hook_sp; + m_interpreter.GetLLDBCommandsFromIOHandler( + "> ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + nullptr); // Baton for the "io_handler" that will be passed back + // into our IOHandlerDelegate functions + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + private: - CommandOptions m_options; - Target::StopHookSP m_stop_hook_sp; + CommandOptions m_options; + Target::StopHookSP m_stop_hook_sp; }; OptionDefinition -CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line breakpoint command inline. Be sure to surround it with quotes."}, {LLDB_OPT_SET_ALL, false, "shlib", 's', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eModuleCompletion, eArgTypeShlibName, "Set the module within which the stop-hook is to be run."}, {LLDB_OPT_SET_ALL, false, "thread-index", 'x', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadIndex, "The stop hook is run only for the thread whose index matches this argument."}, @@ -5203,7 +4639,7 @@ CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] = {LLDB_OPT_SET_2, false, "classname", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeClassName, "Specify the class within which the stop-hook is to be run."}, {LLDB_OPT_SET_3, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Set the function name within which the stop hook will be run."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; #pragma mark CommandObjectTargetStopHookDelete @@ -5212,71 +4648,56 @@ CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] = // CommandObjectTargetStopHookDelete //------------------------------------------------------------------------- -class CommandObjectTargetStopHookDelete : public CommandObjectParsed -{ +class CommandObjectTargetStopHookDelete : public CommandObjectParsed { public: - CommandObjectTargetStopHookDelete (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target stop-hook delete", - "Delete a stop-hook.", - "target stop-hook delete []") - { - } + CommandObjectTargetStopHookDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target stop-hook delete", + "Delete a stop-hook.", + "target stop-hook delete []") {} - ~CommandObjectTargetStopHookDelete() override = default; + ~CommandObjectTargetStopHookDelete() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (target) - { - // FIXME: see if we can use the breakpoint id style parser? - size_t num_args = command.GetArgumentCount(); - if (num_args == 0) - { - if (!m_interpreter.Confirm ("Delete all stop hooks?", true)) - { - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - target->RemoveAllStopHooks(); - } - } - else - { - bool success; - for (size_t i = 0; i < num_args; i++) - { - lldb::user_id_t user_id = StringConvert::ToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success); - if (!success) - { - result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i)); - result.SetStatus(eReturnStatusFailed); - return false; - } - success = target->RemoveStopHookByID (user_id); - if (!success) - { - result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i)); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (target) { + // FIXME: see if we can use the breakpoint id style parser? + size_t num_args = command.GetArgumentCount(); + if (num_args == 0) { + if (!m_interpreter.Confirm("Delete all stop hooks?", true)) { + result.SetStatus(eReturnStatusFailed); + return false; + } else { + target->RemoveAllStopHooks(); } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); + } else { + bool success; + for (size_t i = 0; i < num_args; i++) { + lldb::user_id_t user_id = StringConvert::ToUInt32( + command.GetArgumentAtIndex(i), 0, 0, &success); + if (!success) { + result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; + } + success = target->RemoveStopHookByID(user_id); + if (!success) { + result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; + } } - - return result.Succeeded(); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + + return result.Succeeded(); + } }; #pragma mark CommandObjectTargetStopHookEnableDisable @@ -5285,66 +4706,55 @@ protected: // CommandObjectTargetStopHookEnableDisable //------------------------------------------------------------------------- -class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed -{ +class CommandObjectTargetStopHookEnableDisable : public CommandObjectParsed { public: - CommandObjectTargetStopHookEnableDisable (CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax) : - CommandObjectParsed (interpreter, - name, - help, - syntax), - m_enable (enable) - { - } + CommandObjectTargetStopHookEnableDisable(CommandInterpreter &interpreter, + bool enable, const char *name, + const char *help, const char *syntax) + : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable) { + } - ~CommandObjectTargetStopHookEnableDisable() override = default; + ~CommandObjectTargetStopHookEnableDisable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (target) - { - // FIXME: see if we can use the breakpoint id style parser? - size_t num_args = command.GetArgumentCount(); - bool success; - - if (num_args == 0) - { - target->SetAllStopHooksActiveState (m_enable); - } - else - { - for (size_t i = 0; i < num_args; i++) - { - lldb::user_id_t user_id = StringConvert::ToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success); - if (!success) - { - result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i)); - result.SetStatus(eReturnStatusFailed); - return false; - } - success = target->SetStopHookActiveStateByID (user_id, m_enable); - if (!success) - { - result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i)); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (target) { + // FIXME: see if we can use the breakpoint id style parser? + size_t num_args = command.GetArgumentCount(); + bool success; + + if (num_args == 0) { + target->SetAllStopHooksActiveState(m_enable); + } else { + for (size_t i = 0; i < num_args; i++) { + lldb::user_id_t user_id = StringConvert::ToUInt32( + command.GetArgumentAtIndex(i), 0, 0, &success); + if (!success) { + result.AppendErrorWithFormat("invalid stop hook id: \"%s\".\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; + } + success = target->SetStopHookActiveStateByID(user_id, m_enable); + if (!success) { + result.AppendErrorWithFormat("unknown stop hook id: \"%s\".\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; + } } - return result.Succeeded(); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } + private: - bool m_enable; + bool m_enable; }; #pragma mark CommandObjectTargetStopHookList @@ -5353,49 +4763,39 @@ private: // CommandObjectTargetStopHookList //------------------------------------------------------------------------- -class CommandObjectTargetStopHookList : public CommandObjectParsed -{ +class CommandObjectTargetStopHookList : public CommandObjectParsed { public: - CommandObjectTargetStopHookList (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "target stop-hook list", - "List all stop-hooks.", - "target stop-hook list []") - { - } + CommandObjectTargetStopHookList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "target stop-hook list", + "List all stop-hooks.", + "target stop-hook list []") {} - ~CommandObjectTargetStopHookList() override = default; + ~CommandObjectTargetStopHookList() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = GetSelectedOrDummyTarget(); - if (!target) - { - result.AppendError ("invalid target\n"); - result.SetStatus (eReturnStatusFailed); - return result.Succeeded(); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = GetSelectedOrDummyTarget(); + if (!target) { + result.AppendError("invalid target\n"); + result.SetStatus(eReturnStatusFailed); + return result.Succeeded(); + } - size_t num_hooks = target->GetNumStopHooks (); - if (num_hooks == 0) - { - result.GetOutputStream().PutCString ("No stop hooks.\n"); - } - else - { - for (size_t i = 0; i < num_hooks; i++) - { - Target::StopHookSP this_hook = target->GetStopHookAtIndex (i); - if (i > 0) - result.GetOutputStream().PutCString ("\n"); - this_hook->GetDescription (&(result.GetOutputStream()), eDescriptionLevelFull); - } - } - result.SetStatus (eReturnStatusSuccessFinishResult); - return result.Succeeded(); + size_t num_hooks = target->GetNumStopHooks(); + if (num_hooks == 0) { + result.GetOutputStream().PutCString("No stop hooks.\n"); + } else { + for (size_t i = 0; i < num_hooks; i++) { + Target::StopHookSP this_hook = target->GetStopHookAtIndex(i); + if (i > 0) + result.GetOutputStream().PutCString("\n"); + this_hook->GetDescription(&(result.GetOutputStream()), + eDescriptionLevelFull); + } } + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; #pragma mark CommandObjectMultiwordTargetStopHooks @@ -5404,30 +4804,31 @@ protected: // CommandObjectMultiwordTargetStopHooks //------------------------------------------------------------------------- -class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword -{ +class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword { public: - CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "target stop-hook", - "Commands for operating on debugger target stop-hooks.", - "target stop-hook []") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTargetStopHookAdd (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTargetStopHookDelete (interpreter))); - LoadSubCommand ("disable", CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter, - false, - "target stop-hook disable []", - "Disable a stop-hook.", - "target stop-hook disable"))); - LoadSubCommand ("enable", CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter, - true, - "target stop-hook enable []", - "Enable a stop-hook.", - "target stop-hook enable"))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTargetStopHookList (interpreter))); - } - - ~CommandObjectMultiwordTargetStopHooks() override = default; + CommandObjectMultiwordTargetStopHooks(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "target stop-hook", + "Commands for operating on debugger target stop-hooks.", + "target stop-hook []") { + LoadSubCommand("add", CommandObjectSP( + new CommandObjectTargetStopHookAdd(interpreter))); + LoadSubCommand( + "delete", + CommandObjectSP(new CommandObjectTargetStopHookDelete(interpreter))); + LoadSubCommand("disable", + CommandObjectSP(new CommandObjectTargetStopHookEnableDisable( + interpreter, false, "target stop-hook disable []", + "Disable a stop-hook.", "target stop-hook disable"))); + LoadSubCommand("enable", + CommandObjectSP(new CommandObjectTargetStopHookEnableDisable( + interpreter, true, "target stop-hook enable []", + "Enable a stop-hook.", "target stop-hook enable"))); + LoadSubCommand("list", CommandObjectSP(new CommandObjectTargetStopHookList( + interpreter))); + } + + ~CommandObjectMultiwordTargetStopHooks() override = default; }; #pragma mark CommandObjectMultiwordTarget @@ -5436,18 +4837,28 @@ public: // CommandObjectMultiwordTarget //------------------------------------------------------------------------- -CommandObjectMultiwordTarget::CommandObjectMultiwordTarget(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "target", "Commands for operating on debugger targets.", - "target []") -{ - LoadSubCommand ("create", CommandObjectSP (new CommandObjectTargetCreate (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTargetDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTargetList (interpreter))); - LoadSubCommand ("select", CommandObjectSP (new CommandObjectTargetSelect (interpreter))); - LoadSubCommand ("stop-hook", CommandObjectSP (new CommandObjectMultiwordTargetStopHooks (interpreter))); - LoadSubCommand ("modules", CommandObjectSP (new CommandObjectTargetModules (interpreter))); - LoadSubCommand ("symbols", CommandObjectSP (new CommandObjectTargetSymbols (interpreter))); - LoadSubCommand ("variable", CommandObjectSP (new CommandObjectTargetVariable (interpreter))); +CommandObjectMultiwordTarget::CommandObjectMultiwordTarget( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "target", + "Commands for operating on debugger targets.", + "target []") { + LoadSubCommand("create", + CommandObjectSP(new CommandObjectTargetCreate(interpreter))); + LoadSubCommand("delete", + CommandObjectSP(new CommandObjectTargetDelete(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectTargetList(interpreter))); + LoadSubCommand("select", + CommandObjectSP(new CommandObjectTargetSelect(interpreter))); + LoadSubCommand( + "stop-hook", + CommandObjectSP(new CommandObjectMultiwordTargetStopHooks(interpreter))); + LoadSubCommand("modules", + CommandObjectSP(new CommandObjectTargetModules(interpreter))); + LoadSubCommand("symbols", + CommandObjectSP(new CommandObjectTargetSymbols(interpreter))); + LoadSubCommand("variable", + CommandObjectSP(new CommandObjectTargetVariable(interpreter))); } CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget() = default; diff --git a/lldb/source/Commands/CommandObjectTarget.h b/lldb/source/Commands/CommandObjectTarget.h index d99a2b07f9a..865534111ee 100644 --- a/lldb/source/Commands/CommandObjectTarget.h +++ b/lldb/source/Commands/CommandObjectTarget.h @@ -14,9 +14,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Interpreter/Options.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Interpreter/CommandObjectMultiword.h" +#include "lldb/Interpreter/Options.h" namespace lldb_private { @@ -24,13 +24,11 @@ namespace lldb_private { // CommandObjectMultiwordTarget //------------------------------------------------------------------------- -class CommandObjectMultiwordTarget : public CommandObjectMultiword -{ +class CommandObjectMultiwordTarget : public CommandObjectMultiword { public: + CommandObjectMultiwordTarget(CommandInterpreter &interpreter); - CommandObjectMultiwordTarget (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordTarget() override; + ~CommandObjectMultiwordTarget() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectThread.cpp b/lldb/source/Commands/CommandObjectThread.cpp index 9199c971a28..f2f7cdc212a 100644 --- a/lldb/source/Commands/CommandObjectThread.cpp +++ b/lldb/source/Commands/CommandObjectThread.cpp @@ -13,9 +13,8 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/lldb-private.h" -#include "lldb/Core/State.h" #include "lldb/Core/SourceManager.h" +#include "lldb/Core/State.h" #include "lldb/Core/ValueObject.h" #include "lldb/Host/Host.h" #include "lldb/Host/StringConvert.h" @@ -24,18 +23,19 @@ #include "lldb/Interpreter/Options.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/Function.h" -#include "lldb/Symbol/LineTable.h" #include "lldb/Symbol/LineEntry.h" +#include "lldb/Symbol/LineTable.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlan.h" +#include "lldb/Target/ThreadPlanStepInRange.h" #include "lldb/Target/ThreadPlanStepInstruction.h" #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Target/ThreadPlanStepRange.h" -#include "lldb/Target/ThreadPlanStepInRange.h" +#include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; @@ -44,750 +44,663 @@ using namespace lldb_private; // CommandObjectThreadBacktrace //------------------------------------------------------------------------- -class CommandObjectIterateOverThreads : public CommandObjectParsed -{ +class CommandObjectIterateOverThreads : public CommandObjectParsed { public: - CommandObjectIterateOverThreads (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax, - uint32_t flags) : - CommandObjectParsed (interpreter, name, help, syntax, flags) - { + CommandObjectIterateOverThreads(CommandInterpreter &interpreter, + const char *name, const char *help, + const char *syntax, uint32_t flags) + : CommandObjectParsed(interpreter, name, help, syntax, flags) {} + + ~CommandObjectIterateOverThreads() override = default; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + result.SetStatus(m_success_return); + + if (command.GetArgumentCount() == 0) { + Thread *thread = m_exe_ctx.GetThreadPtr(); + if (!HandleOneThread(thread->GetID(), result)) + return false; + return result.Succeeded(); } - ~CommandObjectIterateOverThreads() override = default; + // Use tids instead of ThreadSPs to prevent deadlocking problems which + // result from JIT-ing + // code while iterating over the (locked) ThreadSP list. + std::vector tids; - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - result.SetStatus (m_success_return); + if (command.GetArgumentCount() == 1 && + ::strcmp(command.GetArgumentAtIndex(0), "all") == 0) { + Process *process = m_exe_ctx.GetProcessPtr(); - if (command.GetArgumentCount() == 0) - { - Thread *thread = m_exe_ctx.GetThreadPtr(); - if (!HandleOneThread (thread->GetID(), result)) - return false; - return result.Succeeded(); - } + for (ThreadSP thread_sp : process->Threads()) + tids.push_back(thread_sp->GetID()); + } else { + const size_t num_args = command.GetArgumentCount(); + Process *process = m_exe_ctx.GetProcessPtr(); - // Use tids instead of ThreadSPs to prevent deadlocking problems which result from JIT-ing - // code while iterating over the (locked) ThreadSP list. - std::vector tids; + std::lock_guard guard( + process->GetThreadList().GetMutex()); - if (command.GetArgumentCount() == 1 && ::strcmp (command.GetArgumentAtIndex(0), "all") == 0) - { - Process *process = m_exe_ctx.GetProcessPtr(); + for (size_t i = 0; i < num_args; i++) { + bool success; - for (ThreadSP thread_sp : process->Threads()) - tids.push_back(thread_sp->GetID()); + uint32_t thread_idx = StringConvert::ToUInt32( + command.GetArgumentAtIndex(i), 0, 0, &success); + if (!success) { + result.AppendErrorWithFormat("invalid thread specification: \"%s\"\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - const size_t num_args = command.GetArgumentCount(); - Process *process = m_exe_ctx.GetProcessPtr(); - - std::lock_guard guard(process->GetThreadList().GetMutex()); - - for (size_t i = 0; i < num_args; i++) - { - bool success; - - uint32_t thread_idx = StringConvert::ToUInt32(command.GetArgumentAtIndex(i), 0, 0, &success); - if (!success) - { - result.AppendErrorWithFormat ("invalid thread specification: \"%s\"\n", command.GetArgumentAtIndex(i)); - result.SetStatus (eReturnStatusFailed); - return false; - } - - ThreadSP thread = process->GetThreadList().FindThreadByIndexID(thread_idx); - - if (!thread) - { - result.AppendErrorWithFormat ("no thread with index: \"%s\"\n", command.GetArgumentAtIndex(i)); - result.SetStatus (eReturnStatusFailed); - return false; - } - - tids.push_back(thread->GetID()); - } + + ThreadSP thread = + process->GetThreadList().FindThreadByIndexID(thread_idx); + + if (!thread) { + result.AppendErrorWithFormat("no thread with index: \"%s\"\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; } - uint32_t idx = 0; - for (const lldb::tid_t &tid : tids) - { - if (idx != 0 && m_add_return) - result.AppendMessage(""); + tids.push_back(thread->GetID()); + } + } - if (!HandleOneThread (tid, result)) - return false; + uint32_t idx = 0; + for (const lldb::tid_t &tid : tids) { + if (idx != 0 && m_add_return) + result.AppendMessage(""); - ++idx; - } - return result.Succeeded(); + if (!HandleOneThread(tid, result)) + return false; + + ++idx; } + return result.Succeeded(); + } protected: - // Override this to do whatever you need to do for one thread. - // - // If you return false, the iteration will stop, otherwise it will proceed. - // The result is set to m_success_return (defaults to eReturnStatusSuccessFinishResult) before the iteration, - // so you only need to set the return status in HandleOneThread if you want to indicate an error. - // If m_add_return is true, a blank line will be inserted between each of the listings (except the last one.) - - virtual bool - HandleOneThread (lldb::tid_t, CommandReturnObject &result) = 0; - - ReturnStatus m_success_return = eReturnStatusSuccessFinishResult; - bool m_add_return = true; + // Override this to do whatever you need to do for one thread. + // + // If you return false, the iteration will stop, otherwise it will proceed. + // The result is set to m_success_return (defaults to + // eReturnStatusSuccessFinishResult) before the iteration, + // so you only need to set the return status in HandleOneThread if you want to + // indicate an error. + // If m_add_return is true, a blank line will be inserted between each of the + // listings (except the last one.) + + virtual bool HandleOneThread(lldb::tid_t, CommandReturnObject &result) = 0; + + ReturnStatus m_success_return = eReturnStatusSuccessFinishResult; + bool m_add_return = true; }; //------------------------------------------------------------------------- // CommandObjectThreadBacktrace //------------------------------------------------------------------------- -class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads -{ +class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'c': - { - bool success; - int32_t input_count = StringConvert::ToSInt32 (option_arg, -1, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option); - if (input_count < -1) - m_count = UINT32_MAX; - else - m_count = input_count; - } - break; - case 's': - { - bool success; - m_start = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success) - error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option); - } - break; - case 'e': - { - bool success; - m_extended_backtrace = Args::StringToBoolean (option_arg, false, &success); - if (!success) - error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option); - } - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + ~CommandOptions() override = default; - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_count = UINT32_MAX; - m_start = 0; - m_extended_backtrace = false; - } + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + switch (short_option) { + case 'c': { + bool success; + int32_t input_count = + StringConvert::ToSInt32(option_arg, -1, 0, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid integer value for option '%c'", short_option); + if (input_count < -1) + m_count = UINT32_MAX; + else + m_count = input_count; + } break; + case 's': { + bool success; + m_start = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid integer value for option '%c'", short_option); + } break; + case 'e': { + bool success; + m_extended_backtrace = + Args::StringToBoolean(option_arg, false, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid boolean value for option '%c'", short_option); + } break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - // Options table: Required for subclasses of Options. + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_count = UINT32_MAX; + m_start = 0; + m_extended_backtrace = false; + } - static OptionDefinition g_option_table[]; + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Instance variables to hold the values for command options. - uint32_t m_count; - uint32_t m_start; - bool m_extended_backtrace; - }; + // Options table: Required for subclasses of Options. - CommandObjectThreadBacktrace(CommandInterpreter &interpreter) - : CommandObjectIterateOverThreads( - interpreter, "thread backtrace", "Show thread call stacks. Defaults to the current thread, thread " - "indexes can be specified as arguments. Use the thread-index \"all\" " - "to see all threads.", - nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), - m_options() - { - } + static OptionDefinition g_option_table[]; - ~CommandObjectThreadBacktrace() override = default; + // Instance variables to hold the values for command options. + uint32_t m_count; + uint32_t m_start; + bool m_extended_backtrace; + }; - Options * - GetOptions () override - { - return &m_options; - } + CommandObjectThreadBacktrace(CommandInterpreter &interpreter) + : CommandObjectIterateOverThreads( + interpreter, "thread backtrace", + "Show thread call stacks. Defaults to the current thread, thread " + "indexes can be specified as arguments. Use the thread-index " + "\"all\" " + "to see all threads.", + nullptr, + eCommandRequiresProcess | eCommandRequiresThread | + eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_options() {} -protected: - void - DoExtendedBacktrace (Thread *thread, CommandReturnObject &result) - { - SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime(); - if (runtime) - { - Stream &strm = result.GetOutputStream(); - const std::vector &types = runtime->GetExtendedBacktraceTypes(); - for (auto type : types) - { - ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread (thread->shared_from_this(), type); - if (ext_thread_sp && ext_thread_sp->IsValid ()) - { - const uint32_t num_frames_with_source = 0; - if (ext_thread_sp->GetStatus (strm, - m_options.m_start, - m_options.m_count, - num_frames_with_source)) - { - DoExtendedBacktrace (ext_thread_sp.get(), result); - } - } - } - } - } + ~CommandObjectThreadBacktrace() override = default; - bool - HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override - { - ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); - if (!thread_sp) - { - result.AppendErrorWithFormat ("thread disappeared while computing backtraces: 0x%" PRIx64 "\n", tid); - result.SetStatus (eReturnStatusFailed); - return false; - } + Options *GetOptions() override { return &m_options; } - Thread *thread = thread_sp.get(); +protected: + void DoExtendedBacktrace(Thread *thread, CommandReturnObject &result) { + SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime(); + if (runtime) { + Stream &strm = result.GetOutputStream(); + const std::vector &types = + runtime->GetExtendedBacktraceTypes(); + for (auto type : types) { + ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread( + thread->shared_from_this(), type); + if (ext_thread_sp && ext_thread_sp->IsValid()) { + const uint32_t num_frames_with_source = 0; + if (ext_thread_sp->GetStatus(strm, m_options.m_start, + m_options.m_count, + num_frames_with_source)) { + DoExtendedBacktrace(ext_thread_sp.get(), result); + } + } + } + } + } + + bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override { + ThreadSP thread_sp = + m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); + if (!thread_sp) { + result.AppendErrorWithFormat( + "thread disappeared while computing backtraces: 0x%" PRIx64 "\n", + tid); + result.SetStatus(eReturnStatusFailed); + return false; + } - Stream &strm = result.GetOutputStream(); + Thread *thread = thread_sp.get(); - // Don't show source context when doing backtraces. - const uint32_t num_frames_with_source = 0; + Stream &strm = result.GetOutputStream(); - if (!thread->GetStatus (strm, - m_options.m_start, - m_options.m_count, - num_frames_with_source)) - { - result.AppendErrorWithFormat ("error displaying backtrace for thread: \"0x%4.4x\"\n", thread->GetIndexID()); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (m_options.m_extended_backtrace) - { - DoExtendedBacktrace (thread, result); - } + // Don't show source context when doing backtraces. + const uint32_t num_frames_with_source = 0; - return true; + if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count, + num_frames_with_source)) { + result.AppendErrorWithFormat( + "error displaying backtrace for thread: \"0x%4.4x\"\n", + thread->GetIndexID()); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (m_options.m_extended_backtrace) { + DoExtendedBacktrace(thread, result); } - CommandOptions m_options; + return true; + } + + CommandOptions m_options; }; OptionDefinition -CommandObjectThreadBacktrace::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectThreadBacktrace::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many frames to display (-1 for all)"}, {LLDB_OPT_SET_1, false, "start", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame in which to start the backtrace"}, {LLDB_OPT_SET_1, false, "extended", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Show the extended backtrace, if available"}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -enum StepScope -{ - eStepScopeSource, - eStepScopeInstruction -}; +enum StepScope { eStepScopeSource, eStepScopeInstruction }; -class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed -{ +class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - { - bool success; - bool avoid_no_debug = Args::StringToBoolean (option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option); - else - { - m_step_in_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo; - } - } - break; - - case 'A': - { - bool success; - bool avoid_no_debug = Args::StringToBoolean (option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option); - else - { - m_step_out_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo; - } - } - break; - - case 'c': - m_step_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_step_count == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid step count '%s'", option_arg); - break; - - case 'C': - m_class_name.clear(); - m_class_name.assign(option_arg); - break; - - case 'm': - { - OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values; - m_run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error); - } - break; - - case 'e': - { - if (strcmp(option_arg, "block") == 0) - { - m_end_line_is_block_end = 1; - break; - } - uint32_t tmp_end_line = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (tmp_end_line == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid end line number '%s'", option_arg); - else - m_end_line = tmp_end_line; - break; - } - break; - - case 'r': - m_avoid_regexp.clear(); - m_avoid_regexp.assign(option_arg); - break; - - case 't': - m_step_in_target.clear(); - m_step_in_target.assign(option_arg); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + ~CommandOptions() override = default; - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_step_in_avoid_no_debug = eLazyBoolCalculate; - m_step_out_avoid_no_debug = eLazyBoolCalculate; - m_run_mode = eOnlyDuringStepping; - - // Check if we are in Non-Stop mode - TargetSP target_sp = - execution_context ? execution_context->GetTargetSP() : - TargetSP(); - if (target_sp && target_sp->GetNonStopModeEnabled()) - m_run_mode = eOnlyThisThread; - - m_avoid_regexp.clear(); - m_step_in_target.clear(); - m_class_name.clear(); - m_step_count = 1; - m_end_line = LLDB_INVALID_LINE_NUMBER; - m_end_line_is_block_end = false; - } + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; + switch (short_option) { + case 'a': { + bool success; + bool avoid_no_debug = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid boolean value for option '%c'", short_option); + else { + m_step_in_avoid_no_debug = + avoid_no_debug ? eLazyBoolYes : eLazyBoolNo; } + } break; - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - LazyBool m_step_in_avoid_no_debug; - LazyBool m_step_out_avoid_no_debug; - RunMode m_run_mode; - std::string m_avoid_regexp; - std::string m_step_in_target; - std::string m_class_name; - uint32_t m_step_count; - uint32_t m_end_line; - bool m_end_line_is_block_end; - }; - - CommandObjectThreadStepWithTypeAndScope (CommandInterpreter &interpreter, - const char *name, - const char *help, - const char *syntax, - StepType step_type, - StepScope step_scope) : - CommandObjectParsed (interpreter, name, help, syntax, - eCommandRequiresProcess | - eCommandRequiresThread | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_step_type (step_type), - m_step_scope (step_scope), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData thread_id_arg; - - // Define the first (and only) variant of this arg. - thread_id_arg.arg_type = eArgTypeThreadID; - thread_id_arg.arg_repetition = eArgRepeatOptional; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (thread_id_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + case 'A': { + bool success; + bool avoid_no_debug = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid boolean value for option '%c'", short_option); + else { + m_step_out_avoid_no_debug = + avoid_no_debug ? eLazyBoolYes : eLazyBoolNo; + } + } break; + + case 'c': + m_step_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_step_count == UINT32_MAX) + error.SetErrorStringWithFormat("invalid step count '%s'", option_arg); + break; + + case 'C': + m_class_name.clear(); + m_class_name.assign(option_arg); + break; + + case 'm': { + OptionEnumValueElement *enum_values = + g_option_table[option_idx].enum_values; + m_run_mode = (lldb::RunMode)Args::StringToOptionEnum( + option_arg, enum_values, eOnlyDuringStepping, error); + } break; + + case 'e': { + if (strcmp(option_arg, "block") == 0) { + m_end_line_is_block_end = 1; + break; + } + uint32_t tmp_end_line = + StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (tmp_end_line == UINT32_MAX) + error.SetErrorStringWithFormat("invalid end line number '%s'", + option_arg); + else + m_end_line = tmp_end_line; + break; + } break; + + case 'r': + m_avoid_regexp.clear(); + m_avoid_regexp.assign(option_arg); + break; + + case 't': + m_step_in_target.clear(); + m_step_in_target.assign(option_arg); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; } - ~CommandObjectThreadStepWithTypeAndScope() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_step_in_avoid_no_debug = eLazyBoolCalculate; + m_step_out_avoid_no_debug = eLazyBoolCalculate; + m_run_mode = eOnlyDuringStepping; + + // Check if we are in Non-Stop mode + TargetSP target_sp = + execution_context ? execution_context->GetTargetSP() : TargetSP(); + if (target_sp && target_sp->GetNonStopModeEnabled()) + m_run_mode = eOnlyThisThread; + + m_avoid_regexp.clear(); + m_step_in_target.clear(); + m_class_name.clear(); + m_step_count = 1; + m_end_line = LLDB_INVALID_LINE_NUMBER; + m_end_line_is_block_end = false; } -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - bool synchronous_execution = m_interpreter.GetSynchronous(); - - const uint32_t num_threads = process->GetThreadList().GetSize(); - Thread *thread = nullptr; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + LazyBool m_step_in_avoid_no_debug; + LazyBool m_step_out_avoid_no_debug; + RunMode m_run_mode; + std::string m_avoid_regexp; + std::string m_step_in_target; + std::string m_class_name; + uint32_t m_step_count; + uint32_t m_end_line; + bool m_end_line_is_block_end; + }; + + CommandObjectThreadStepWithTypeAndScope(CommandInterpreter &interpreter, + const char *name, const char *help, + const char *syntax, + StepType step_type, + StepScope step_scope) + : CommandObjectParsed(interpreter, name, help, syntax, + eCommandRequiresProcess | eCommandRequiresThread | + eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_step_type(step_type), m_step_scope(step_scope), m_options() { + CommandArgumentEntry arg; + CommandArgumentData thread_id_arg; + + // Define the first (and only) variant of this arg. + thread_id_arg.arg_type = eArgTypeThreadID; + thread_id_arg.arg_repetition = eArgRepeatOptional; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(thread_id_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectThreadStepWithTypeAndScope() override = default; + + Options *GetOptions() override { return &m_options; } - if (command.GetArgumentCount() == 0) - { - thread = GetDefaultThread(); +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + bool synchronous_execution = m_interpreter.GetSynchronous(); + + const uint32_t num_threads = process->GetThreadList().GetSize(); + Thread *thread = nullptr; + + if (command.GetArgumentCount() == 0) { + thread = GetDefaultThread(); + + if (thread == nullptr) { + result.AppendError("no selected thread in process"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + const char *thread_idx_cstr = command.GetArgumentAtIndex(0); + uint32_t step_thread_idx = + StringConvert::ToUInt32(thread_idx_cstr, LLDB_INVALID_INDEX32); + if (step_thread_idx == LLDB_INVALID_INDEX32) { + result.AppendErrorWithFormat("invalid thread index '%s'.\n", + thread_idx_cstr); + result.SetStatus(eReturnStatusFailed); + return false; + } + thread = + process->GetThreadList().FindThreadByIndexID(step_thread_idx).get(); + if (thread == nullptr) { + result.AppendErrorWithFormat( + "Thread index %u is out of range (valid values are 0 - %u).\n", + step_thread_idx, num_threads); + result.SetStatus(eReturnStatusFailed); + return false; + } + } - if (thread == nullptr) - { - result.AppendError ("no selected thread in process"); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - const char *thread_idx_cstr = command.GetArgumentAtIndex(0); - uint32_t step_thread_idx = StringConvert::ToUInt32 (thread_idx_cstr, LLDB_INVALID_INDEX32); - if (step_thread_idx == LLDB_INVALID_INDEX32) - { - result.AppendErrorWithFormat ("invalid thread index '%s'.\n", thread_idx_cstr); - result.SetStatus (eReturnStatusFailed); - return false; - } - thread = process->GetThreadList().FindThreadByIndexID(step_thread_idx).get(); - if (thread == nullptr) - { - result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n", - step_thread_idx, num_threads); - result.SetStatus (eReturnStatusFailed); - return false; - } - } + if (m_step_type == eStepTypeScripted) { + if (m_options.m_class_name.empty()) { + result.AppendErrorWithFormat("empty class name for scripted step."); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists( + m_options.m_class_name.c_str())) { + result.AppendErrorWithFormat( + "class for scripted step: \"%s\" does not exist.", + m_options.m_class_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } - if (m_step_type == eStepTypeScripted) - { - if (m_options.m_class_name.empty()) - { - result.AppendErrorWithFormat ("empty class name for scripted step."); - result.SetStatus(eReturnStatusFailed); - return false; - } - else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists(m_options.m_class_name.c_str())) - { - result.AppendErrorWithFormat ("class for scripted step: \"%s\" does not exist.", m_options.m_class_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } + if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER && + m_step_type != eStepTypeInto) { + result.AppendErrorWithFormat( + "end line option is only valid for step into"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER - && m_step_type != eStepTypeInto) - { - result.AppendErrorWithFormat("end line option is only valid for step into"); + const bool abort_other_plans = false; + const lldb::RunMode stop_other_threads = m_options.m_run_mode; + + // This is a bit unfortunate, but not all the commands in this command + // object support + // only while stepping, so I use the bool for them. + bool bool_stop_other_threads; + if (m_options.m_run_mode == eAllThreads) + bool_stop_other_threads = false; + else if (m_options.m_run_mode == eOnlyDuringStepping) + bool_stop_other_threads = + (m_step_type != eStepTypeOut && m_step_type != eStepTypeScripted); + else + bool_stop_other_threads = true; + + ThreadPlanSP new_plan_sp; + + if (m_step_type == eStepTypeInto) { + StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); + assert(frame != nullptr); + + if (frame->HasDebugInformation()) { + AddressRange range; + SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything); + if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) { + Error error; + if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range, + error)) { + result.AppendErrorWithFormat("invalid end-line option: %s.", + error.AsCString()); result.SetStatus(eReturnStatusFailed); return false; - } - - const bool abort_other_plans = false; - const lldb::RunMode stop_other_threads = m_options.m_run_mode; - - // This is a bit unfortunate, but not all the commands in this command object support - // only while stepping, so I use the bool for them. - bool bool_stop_other_threads; - if (m_options.m_run_mode == eAllThreads) - bool_stop_other_threads = false; - else if (m_options.m_run_mode == eOnlyDuringStepping) - bool_stop_other_threads = (m_step_type != eStepTypeOut && m_step_type != eStepTypeScripted); - else - bool_stop_other_threads = true; - - ThreadPlanSP new_plan_sp; - - if (m_step_type == eStepTypeInto) - { - StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); - assert(frame != nullptr); - - if (frame->HasDebugInformation ()) - { - AddressRange range; - SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything); - if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) - { - Error error; - if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range, error)) - { - result.AppendErrorWithFormat("invalid end-line option: %s.", error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else if (m_options.m_end_line_is_block_end) - { - Error error; - Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; - if (!block) - { - result.AppendErrorWithFormat("Could not find the current block."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - AddressRange block_range; - Address pc_address = frame->GetFrameCodeAddress(); - block->GetRangeContainingAddress(pc_address, block_range); - if (!block_range.GetBaseAddress().IsValid()) - { - result.AppendErrorWithFormat("Could not find the current block address."); - result.SetStatus(eReturnStatusFailed); - return false; - } - lldb::addr_t pc_offset_in_block = pc_address.GetFileAddress() - block_range.GetBaseAddress().GetFileAddress(); - lldb::addr_t range_length = block_range.GetByteSize() - pc_offset_in_block; - range = AddressRange(pc_address, range_length); - } - else - { - range = sc.line_entry.range; - } - - new_plan_sp = thread->QueueThreadPlanForStepInRange (abort_other_plans, - range, - frame->GetSymbolContext(eSymbolContextEverything), - m_options.m_step_in_target.c_str(), - stop_other_threads, - m_options.m_step_in_avoid_no_debug, - m_options.m_step_out_avoid_no_debug); - - if (new_plan_sp && !m_options.m_avoid_regexp.empty()) - { - ThreadPlanStepInRange *step_in_range_plan = static_cast (new_plan_sp.get()); - step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str()); - } - } - else - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads); - } - else if (m_step_type == eStepTypeOver) - { - StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); - - if (frame->HasDebugInformation()) - new_plan_sp = thread->QueueThreadPlanForStepOverRange (abort_other_plans, - frame->GetSymbolContext(eSymbolContextEverything).line_entry, - frame->GetSymbolContext(eSymbolContextEverything), - stop_other_threads, - m_options.m_step_out_avoid_no_debug); - else - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true, - abort_other_plans, - bool_stop_other_threads); - } - else if (m_step_type == eStepTypeTrace) - { - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads); - } - else if (m_step_type == eStepTypeTraceOver) - { - new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true, abort_other_plans, bool_stop_other_threads); - } - else if (m_step_type == eStepTypeOut) - { - new_plan_sp = thread->QueueThreadPlanForStepOut(abort_other_plans, - nullptr, - false, - bool_stop_other_threads, - eVoteYes, - eVoteNoOpinion, - thread->GetSelectedFrameIndex(), - m_options.m_step_out_avoid_no_debug); - } - else if (m_step_type == eStepTypeScripted) - { - new_plan_sp = thread->QueueThreadPlanForStepScripted (abort_other_plans, - m_options.m_class_name.c_str(), - bool_stop_other_threads); - } - else - { - result.AppendError ("step type is not supported"); - result.SetStatus (eReturnStatusFailed); + } + } else if (m_options.m_end_line_is_block_end) { + Error error; + Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; + if (!block) { + result.AppendErrorWithFormat("Could not find the current block."); + result.SetStatus(eReturnStatusFailed); return false; - } - - // If we got a new plan, then set it to be a master plan (User level Plans should be master plans - // so that they can be interruptible). Then resume the process. - - if (new_plan_sp) - { - new_plan_sp->SetIsMasterPlan (true); - new_plan_sp->SetOkayToDiscard (false); - - if (m_options.m_step_count > 1) - { - if (new_plan_sp->SetIterationCount(m_options.m_step_count)) - { - result.AppendWarning ("step operation does not support iteration count."); - } - } - - process->GetThreadList().SetSelectedThreadByID (thread->GetID()); - - const uint32_t iohandler_id = process->GetIOHandlerID(); - - StreamString stream; - Error error; - if (synchronous_execution) - error = process->ResumeSynchronous (&stream); - else - error = process->Resume (); - - // There is a race condition where this thread will return up the call stack to the main command handler - // and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has - // a chance to call PushProcessIOHandler(). - process->SyncIOHandler(iohandler_id, 2000); - - if (synchronous_execution) - { - // If any state changed events had anything to say, add that to the result - if (stream.GetData()) - result.AppendMessage(stream.GetData()); + } + + AddressRange block_range; + Address pc_address = frame->GetFrameCodeAddress(); + block->GetRangeContainingAddress(pc_address, block_range); + if (!block_range.GetBaseAddress().IsValid()) { + result.AppendErrorWithFormat( + "Could not find the current block address."); + result.SetStatus(eReturnStatusFailed); + return false; + } + lldb::addr_t pc_offset_in_block = + pc_address.GetFileAddress() - + block_range.GetBaseAddress().GetFileAddress(); + lldb::addr_t range_length = + block_range.GetByteSize() - pc_offset_in_block; + range = AddressRange(pc_address, range_length); + } else { + range = sc.line_entry.range; + } + + new_plan_sp = thread->QueueThreadPlanForStepInRange( + abort_other_plans, range, + frame->GetSymbolContext(eSymbolContextEverything), + m_options.m_step_in_target.c_str(), stop_other_threads, + m_options.m_step_in_avoid_no_debug, + m_options.m_step_out_avoid_no_debug); + + if (new_plan_sp && !m_options.m_avoid_regexp.empty()) { + ThreadPlanStepInRange *step_in_range_plan = + static_cast(new_plan_sp.get()); + step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str()); + } + } else + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + false, abort_other_plans, bool_stop_other_threads); + } else if (m_step_type == eStepTypeOver) { + StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); + + if (frame->HasDebugInformation()) + new_plan_sp = thread->QueueThreadPlanForStepOverRange( + abort_other_plans, + frame->GetSymbolContext(eSymbolContextEverything).line_entry, + frame->GetSymbolContext(eSymbolContextEverything), + stop_other_threads, m_options.m_step_out_avoid_no_debug); + else + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + true, abort_other_plans, bool_stop_other_threads); + } else if (m_step_type == eStepTypeTrace) { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + false, abort_other_plans, bool_stop_other_threads); + } else if (m_step_type == eStepTypeTraceOver) { + new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction( + true, abort_other_plans, bool_stop_other_threads); + } else if (m_step_type == eStepTypeOut) { + new_plan_sp = thread->QueueThreadPlanForStepOut( + abort_other_plans, nullptr, false, bool_stop_other_threads, eVoteYes, + eVoteNoOpinion, thread->GetSelectedFrameIndex(), + m_options.m_step_out_avoid_no_debug); + } else if (m_step_type == eStepTypeScripted) { + new_plan_sp = thread->QueueThreadPlanForStepScripted( + abort_other_plans, m_options.m_class_name.c_str(), + bool_stop_other_threads); + } else { + result.AppendError("step type is not supported"); + result.SetStatus(eReturnStatusFailed); + return false; + } - process->GetThreadList().SetSelectedThreadByID (thread->GetID()); - result.SetDidChangeProcessState (true); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.SetStatus (eReturnStatusSuccessContinuingNoResult); - } - } - else - { - result.AppendError ("Couldn't find thread plan to implement step type."); - result.SetStatus (eReturnStatusFailed); - } - return result.Succeeded(); + // If we got a new plan, then set it to be a master plan (User level Plans + // should be master plans + // so that they can be interruptible). Then resume the process. + + if (new_plan_sp) { + new_plan_sp->SetIsMasterPlan(true); + new_plan_sp->SetOkayToDiscard(false); + + if (m_options.m_step_count > 1) { + if (new_plan_sp->SetIterationCount(m_options.m_step_count)) { + result.AppendWarning( + "step operation does not support iteration count."); + } + } + + process->GetThreadList().SetSelectedThreadByID(thread->GetID()); + + const uint32_t iohandler_id = process->GetIOHandlerID(); + + StreamString stream; + Error error; + if (synchronous_execution) + error = process->ResumeSynchronous(&stream); + else + error = process->Resume(); + + // There is a race condition where this thread will return up the call + // stack to the main command handler + // and show an (lldb) prompt before HandlePrivateEvent (from + // PrivateStateThread) has + // a chance to call PushProcessIOHandler(). + process->SyncIOHandler(iohandler_id, 2000); + + if (synchronous_execution) { + // If any state changed events had anything to say, add that to the + // result + if (stream.GetData()) + result.AppendMessage(stream.GetData()); + + process->GetThreadList().SetSelectedThreadByID(thread->GetID()); + result.SetDidChangeProcessState(true); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.SetStatus(eReturnStatusSuccessContinuingNoResult); + } + } else { + result.AppendError("Couldn't find thread plan to implement step type."); + result.SetStatus(eReturnStatusFailed); } + return result.Succeeded(); + } protected: - StepType m_step_type; - StepScope m_step_scope; - CommandOptions m_options; + StepType m_step_type; + StepScope m_step_scope; + CommandOptions m_options; }; -static OptionEnumValueElement -g_tri_running_mode[] = -{ -{ eOnlyThisThread, "this-thread", "Run only this thread"}, -{ eAllThreads, "all-threads", "Run all threads"}, -{ eOnlyDuringStepping, "while-stepping", "Run only this thread while stepping"}, -{ 0, nullptr, nullptr } -}; - -static OptionEnumValueElement -g_duo_running_mode[] = -{ -{ eOnlyThisThread, "this-thread", "Run only this thread"}, -{ eAllThreads, "all-threads", "Run all threads"}, -{ 0, nullptr, nullptr } -}; - -OptionDefinition -CommandObjectThreadStepWithTypeAndScope::CommandOptions::g_option_table[] = -{ - // clang-format off +static OptionEnumValueElement g_tri_running_mode[] = { + {eOnlyThisThread, "this-thread", "Run only this thread"}, + {eAllThreads, "all-threads", "Run all threads"}, + {eOnlyDuringStepping, "while-stepping", + "Run only this thread while stepping"}, + {0, nullptr, nullptr}}; + +static OptionEnumValueElement g_duo_running_mode[] = { + {eOnlyThisThread, "this-thread", "Run only this thread"}, + {eAllThreads, "all-threads", "Run all threads"}, + {0, nullptr, nullptr}}; + +OptionDefinition CommandObjectThreadStepWithTypeAndScope::CommandOptions:: + g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "step-in-avoids-no-debug", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "A boolean value that sets whether stepping into functions will step over functions with no debug information."}, {LLDB_OPT_SET_1, false, "step-out-avoids-no-debug", 'A', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "A boolean value, if true stepping out of functions will continue to step out till it hits a function with debug information."}, {LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 1, eArgTypeCount, "How many times to perform the stepping operation - currently only supported for step-inst and next-inst."}, @@ -797,1167 +710,1045 @@ CommandObjectThreadStepWithTypeAndScope::CommandOptions::g_option_table[] = {LLDB_OPT_SET_1, false, "step-in-target", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFunctionName, "The name of the directly called function step in should stop at when stepping into."}, {LLDB_OPT_SET_2, false, "python-class", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonClass, "The name of the class that will manage this step - only supported for Scripted Step."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectThreadContinue //------------------------------------------------------------------------- -class CommandObjectThreadContinue : public CommandObjectParsed -{ +class CommandObjectThreadContinue : public CommandObjectParsed { public: - CommandObjectThreadContinue(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "thread continue", "Continue execution of the current target process. One " - "or more threads may be specified, by default all " - "threads continue.", - nullptr, eCommandRequiresThread | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) - { - CommandArgumentEntry arg; - CommandArgumentData thread_idx_arg; - - // Define the first (and only) variant of this arg. - thread_idx_arg.arg_type = eArgTypeThreadIndex; - thread_idx_arg.arg_repetition = eArgRepeatPlus; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (thread_idx_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + CommandObjectThreadContinue(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "thread continue", + "Continue execution of the current target process. One " + "or more threads may be specified, by default all " + "threads continue.", + nullptr, + eCommandRequiresThread | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) { + CommandArgumentEntry arg; + CommandArgumentData thread_idx_arg; + + // Define the first (and only) variant of this arg. + thread_idx_arg.arg_type = eArgTypeThreadIndex; + thread_idx_arg.arg_repetition = eArgRepeatPlus; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(thread_idx_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectThreadContinue() override = default; + + bool DoExecute(Args &command, CommandReturnObject &result) override { + bool synchronous_execution = m_interpreter.GetSynchronous(); + + if (!m_interpreter.GetDebugger().GetSelectedTarget()) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectThreadContinue() override = default; - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - bool synchronous_execution = m_interpreter.GetSynchronous (); - - if (!m_interpreter.GetDebugger().GetSelectedTarget()) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - Process *process = m_exe_ctx.GetProcessPtr(); - if (process == nullptr) - { - result.AppendError ("no process exists. Cannot continue"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - StateType state = process->GetState(); - if ((state == eStateCrashed) || (state == eStateStopped) || (state == eStateSuspended)) - { - const size_t argc = command.GetArgumentCount(); - if (argc > 0) - { - // These two lines appear at the beginning of both blocks in - // this if..else, but that is because we need to release the - // lock before calling process->Resume below. - std::lock_guard guard(process->GetThreadList().GetMutex()); - const uint32_t num_threads = process->GetThreadList().GetSize(); - std::vector resume_threads; - for (uint32_t i = 0; i < argc; ++i) - { - bool success; - const int base = 0; - uint32_t thread_idx = StringConvert::ToUInt32 (command.GetArgumentAtIndex(i), LLDB_INVALID_INDEX32, base, &success); - if (success) - { - Thread *thread = process->GetThreadList().FindThreadByIndexID(thread_idx).get(); - - if (thread) - { - resume_threads.push_back(thread); - } - else - { - result.AppendErrorWithFormat("invalid thread index %u.\n", thread_idx); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - result.AppendErrorWithFormat ("invalid thread index argument: \"%s\".\n", command.GetArgumentAtIndex(i)); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - - if (resume_threads.empty()) - { - result.AppendError ("no valid thread indexes were specified"); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - { - if (resume_threads.size() == 1) - result.AppendMessageWithFormat ("Resuming thread: "); - else - result.AppendMessageWithFormat ("Resuming threads: "); - - for (uint32_t idx = 0; idx < num_threads; ++idx) - { - Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get(); - std::vector::iterator this_thread_pos = find(resume_threads.begin(), resume_threads.end(), thread); - - if (this_thread_pos != resume_threads.end()) - { - resume_threads.erase(this_thread_pos); - if (!resume_threads.empty()) - result.AppendMessageWithFormat ("%u, ", thread->GetIndexID()); - else - result.AppendMessageWithFormat ("%u ", thread->GetIndexID()); - - const bool override_suspend = true; - thread->SetResumeState (eStateRunning, override_suspend); - } - else - { - thread->SetResumeState (eStateSuspended); - } - } - result.AppendMessageWithFormat ("in process %" PRIu64 "\n", process->GetID()); - } - } - else - { - // These two lines appear at the beginning of both blocks in - // this if..else, but that is because we need to release the - // lock before calling process->Resume below. - std::lock_guard guard(process->GetThreadList().GetMutex()); - const uint32_t num_threads = process->GetThreadList().GetSize(); - Thread *current_thread = GetDefaultThread(); - if (current_thread == nullptr) - { - result.AppendError ("the process doesn't have a current thread"); - result.SetStatus (eReturnStatusFailed); - return false; - } - // Set the actions that the threads should each take when resuming - for (uint32_t idx = 0; idx < num_threads; ++idx) - { - Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get(); - if (thread == current_thread) - { - result.AppendMessageWithFormat ("Resuming thread 0x%4.4" PRIx64 " in process %" PRIu64 "\n", thread->GetID(), process->GetID()); - const bool override_suspend = true; - thread->SetResumeState (eStateRunning, override_suspend); - } - else - { - thread->SetResumeState (eStateSuspended); - } - } - } + Process *process = m_exe_ctx.GetProcessPtr(); + if (process == nullptr) { + result.AppendError("no process exists. Cannot continue"); + result.SetStatus(eReturnStatusFailed); + return false; + } - StreamString stream; - Error error; - if (synchronous_execution) - error = process->ResumeSynchronous (&stream); - else - error = process->Resume (); - - // We should not be holding the thread list lock when we do this. - if (error.Success()) - { - result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID()); - if (synchronous_execution) - { - // If any state changed events had anything to say, add that to the result - if (stream.GetData()) - result.AppendMessage(stream.GetData()); - - result.SetDidChangeProcessState (true); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.SetStatus (eReturnStatusSuccessContinuingNoResult); - } + StateType state = process->GetState(); + if ((state == eStateCrashed) || (state == eStateStopped) || + (state == eStateSuspended)) { + const size_t argc = command.GetArgumentCount(); + if (argc > 0) { + // These two lines appear at the beginning of both blocks in + // this if..else, but that is because we need to release the + // lock before calling process->Resume below. + std::lock_guard guard( + process->GetThreadList().GetMutex()); + const uint32_t num_threads = process->GetThreadList().GetSize(); + std::vector resume_threads; + for (uint32_t i = 0; i < argc; ++i) { + bool success; + const int base = 0; + uint32_t thread_idx = + StringConvert::ToUInt32(command.GetArgumentAtIndex(i), + LLDB_INVALID_INDEX32, base, &success); + if (success) { + Thread *thread = + process->GetThreadList().FindThreadByIndexID(thread_idx).get(); + + if (thread) { + resume_threads.push_back(thread); + } else { + result.AppendErrorWithFormat("invalid thread index %u.\n", + thread_idx); + result.SetStatus(eReturnStatusFailed); + return false; } - else - { - result.AppendErrorWithFormat("Failed to resume process: %s\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); + } else { + result.AppendErrorWithFormat( + "invalid thread index argument: \"%s\".\n", + command.GetArgumentAtIndex(i)); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + if (resume_threads.empty()) { + result.AppendError("no valid thread indexes were specified"); + result.SetStatus(eReturnStatusFailed); + return false; + } else { + if (resume_threads.size() == 1) + result.AppendMessageWithFormat("Resuming thread: "); + else + result.AppendMessageWithFormat("Resuming threads: "); + + for (uint32_t idx = 0; idx < num_threads; ++idx) { + Thread *thread = + process->GetThreadList().GetThreadAtIndex(idx).get(); + std::vector::iterator this_thread_pos = + find(resume_threads.begin(), resume_threads.end(), thread); + + if (this_thread_pos != resume_threads.end()) { + resume_threads.erase(this_thread_pos); + if (!resume_threads.empty()) + result.AppendMessageWithFormat("%u, ", thread->GetIndexID()); + else + result.AppendMessageWithFormat("%u ", thread->GetIndexID()); + + const bool override_suspend = true; + thread->SetResumeState(eStateRunning, override_suspend); + } else { + thread->SetResumeState(eStateSuspended); } - } - else - { - result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n", - StateAsCString(state)); - result.SetStatus (eReturnStatusFailed); - } - - return result.Succeeded(); + } + result.AppendMessageWithFormat("in process %" PRIu64 "\n", + process->GetID()); + } + } else { + // These two lines appear at the beginning of both blocks in + // this if..else, but that is because we need to release the + // lock before calling process->Resume below. + std::lock_guard guard( + process->GetThreadList().GetMutex()); + const uint32_t num_threads = process->GetThreadList().GetSize(); + Thread *current_thread = GetDefaultThread(); + if (current_thread == nullptr) { + result.AppendError("the process doesn't have a current thread"); + result.SetStatus(eReturnStatusFailed); + return false; + } + // Set the actions that the threads should each take when resuming + for (uint32_t idx = 0; idx < num_threads; ++idx) { + Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get(); + if (thread == current_thread) { + result.AppendMessageWithFormat("Resuming thread 0x%4.4" PRIx64 + " in process %" PRIu64 "\n", + thread->GetID(), process->GetID()); + const bool override_suspend = true; + thread->SetResumeState(eStateRunning, override_suspend); + } else { + thread->SetResumeState(eStateSuspended); + } + } + } + + StreamString stream; + Error error; + if (synchronous_execution) + error = process->ResumeSynchronous(&stream); + else + error = process->Resume(); + + // We should not be holding the thread list lock when we do this. + if (error.Success()) { + result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n", + process->GetID()); + if (synchronous_execution) { + // If any state changed events had anything to say, add that to the + // result + if (stream.GetData()) + result.AppendMessage(stream.GetData()); + + result.SetDidChangeProcessState(true); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.SetStatus(eReturnStatusSuccessContinuingNoResult); + } + } else { + result.AppendErrorWithFormat("Failed to resume process: %s\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + } else { + result.AppendErrorWithFormat( + "Process cannot be continued from its current state (%s).\n", + StateAsCString(state)); + result.SetStatus(eReturnStatusFailed); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectThreadUntil //------------------------------------------------------------------------- -class CommandObjectThreadUntil : public CommandObjectParsed -{ +class CommandObjectThreadUntil : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - uint32_t m_thread_idx; - uint32_t m_frame_idx; - - CommandOptions() : - Options(), - m_thread_idx(LLDB_INVALID_THREAD_ID), - m_frame_idx(LLDB_INVALID_FRAME_ID) - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - { - lldb::addr_t tmp_addr = - Args::StringToAddress(execution_context, option_arg, - LLDB_INVALID_ADDRESS, &error); - if (error.Success()) - m_until_addrs.push_back(tmp_addr); - } - break; - case 't': - m_thread_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_INDEX32); - if (m_thread_idx == LLDB_INVALID_INDEX32) - { - error.SetErrorStringWithFormat ("invalid thread index '%s'", option_arg); - } - break; - case 'f': - m_frame_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_FRAME_ID); - if (m_frame_idx == LLDB_INVALID_FRAME_ID) - { - error.SetErrorStringWithFormat ("invalid frame index '%s'", option_arg); - } - break; - case 'm': - { - OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values; - lldb::RunMode run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error); - - if (error.Success()) - { - if (run_mode == eAllThreads) - m_stop_others = false; - else - m_stop_others = true; - } - } - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + class CommandOptions : public Options { + public: + uint32_t m_thread_idx; + uint32_t m_frame_idx; + + CommandOptions() + : Options(), m_thread_idx(LLDB_INVALID_THREAD_ID), + m_frame_idx(LLDB_INVALID_FRAME_ID) { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_thread_idx = LLDB_INVALID_THREAD_ID; - m_frame_idx = 0; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': { + lldb::addr_t tmp_addr = Args::StringToAddress( + execution_context, option_arg, LLDB_INVALID_ADDRESS, &error); + if (error.Success()) + m_until_addrs.push_back(tmp_addr); + } break; + case 't': + m_thread_idx = + StringConvert::ToUInt32(option_arg, LLDB_INVALID_INDEX32); + if (m_thread_idx == LLDB_INVALID_INDEX32) { + error.SetErrorStringWithFormat("invalid thread index '%s'", + option_arg); + } + break; + case 'f': + m_frame_idx = + StringConvert::ToUInt32(option_arg, LLDB_INVALID_FRAME_ID); + if (m_frame_idx == LLDB_INVALID_FRAME_ID) { + error.SetErrorStringWithFormat("invalid frame index '%s'", + option_arg); + } + break; + case 'm': { + OptionEnumValueElement *enum_values = + g_option_table[option_idx].enum_values; + lldb::RunMode run_mode = (lldb::RunMode)Args::StringToOptionEnum( + option_arg, enum_values, eOnlyDuringStepping, error); + + if (error.Success()) { + if (run_mode == eAllThreads) m_stop_others = false; - m_until_addrs.clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - uint32_t m_step_thread_idx; - bool m_stop_others; - std::vector m_until_addrs; - - // Options table: Required for subclasses of Options. + else + m_stop_others = true; + } + } break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - static OptionDefinition g_option_table[]; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_thread_idx = LLDB_INVALID_THREAD_ID; + m_frame_idx = 0; + m_stop_others = false; + m_until_addrs.clear(); + } - // Instance variables to hold the values for command options. - }; + const OptionDefinition *GetDefinitions() override { return g_option_table; } - CommandObjectThreadUntil(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "thread until", "Continue until a line number or address is reached by the " - "current or specified thread. Stops when returning from " - "the current function as a safety measure.", - nullptr, eCommandRequiresThread | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData line_num_arg; - - // Define the first (and only) variant of this arg. - line_num_arg.arg_type = eArgTypeLineNum; - line_num_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (line_num_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + uint32_t m_step_thread_idx; + bool m_stop_others; + std::vector m_until_addrs; - ~CommandObjectThreadUntil() override = default; + // Options table: Required for subclasses of Options. - Options * - GetOptions () override - { - return &m_options; - } + static OptionDefinition g_option_table[]; -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - bool synchronous_execution = m_interpreter.GetSynchronous (); + // Instance variables to hold the values for command options. + }; - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("invalid target, create a debug target using the 'target create' command"); - result.SetStatus (eReturnStatusFailed); - return false; - } + CommandObjectThreadUntil(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "thread until", + "Continue until a line number or address is reached by the " + "current or specified thread. Stops when returning from " + "the current function as a safety measure.", + nullptr, + eCommandRequiresThread | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData line_num_arg; - Process *process = m_exe_ctx.GetProcessPtr(); - if (process == nullptr) - { - result.AppendError ("need a valid process to step"); - result.SetStatus (eReturnStatusFailed); - } - else - { - Thread *thread = nullptr; - std::vector line_numbers; - - if (command.GetArgumentCount() >= 1) - { - size_t num_args = command.GetArgumentCount(); - for (size_t i = 0; i < num_args; i++) - { - uint32_t line_number; - line_number = StringConvert::ToUInt32 (command.GetArgumentAtIndex(0), UINT32_MAX); - if (line_number == UINT32_MAX) - { - result.AppendErrorWithFormat ("invalid line number: '%s'.\n", command.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - return false; - } - else - line_numbers.push_back(line_number); - } - } - else if (m_options.m_until_addrs.empty()) - { - result.AppendErrorWithFormat ("No line number or address provided:\n%s", GetSyntax()); - result.SetStatus (eReturnStatusFailed); - return false; - } + // Define the first (and only) variant of this arg. + line_num_arg.arg_type = eArgTypeLineNum; + line_num_arg.arg_repetition = eArgRepeatPlain; - if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) - { - thread = GetDefaultThread(); - } - else - { - thread = process->GetThreadList().FindThreadByIndexID(m_options.m_thread_idx).get(); - } + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(line_num_arg); - if (thread == nullptr) - { - const uint32_t num_threads = process->GetThreadList().GetSize(); - result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n", - m_options.m_thread_idx, - num_threads); - result.SetStatus (eReturnStatusFailed); - return false; - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - const bool abort_other_plans = false; + ~CommandObjectThreadUntil() override = default; - StackFrame *frame = thread->GetStackFrameAtIndex(m_options.m_frame_idx).get(); - if (frame == nullptr) - { - result.AppendErrorWithFormat ("Frame index %u is out of range for thread %u.\n", - m_options.m_frame_idx, - m_options.m_thread_idx); - result.SetStatus (eReturnStatusFailed); - return false; - } + Options *GetOptions() override { return &m_options; } - ThreadPlanSP new_plan_sp; - - if (frame->HasDebugInformation ()) - { - // Finally we got here... Translate the given line number to a bunch of addresses: - SymbolContext sc(frame->GetSymbolContext (eSymbolContextCompUnit)); - LineTable *line_table = nullptr; - if (sc.comp_unit) - line_table = sc.comp_unit->GetLineTable(); - - if (line_table == nullptr) - { - result.AppendErrorWithFormat ("Failed to resolve the line table for frame %u of thread index %u.\n", - m_options.m_frame_idx, m_options.m_thread_idx); - result.SetStatus (eReturnStatusFailed); - return false; - } - - LineEntry function_start; - uint32_t index_ptr = 0, end_ptr; - std::vector address_list; - - // Find the beginning & end index of the - AddressRange fun_addr_range = sc.function->GetAddressRange(); - Address fun_start_addr = fun_addr_range.GetBaseAddress(); - line_table->FindLineEntryByAddress (fun_start_addr, function_start, &index_ptr); - - Address fun_end_addr(fun_start_addr.GetSection(), - fun_start_addr.GetOffset() + fun_addr_range.GetByteSize()); - - bool all_in_function = true; - - line_table->FindLineEntryByAddress (fun_end_addr, function_start, &end_ptr); - - for (uint32_t line_number : line_numbers) - { - uint32_t start_idx_ptr = index_ptr; - while (start_idx_ptr <= end_ptr) - { - LineEntry line_entry; - const bool exact = false; - start_idx_ptr = sc.comp_unit->FindLineEntry(start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry); - if (start_idx_ptr == UINT32_MAX) - break; - - addr_t address = line_entry.range.GetBaseAddress().GetLoadAddress(target); - if (address != LLDB_INVALID_ADDRESS) - { - if (fun_addr_range.ContainsLoadAddress (address, target)) - address_list.push_back (address); - else - all_in_function = false; - } - start_idx_ptr++; - } - } - - for (lldb::addr_t address : m_options.m_until_addrs) - { - if (fun_addr_range.ContainsLoadAddress (address, target)) - address_list.push_back (address); - else - all_in_function = false; - } - - if (address_list.empty()) - { - if (all_in_function) - result.AppendErrorWithFormat ("No line entries matching until target.\n"); - else - result.AppendErrorWithFormat ("Until target outside of the current function.\n"); - - result.SetStatus (eReturnStatusFailed); - return false; - } - - new_plan_sp = thread->QueueThreadPlanForStepUntil (abort_other_plans, - &address_list.front(), - address_list.size(), - m_options.m_stop_others, - m_options.m_frame_idx); - // User level plans should be master plans so they can be interrupted (e.g. by hitting a breakpoint) - // and other plans executed by the user (stepping around the breakpoint) and then a "continue" - // will resume the original plan. - new_plan_sp->SetIsMasterPlan (true); - new_plan_sp->SetOkayToDiscard(false); - } - else - { - result.AppendErrorWithFormat ("Frame index %u of thread %u has no debug information.\n", - m_options.m_frame_idx, - m_options.m_thread_idx); - result.SetStatus (eReturnStatusFailed); - return false; - } +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + bool synchronous_execution = m_interpreter.GetSynchronous(); + + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("invalid target, create a debug target using the " + "'target create' command"); + result.SetStatus(eReturnStatusFailed); + return false; + } - process->GetThreadList().SetSelectedThreadByID (m_options.m_thread_idx); - - StreamString stream; - Error error; - if (synchronous_execution) - error = process->ResumeSynchronous (&stream); - else - error = process->Resume (); - - if (error.Success()) - { - result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID()); - if (synchronous_execution) - { - // If any state changed events had anything to say, add that to the result - if (stream.GetData()) - result.AppendMessage(stream.GetData()); - - result.SetDidChangeProcessState (true); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - result.SetStatus (eReturnStatusSuccessContinuingNoResult); - } - } - else - { - result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString()); - result.SetStatus (eReturnStatusFailed); + Process *process = m_exe_ctx.GetProcessPtr(); + if (process == nullptr) { + result.AppendError("need a valid process to step"); + result.SetStatus(eReturnStatusFailed); + } else { + Thread *thread = nullptr; + std::vector line_numbers; + + if (command.GetArgumentCount() >= 1) { + size_t num_args = command.GetArgumentCount(); + for (size_t i = 0; i < num_args; i++) { + uint32_t line_number; + line_number = StringConvert::ToUInt32(command.GetArgumentAtIndex(0), + UINT32_MAX); + if (line_number == UINT32_MAX) { + result.AppendErrorWithFormat("invalid line number: '%s'.\n", + command.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + return false; + } else + line_numbers.push_back(line_number); + } + } else if (m_options.m_until_addrs.empty()) { + result.AppendErrorWithFormat("No line number or address provided:\n%s", + GetSyntax()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID) { + thread = GetDefaultThread(); + } else { + thread = process->GetThreadList() + .FindThreadByIndexID(m_options.m_thread_idx) + .get(); + } + + if (thread == nullptr) { + const uint32_t num_threads = process->GetThreadList().GetSize(); + result.AppendErrorWithFormat( + "Thread index %u is out of range (valid values are 0 - %u).\n", + m_options.m_thread_idx, num_threads); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const bool abort_other_plans = false; + + StackFrame *frame = + thread->GetStackFrameAtIndex(m_options.m_frame_idx).get(); + if (frame == nullptr) { + result.AppendErrorWithFormat( + "Frame index %u is out of range for thread %u.\n", + m_options.m_frame_idx, m_options.m_thread_idx); + result.SetStatus(eReturnStatusFailed); + return false; + } + + ThreadPlanSP new_plan_sp; + + if (frame->HasDebugInformation()) { + // Finally we got here... Translate the given line number to a bunch of + // addresses: + SymbolContext sc(frame->GetSymbolContext(eSymbolContextCompUnit)); + LineTable *line_table = nullptr; + if (sc.comp_unit) + line_table = sc.comp_unit->GetLineTable(); + + if (line_table == nullptr) { + result.AppendErrorWithFormat("Failed to resolve the line table for " + "frame %u of thread index %u.\n", + m_options.m_frame_idx, + m_options.m_thread_idx); + result.SetStatus(eReturnStatusFailed); + return false; + } + + LineEntry function_start; + uint32_t index_ptr = 0, end_ptr; + std::vector address_list; + + // Find the beginning & end index of the + AddressRange fun_addr_range = sc.function->GetAddressRange(); + Address fun_start_addr = fun_addr_range.GetBaseAddress(); + line_table->FindLineEntryByAddress(fun_start_addr, function_start, + &index_ptr); + + Address fun_end_addr(fun_start_addr.GetSection(), + fun_start_addr.GetOffset() + + fun_addr_range.GetByteSize()); + + bool all_in_function = true; + + line_table->FindLineEntryByAddress(fun_end_addr, function_start, + &end_ptr); + + for (uint32_t line_number : line_numbers) { + uint32_t start_idx_ptr = index_ptr; + while (start_idx_ptr <= end_ptr) { + LineEntry line_entry; + const bool exact = false; + start_idx_ptr = sc.comp_unit->FindLineEntry( + start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry); + if (start_idx_ptr == UINT32_MAX) + break; + + addr_t address = + line_entry.range.GetBaseAddress().GetLoadAddress(target); + if (address != LLDB_INVALID_ADDRESS) { + if (fun_addr_range.ContainsLoadAddress(address, target)) + address_list.push_back(address); + else + all_in_function = false; } - - } - return result.Succeeded(); + start_idx_ptr++; + } + } + + for (lldb::addr_t address : m_options.m_until_addrs) { + if (fun_addr_range.ContainsLoadAddress(address, target)) + address_list.push_back(address); + else + all_in_function = false; + } + + if (address_list.empty()) { + if (all_in_function) + result.AppendErrorWithFormat( + "No line entries matching until target.\n"); + else + result.AppendErrorWithFormat( + "Until target outside of the current function.\n"); + + result.SetStatus(eReturnStatusFailed); + return false; + } + + new_plan_sp = thread->QueueThreadPlanForStepUntil( + abort_other_plans, &address_list.front(), address_list.size(), + m_options.m_stop_others, m_options.m_frame_idx); + // User level plans should be master plans so they can be interrupted + // (e.g. by hitting a breakpoint) + // and other plans executed by the user (stepping around the breakpoint) + // and then a "continue" + // will resume the original plan. + new_plan_sp->SetIsMasterPlan(true); + new_plan_sp->SetOkayToDiscard(false); + } else { + result.AppendErrorWithFormat( + "Frame index %u of thread %u has no debug information.\n", + m_options.m_frame_idx, m_options.m_thread_idx); + result.SetStatus(eReturnStatusFailed); + return false; + } + + process->GetThreadList().SetSelectedThreadByID(m_options.m_thread_idx); + + StreamString stream; + Error error; + if (synchronous_execution) + error = process->ResumeSynchronous(&stream); + else + error = process->Resume(); + + if (error.Success()) { + result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n", + process->GetID()); + if (synchronous_execution) { + // If any state changed events had anything to say, add that to the + // result + if (stream.GetData()) + result.AppendMessage(stream.GetData()); + + result.SetDidChangeProcessState(true); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.SetStatus(eReturnStatusSuccessContinuingNoResult); + } + } else { + result.AppendErrorWithFormat("Failed to resume process: %s.\n", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } } + return result.Succeeded(); + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectThreadUntil::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectThreadUntil::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "frame", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame index for until operation - defaults to 0"}, {LLDB_OPT_SET_1, false, "thread", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeThreadIndex, "Thread index for the thread for until operation"}, {LLDB_OPT_SET_1, false, "run-mode",'m', OptionParser::eRequiredArgument, nullptr, g_duo_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping this one"}, {LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Run until we reach the specified address, or leave the function - can be specified multiple times."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectThreadSelect //------------------------------------------------------------------------- -class CommandObjectThreadSelect : public CommandObjectParsed -{ +class CommandObjectThreadSelect : public CommandObjectParsed { public: - CommandObjectThreadSelect(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "thread select", "Change the currently selected thread.", nullptr, - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused) - { - CommandArgumentEntry arg; - CommandArgumentData thread_idx_arg; - - // Define the first (and only) variant of this arg. - thread_idx_arg.arg_type = eArgTypeThreadIndex; - thread_idx_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (thread_idx_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectThreadSelect(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "thread select", + "Change the currently selected thread.", nullptr, + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused) { + CommandArgumentEntry arg; + CommandArgumentData thread_idx_arg; - ~CommandObjectThreadSelect() override = default; + // Define the first (and only) variant of this arg. + thread_idx_arg.arg_type = eArgTypeThreadIndex; + thread_idx_arg.arg_repetition = eArgRepeatPlain; -protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Process *process = m_exe_ctx.GetProcessPtr(); - if (process == nullptr) - { - result.AppendError ("no process"); - result.SetStatus (eReturnStatusFailed); - return false; - } - else if (command.GetArgumentCount() != 1) - { - result.AppendErrorWithFormat("'%s' takes exactly one thread index argument:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); - result.SetStatus (eReturnStatusFailed); - return false; - } + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(thread_idx_arg); - uint32_t index_id = StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - Thread *new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get(); - if (new_thread == nullptr) - { - result.AppendErrorWithFormat ("invalid thread #%s.\n", command.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - return false; - } + ~CommandObjectThreadSelect() override = default; - process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - - return result.Succeeded(); +protected: + bool DoExecute(Args &command, CommandReturnObject &result) override { + Process *process = m_exe_ctx.GetProcessPtr(); + if (process == nullptr) { + result.AppendError("no process"); + result.SetStatus(eReturnStatusFailed); + return false; + } else if (command.GetArgumentCount() != 1) { + result.AppendErrorWithFormat( + "'%s' takes exactly one thread index argument:\nUsage: %s\n", + m_cmd_name.c_str(), m_cmd_syntax.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } + + uint32_t index_id = + StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0); + + Thread *new_thread = + process->GetThreadList().FindThreadByIndexID(index_id).get(); + if (new_thread == nullptr) { + result.AppendErrorWithFormat("invalid thread #%s.\n", + command.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + return false; + } + + process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectThreadList //------------------------------------------------------------------------- -class CommandObjectThreadList : public CommandObjectParsed -{ +class CommandObjectThreadList : public CommandObjectParsed { public: - CommandObjectThreadList(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "thread list", - "Show a summary of each thread in the current target process.", "thread list", - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused) - { - } + CommandObjectThreadList(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "thread list", + "Show a summary of each thread in the current target process.", + "thread list", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} - ~CommandObjectThreadList() override = default; + ~CommandObjectThreadList() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Stream &strm = result.GetOutputStream(); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - Process *process = m_exe_ctx.GetProcessPtr(); - const bool only_threads_with_stop_reason = false; - const uint32_t start_frame = 0; - const uint32_t num_frames = 0; - const uint32_t num_frames_with_source = 0; - process->GetStatus(strm); - process->GetThreadStatus (strm, - only_threads_with_stop_reason, - start_frame, - num_frames, - num_frames_with_source); - return result.Succeeded(); - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Stream &strm = result.GetOutputStream(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + Process *process = m_exe_ctx.GetProcessPtr(); + const bool only_threads_with_stop_reason = false; + const uint32_t start_frame = 0; + const uint32_t num_frames = 0; + const uint32_t num_frames_with_source = 0; + process->GetStatus(strm); + process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame, + num_frames, num_frames_with_source); + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectThreadInfo //------------------------------------------------------------------------- -class CommandObjectThreadInfo : public CommandObjectIterateOverThreads -{ +class CommandObjectThreadInfo : public CommandObjectIterateOverThreads { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_json_thread = false; - m_json_stopinfo = false; - } + ~CommandOptions() override = default; - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - const int short_option = m_getopt_table[option_idx].val; - Error error; - - switch (short_option) - { - case 'j': - m_json_thread = true; - break; - - case 's': - m_json_stopinfo = true; - break; - - default: - return Error("invalid short option character '%c'", short_option); - } - return error; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_json_thread = false; + m_json_stopinfo = false; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + const int short_option = m_getopt_table[option_idx].val; + Error error; - bool m_json_thread; - bool m_json_stopinfo; + switch (short_option) { + case 'j': + m_json_thread = true; + break; - static OptionDefinition g_option_table[]; - }; + case 's': + m_json_stopinfo = true; + break; - CommandObjectThreadInfo(CommandInterpreter &interpreter) - : CommandObjectIterateOverThreads( - interpreter, "thread info", - "Show an extended summary of one or more threads. Defaults to the current thread.", "thread info", - eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused), - m_options() - { - m_add_return = false; + default: + return Error("invalid short option character '%c'", short_option); + } + return error; } - ~CommandObjectThreadInfo() override = default; - - Options * - GetOptions () override - { - return &m_options; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + bool m_json_thread; + bool m_json_stopinfo; + + static OptionDefinition g_option_table[]; + }; + + CommandObjectThreadInfo(CommandInterpreter &interpreter) + : CommandObjectIterateOverThreads( + interpreter, "thread info", "Show an extended summary of one or " + "more threads. Defaults to the " + "current thread.", + "thread info", + eCommandRequiresProcess | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() { + m_add_return = false; + } + + ~CommandObjectThreadInfo() override = default; + + Options *GetOptions() override { return &m_options; } + + bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override { + ThreadSP thread_sp = + m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); + if (!thread_sp) { + result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n", + tid); + result.SetStatus(eReturnStatusFailed); + return false; } - bool - HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override - { - ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); - if (!thread_sp) - { - result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid); - result.SetStatus (eReturnStatusFailed); - return false; - } - - Thread *thread = thread_sp.get(); + Thread *thread = thread_sp.get(); - Stream &strm = result.GetOutputStream(); - if (!thread->GetDescription (strm, eDescriptionLevelFull, m_options.m_json_thread, m_options.m_json_stopinfo)) - { - result.AppendErrorWithFormat ("error displaying info for thread: \"%d\"\n", thread->GetIndexID()); - result.SetStatus (eReturnStatusFailed); - return false; - } - return true; + Stream &strm = result.GetOutputStream(); + if (!thread->GetDescription(strm, eDescriptionLevelFull, + m_options.m_json_thread, + m_options.m_json_stopinfo)) { + result.AppendErrorWithFormat("error displaying info for thread: \"%d\"\n", + thread->GetIndexID()); + result.SetStatus(eReturnStatusFailed); + return false; } + return true; + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectThreadInfo::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectThreadInfo::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "json", 'j', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the thread info in JSON format."}, {LLDB_OPT_SET_ALL, false, "stop-info", 's', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the extended stop info in JSON format."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectThreadReturn //------------------------------------------------------------------------- -class CommandObjectThreadReturn : public CommandObjectRaw -{ +class CommandObjectThreadReturn : public CommandObjectRaw { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_from_expression(false) - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_from_expression(false) { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'x': - { - bool success; - bool tmp_value = Args::StringToBoolean (option_arg, false, &success); - if (success) - m_from_expression = tmp_value; - else - { - error.SetErrorStringWithFormat ("invalid boolean value '%s' for 'x' option", option_arg); - } - } - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + ~CommandOptions() override = default; - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_from_expression = false; - } + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + switch (short_option) { + case 'x': { + bool success; + bool tmp_value = Args::StringToBoolean(option_arg, false, &success); + if (success) + m_from_expression = tmp_value; + else { + error.SetErrorStringWithFormat( + "invalid boolean value '%s' for 'x' option", option_arg); + } + } break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - bool m_from_expression; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_from_expression = false; + } - // Options table: Required for subclasses of Options. + const OptionDefinition *GetDefinitions() override { return g_option_table; } - static OptionDefinition g_option_table[]; + bool m_from_expression; - // Instance variables to hold the values for command options. - }; + // Options table: Required for subclasses of Options. - CommandObjectThreadReturn(CommandInterpreter &interpreter) - : CommandObjectRaw(interpreter, "thread return", - "Prematurely return from a stack frame, short-circuiting execution of newer frames " - "and optionally yielding a specified value. Defaults to the exiting the current stack " - "frame.", - "thread return", eCommandRequiresFrame | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), - m_options() - { - CommandArgumentEntry arg; - CommandArgumentData expression_arg; + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + }; + + CommandObjectThreadReturn(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "thread return", + "Prematurely return from a stack frame, " + "short-circuiting execution of newer frames " + "and optionally yielding a specified value. Defaults " + "to the exiting the current stack " + "frame.", + "thread return", + eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_options() { + CommandArgumentEntry arg; + CommandArgumentData expression_arg; + + // Define the first (and only) variant of this arg. + expression_arg.arg_type = eArgTypeExpression; + expression_arg.arg_repetition = eArgRepeatOptional; - // Define the first (and only) variant of this arg. - expression_arg.arg_type = eArgTypeExpression; - expression_arg.arg_repetition = eArgRepeatOptional; + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(expression_arg); - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (expression_arg); + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + ~CommandObjectThreadReturn() override = default; + + Options *GetOptions() override { return &m_options; } + +protected: + bool DoExecute(const char *command, CommandReturnObject &result) override { + // I am going to handle this by hand, because I don't want you to have to + // say: + // "thread return -- -5". + if (command[0] == '-' && command[1] == 'x') { + if (command && command[2] != '\0') + result.AppendWarning("Return values ignored when returning from user " + "called expressions"); + + Thread *thread = m_exe_ctx.GetThreadPtr(); + Error error; + error = thread->UnwindInnermostExpression(); + if (!error.Success()) { + result.AppendErrorWithFormat("Unwinding expression failed - %s.", + error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } else { + bool success = + thread->SetSelectedFrameByIndexNoisily(0, result.GetOutputStream()); + if (success) { + m_exe_ctx.SetFrameSP(thread->GetSelectedFrame()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "Could not select 0th frame after unwinding expression."); + result.SetStatus(eReturnStatusFailed); + } + } + return result.Succeeded(); } - ~CommandObjectThreadReturn() override = default; + ValueObjectSP return_valobj_sp; - Options * - GetOptions() override - { - return &m_options; + StackFrameSP frame_sp = m_exe_ctx.GetFrameSP(); + uint32_t frame_idx = frame_sp->GetFrameIndex(); + + if (frame_sp->IsInlined()) { + result.AppendError("Don't know how to return from inlined frames."); + result.SetStatus(eReturnStatusFailed); + return false; } -protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - // I am going to handle this by hand, because I don't want you to have to say: - // "thread return -- -5". - if (command[0] == '-' && command[1] == 'x') - { - if (command && command[2] != '\0') - result.AppendWarning("Return values ignored when returning from user called expressions"); - - Thread *thread = m_exe_ctx.GetThreadPtr(); - Error error; - error = thread->UnwindInnermostExpression(); - if (!error.Success()) - { - result.AppendErrorWithFormat ("Unwinding expression failed - %s.", error.AsCString()); - result.SetStatus (eReturnStatusFailed); - } - else - { - bool success = thread->SetSelectedFrameByIndexNoisily (0, result.GetOutputStream()); - if (success) - { - m_exe_ctx.SetFrameSP(thread->GetSelectedFrame ()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat ("Could not select 0th frame after unwinding expression."); - result.SetStatus (eReturnStatusFailed); - } - } - return result.Succeeded(); - } - - ValueObjectSP return_valobj_sp; - - StackFrameSP frame_sp = m_exe_ctx.GetFrameSP(); - uint32_t frame_idx = frame_sp->GetFrameIndex(); - - if (frame_sp->IsInlined()) - { - result.AppendError("Don't know how to return from inlined frames."); - result.SetStatus (eReturnStatusFailed); - return false; - } - - if (command && command[0] != '\0') - { - Target *target = m_exe_ctx.GetTargetPtr(); - EvaluateExpressionOptions options; - - options.SetUnwindOnError(true); - options.SetUseDynamic(eNoDynamicValues); - - ExpressionResults exe_results = eExpressionSetupError; - exe_results = target->EvaluateExpression (command, - frame_sp.get(), - return_valobj_sp, - options); - if (exe_results != eExpressionCompleted) - { - if (return_valobj_sp) - result.AppendErrorWithFormat("Error evaluating result expression: %s", return_valobj_sp->GetError().AsCString()); - else - result.AppendErrorWithFormat("Unknown error evaluating result expression."); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - - Error error; - ThreadSP thread_sp = m_exe_ctx.GetThreadSP(); - const bool broadcast = true; - error = thread_sp->ReturnFromFrame (frame_sp, return_valobj_sp, broadcast); - if (!error.Success()) - { - result.AppendErrorWithFormat("Error returning from frame %d of thread %d: %s.", frame_idx, thread_sp->GetIndexID(), error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (command && command[0] != '\0') { + Target *target = m_exe_ctx.GetTargetPtr(); + EvaluateExpressionOptions options; + + options.SetUnwindOnError(true); + options.SetUseDynamic(eNoDynamicValues); + + ExpressionResults exe_results = eExpressionSetupError; + exe_results = target->EvaluateExpression(command, frame_sp.get(), + return_valobj_sp, options); + if (exe_results != eExpressionCompleted) { + if (return_valobj_sp) + result.AppendErrorWithFormat( + "Error evaluating result expression: %s", + return_valobj_sp->GetError().AsCString()); + else + result.AppendErrorWithFormat( + "Unknown error evaluating result expression."); + result.SetStatus(eReturnStatusFailed); + return false; + } + } - result.SetStatus (eReturnStatusSuccessFinishResult); - return true; + Error error; + ThreadSP thread_sp = m_exe_ctx.GetThreadSP(); + const bool broadcast = true; + error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast); + if (!error.Success()) { + result.AppendErrorWithFormat( + "Error returning from frame %d of thread %d: %s.", frame_idx, + thread_sp->GetIndexID(), error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } - - CommandOptions m_options; + + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + + CommandOptions m_options; }; -OptionDefinition -CommandObjectThreadReturn::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectThreadReturn::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "from-expression", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Return from the innermost expression evaluation."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectThreadJump //------------------------------------------------------------------------- -class CommandObjectThreadJump : public CommandObjectParsed -{ +class CommandObjectThreadJump : public CommandObjectParsed { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - OptionParsingStarting(nullptr); - } - - ~CommandOptions() override = default; - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_filenames.Clear(); - m_line_num = 0; - m_line_offset = 0; - m_load_addr = LLDB_INVALID_ADDRESS; - m_force = false; - } - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - bool success; - const int short_option = m_getopt_table[option_idx].val; - Error error; - - switch (short_option) - { - case 'f': - m_filenames.AppendIfUnique (FileSpec(option_arg, false)); - if (m_filenames.GetSize() > 1) - return Error("only one source file expected."); - break; - case 'l': - m_line_num = StringConvert::ToUInt32 (option_arg, 0, 0, &success); - if (!success || m_line_num == 0) - return Error("invalid line number: '%s'.", option_arg); - break; - case 'b': - m_line_offset = StringConvert::ToSInt32 (option_arg, 0, 0, &success); - if (!success) - return Error("invalid line offset: '%s'.", option_arg); - break; - case 'a': - m_load_addr = Args::StringToAddress(execution_context, - option_arg, - LLDB_INVALID_ADDRESS, - &error); - break; - case 'r': - m_force = true; - break; - default: - return Error("invalid short option character '%c'", short_option); - } - return error; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - FileSpecList m_filenames; - uint32_t m_line_num; - int32_t m_line_offset; - lldb::addr_t m_load_addr; - bool m_force; - - static OptionDefinition g_option_table[]; - }; - - CommandObjectThreadJump (CommandInterpreter &interpreter) : - CommandObjectParsed (interpreter, - "thread jump", - "Sets the program counter to a new address.", - "thread jump", - eCommandRequiresFrame | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_options() - { + class CommandOptions : public Options { + public: + CommandOptions() : Options() { OptionParsingStarting(nullptr); } + + ~CommandOptions() override = default; + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_filenames.Clear(); + m_line_num = 0; + m_line_offset = 0; + m_load_addr = LLDB_INVALID_ADDRESS; + m_force = false; } - ~CommandObjectThreadJump() override = default; - - Options * - GetOptions() override - { - return &m_options; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + bool success; + const int short_option = m_getopt_table[option_idx].val; + Error error; + + switch (short_option) { + case 'f': + m_filenames.AppendIfUnique(FileSpec(option_arg, false)); + if (m_filenames.GetSize() > 1) + return Error("only one source file expected."); + break; + case 'l': + m_line_num = StringConvert::ToUInt32(option_arg, 0, 0, &success); + if (!success || m_line_num == 0) + return Error("invalid line number: '%s'.", option_arg); + break; + case 'b': + m_line_offset = StringConvert::ToSInt32(option_arg, 0, 0, &success); + if (!success) + return Error("invalid line offset: '%s'.", option_arg); + break; + case 'a': + m_load_addr = Args::StringToAddress(execution_context, option_arg, + LLDB_INVALID_ADDRESS, &error); + break; + case 'r': + m_force = true; + break; + default: + return Error("invalid short option character '%c'", short_option); + } + return error; } -protected: - bool DoExecute (Args& args, CommandReturnObject &result) override - { - RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); - StackFrame *frame = m_exe_ctx.GetFramePtr(); - Thread *thread = m_exe_ctx.GetThreadPtr(); - Target *target = m_exe_ctx.GetTargetPtr(); - const SymbolContext &sym_ctx = frame->GetSymbolContext (eSymbolContextLineEntry); - - if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) - { - // Use this address directly. - Address dest = Address(m_options.m_load_addr); - - lldb::addr_t callAddr = dest.GetCallableLoadAddress (target); - if (callAddr == LLDB_INVALID_ADDRESS) - { - result.AppendErrorWithFormat ("Invalid destination address."); - result.SetStatus (eReturnStatusFailed); - return false; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - if (!reg_ctx->SetPC (callAddr)) - { - result.AppendErrorWithFormat ("Error changing PC value for thread %d.", thread->GetIndexID()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - else - { - // Pick either the absolute line, or work out a relative one. - int32_t line = (int32_t)m_options.m_line_num; - if (line == 0) - line = sym_ctx.line_entry.line + m_options.m_line_offset; - - // Try the current file, but override if asked. - FileSpec file = sym_ctx.line_entry.file; - if (m_options.m_filenames.GetSize() == 1) - file = m_options.m_filenames.GetFileSpecAtIndex(0); - - if (!file) - { - result.AppendErrorWithFormat ("No source file available for the current location."); - result.SetStatus (eReturnStatusFailed); - return false; - } + FileSpecList m_filenames; + uint32_t m_line_num; + int32_t m_line_offset; + lldb::addr_t m_load_addr; + bool m_force; - std::string warnings; - Error err = thread->JumpToLine (file, line, m_options.m_force, &warnings); + static OptionDefinition g_option_table[]; + }; - if (err.Fail()) - { - result.SetError (err); - return false; - } + CommandObjectThreadJump(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "thread jump", + "Sets the program counter to a new address.", "thread jump", + eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_options() {} - if (!warnings.empty()) - result.AppendWarning (warnings.c_str()); - } + ~CommandObjectThreadJump() override = default; - result.SetStatus (eReturnStatusSuccessFinishResult); - return true; + Options *GetOptions() override { return &m_options; } + +protected: + bool DoExecute(Args &args, CommandReturnObject &result) override { + RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); + StackFrame *frame = m_exe_ctx.GetFramePtr(); + Thread *thread = m_exe_ctx.GetThreadPtr(); + Target *target = m_exe_ctx.GetTargetPtr(); + const SymbolContext &sym_ctx = + frame->GetSymbolContext(eSymbolContextLineEntry); + + if (m_options.m_load_addr != LLDB_INVALID_ADDRESS) { + // Use this address directly. + Address dest = Address(m_options.m_load_addr); + + lldb::addr_t callAddr = dest.GetCallableLoadAddress(target); + if (callAddr == LLDB_INVALID_ADDRESS) { + result.AppendErrorWithFormat("Invalid destination address."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (!reg_ctx->SetPC(callAddr)) { + result.AppendErrorWithFormat("Error changing PC value for thread %d.", + thread->GetIndexID()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + // Pick either the absolute line, or work out a relative one. + int32_t line = (int32_t)m_options.m_line_num; + if (line == 0) + line = sym_ctx.line_entry.line + m_options.m_line_offset; + + // Try the current file, but override if asked. + FileSpec file = sym_ctx.line_entry.file; + if (m_options.m_filenames.GetSize() == 1) + file = m_options.m_filenames.GetFileSpecAtIndex(0); + + if (!file) { + result.AppendErrorWithFormat( + "No source file available for the current location."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + std::string warnings; + Error err = thread->JumpToLine(file, line, m_options.m_force, &warnings); + + if (err.Fail()) { + result.SetError(err); + return false; + } + + if (!warnings.empty()) + result.AppendWarning(warnings.c_str()); } - CommandOptions m_options; + result.SetStatus(eReturnStatusSuccessFinishResult); + return true; + } + + CommandOptions m_options; }; -OptionDefinition -CommandObjectThreadJump::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectThreadJump::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename, "Specifies the source file to jump to."}, {LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum, "Specifies the line number to jump to."}, {LLDB_OPT_SET_2, true, "by", 'b', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "Jumps by a relative line offset from the current line."}, {LLDB_OPT_SET_3, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression, "Jumps to a specific address."}, {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allows the PC to leave the current function."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -1968,267 +1759,265 @@ CommandObjectThreadJump::CommandOptions::g_option_table[] = // CommandObjectThreadPlanList //------------------------------------------------------------------------- -class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads -{ +class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads { public: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - // Keep default values of all options in one place: OptionParsingStarting () - OptionParsingStarting(nullptr); - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() { + // Keep default values of all options in one place: OptionParsingStarting + // () + OptionParsingStarting(nullptr); + } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'i': - m_internal = true; - break; - case 'v': - m_verbose = true; - break; - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - return error; - } + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'i': + m_internal = true; + break; + case 'v': + m_verbose = true; + break; + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + return error; + } - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_verbose = false; - m_internal = false; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_verbose = false; + m_internal = false; + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. - bool m_verbose; - bool m_internal; - }; + // Instance variables to hold the values for command options. + bool m_verbose; + bool m_internal; + }; - CommandObjectThreadPlanList(CommandInterpreter &interpreter) - : CommandObjectIterateOverThreads( - interpreter, "thread plan list", - "Show thread plans for one or more threads. If no threads are specified, show the " - "current thread. Use the thread-index \"all\" to see all threads.", - nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), - m_options() - { - } + CommandObjectThreadPlanList(CommandInterpreter &interpreter) + : CommandObjectIterateOverThreads( + interpreter, "thread plan list", + "Show thread plans for one or more threads. If no threads are " + "specified, show the " + "current thread. Use the thread-index \"all\" to see all threads.", + nullptr, + eCommandRequiresProcess | eCommandRequiresThread | + eCommandTryTargetAPILock | eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused), + m_options() {} - ~CommandObjectThreadPlanList() override = default; + ~CommandObjectThreadPlanList() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } protected: - bool - HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override - { - ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); - if (!thread_sp) - { - result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool HandleOneThread(lldb::tid_t tid, CommandReturnObject &result) override { + ThreadSP thread_sp = + m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid); + if (!thread_sp) { + result.AppendErrorWithFormat("thread no longer exists: 0x%" PRIx64 "\n", + tid); + result.SetStatus(eReturnStatusFailed); + return false; + } - Thread *thread = thread_sp.get(); + Thread *thread = thread_sp.get(); - Stream &strm = result.GetOutputStream(); - DescriptionLevel desc_level = eDescriptionLevelFull; - if (m_options.m_verbose) - desc_level = eDescriptionLevelVerbose; + Stream &strm = result.GetOutputStream(); + DescriptionLevel desc_level = eDescriptionLevelFull; + if (m_options.m_verbose) + desc_level = eDescriptionLevelVerbose; - thread->DumpThreadPlans (&strm, desc_level, m_options.m_internal, true); - return true; - } + thread->DumpThreadPlans(&strm, desc_level, m_options.m_internal, true); + return true; + } - CommandOptions m_options; + CommandOptions m_options; }; -OptionDefinition -CommandObjectThreadPlanList::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectThreadPlanList::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display more information about the thread plans"}, {LLDB_OPT_SET_1, false, "internal", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display internal as well as user thread plans"}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectThreadPlanDiscard : public CommandObjectParsed -{ +class CommandObjectThreadPlanDiscard : public CommandObjectParsed { public: - CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "thread plan discard", - "Discards thread plans up to and including the specified index (see 'thread plan list'.) " - "Only user visible plans can be discarded.", - nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) - { - CommandArgumentEntry arg; - CommandArgumentData plan_index_arg; - - // Define the first (and only) variant of this arg. - plan_index_arg.arg_type = eArgTypeUnsignedInteger; - plan_index_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (plan_index_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); + CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "thread plan discard", + "Discards thread plans up to and including the " + "specified index (see 'thread plan list'.) " + "Only user visible plans can be discarded.", + nullptr, + eCommandRequiresProcess | eCommandRequiresThread | + eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | + eCommandProcessMustBePaused) { + CommandArgumentEntry arg; + CommandArgumentData plan_index_arg; + + // Define the first (and only) variant of this arg. + plan_index_arg.arg_type = eArgTypeUnsignedInteger; + plan_index_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(plan_index_arg); + + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectThreadPlanDiscard() override = default; + + bool DoExecute(Args &args, CommandReturnObject &result) override { + Thread *thread = m_exe_ctx.GetThreadPtr(); + if (args.GetArgumentCount() != 1) { + result.AppendErrorWithFormat("Too many arguments, expected one - the " + "thread plan index - but got %zu.", + args.GetArgumentCount()); + result.SetStatus(eReturnStatusFailed); + return false; } - ~CommandObjectThreadPlanDiscard() override = default; - - bool - DoExecute (Args& args, CommandReturnObject &result) override - { - Thread *thread = m_exe_ctx.GetThreadPtr(); - if (args.GetArgumentCount() != 1) - { - result.AppendErrorWithFormat("Too many arguments, expected one - the thread plan index - but got %zu.", - args.GetArgumentCount()); - result.SetStatus (eReturnStatusFailed); - return false; - } - - bool success; - uint32_t thread_plan_idx = StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success); - if (!success) - { - result.AppendErrorWithFormat("Invalid thread index: \"%s\" - should be unsigned int.", - args.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool success; + uint32_t thread_plan_idx = + StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success); + if (!success) { + result.AppendErrorWithFormat( + "Invalid thread index: \"%s\" - should be unsigned int.", + args.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (thread_plan_idx == 0) - { - result.AppendErrorWithFormat("You wouldn't really want me to discard the base thread plan."); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (thread_plan_idx == 0) { + result.AppendErrorWithFormat( + "You wouldn't really want me to discard the base thread plan."); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) - { - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return true; - } - else - { - result.AppendErrorWithFormat("Could not find User thread plan with index %s.", - args.GetArgumentAtIndex(0)); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx)) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } else { + result.AppendErrorWithFormat( + "Could not find User thread plan with index %s.", + args.GetArgumentAtIndex(0)); + result.SetStatus(eReturnStatusFailed); + return false; } + } }; //------------------------------------------------------------------------- // CommandObjectMultiwordThreadPlan //------------------------------------------------------------------------- -class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword -{ +class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword { public: - CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "plan", "Commands for managing thread plans that control execution.", - "thread plan [ [ []") -{ - LoadSubCommand ("backtrace", CommandObjectSP (new CommandObjectThreadBacktrace (interpreter))); - LoadSubCommand ("continue", CommandObjectSP (new CommandObjectThreadContinue (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectThreadList (interpreter))); - LoadSubCommand ("return", CommandObjectSP (new CommandObjectThreadReturn (interpreter))); - LoadSubCommand ("jump", CommandObjectSP (new CommandObjectThreadJump (interpreter))); - LoadSubCommand ("select", CommandObjectSP (new CommandObjectThreadSelect (interpreter))); - LoadSubCommand ("until", CommandObjectSP (new CommandObjectThreadUntil (interpreter))); - LoadSubCommand ("info", CommandObjectSP (new CommandObjectThreadInfo (interpreter))); - LoadSubCommand("step-in", - CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( - interpreter, "thread step-in", - "Source level single step, stepping into calls. Defaults to current thread unless specified.", - nullptr, eStepTypeInto, eStepScopeSource))); - - LoadSubCommand("step-out", - CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( - interpreter, "thread step-out", "Finish executing the current stack frame and stop after " - "returning. Defaults to current thread unless specified.", - nullptr, eStepTypeOut, eStepScopeSource))); - - LoadSubCommand("step-over", - CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( - interpreter, "thread step-over", - "Source level single step, stepping over calls. Defaults to current thread unless specified.", - nullptr, eStepTypeOver, eStepScopeSource))); - - LoadSubCommand( - "step-inst", - CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( - interpreter, "thread step-inst", - "Instruction level single step, stepping into calls. Defaults to current thread unless specified.", - nullptr, eStepTypeTrace, eStepScopeInstruction))); - - LoadSubCommand( - "step-inst-over", - CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( - interpreter, "thread step-inst-over", - "Instruction level single step, stepping over calls. Defaults to current thread unless specified.", - nullptr, eStepTypeTraceOver, eStepScopeInstruction))); - - LoadSubCommand ("step-scripted", CommandObjectSP (new CommandObjectThreadStepWithTypeAndScope ( - interpreter, - "thread step-scripted", - "Step as instructed by the script class passed in the -C option.", - nullptr, - eStepTypeScripted, - eStepScopeSource))); - - LoadSubCommand ("plan", CommandObjectSP (new CommandObjectMultiwordThreadPlan(interpreter))); +CommandObjectMultiwordThread::CommandObjectMultiwordThread( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "thread", "Commands for operating on " + "one or more threads in " + "the current process.", + "thread []") { + LoadSubCommand("backtrace", CommandObjectSP(new CommandObjectThreadBacktrace( + interpreter))); + LoadSubCommand("continue", + CommandObjectSP(new CommandObjectThreadContinue(interpreter))); + LoadSubCommand("list", + CommandObjectSP(new CommandObjectThreadList(interpreter))); + LoadSubCommand("return", + CommandObjectSP(new CommandObjectThreadReturn(interpreter))); + LoadSubCommand("jump", + CommandObjectSP(new CommandObjectThreadJump(interpreter))); + LoadSubCommand("select", + CommandObjectSP(new CommandObjectThreadSelect(interpreter))); + LoadSubCommand("until", + CommandObjectSP(new CommandObjectThreadUntil(interpreter))); + LoadSubCommand("info", + CommandObjectSP(new CommandObjectThreadInfo(interpreter))); + LoadSubCommand("step-in", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-in", + "Source level single step, stepping into calls. Defaults " + "to current thread unless specified.", + nullptr, eStepTypeInto, eStepScopeSource))); + + LoadSubCommand("step-out", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-out", + "Finish executing the current stack frame and stop after " + "returning. Defaults to current thread unless specified.", + nullptr, eStepTypeOut, eStepScopeSource))); + + LoadSubCommand("step-over", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-over", + "Source level single step, stepping over calls. Defaults " + "to current thread unless specified.", + nullptr, eStepTypeOver, eStepScopeSource))); + + LoadSubCommand("step-inst", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-inst", + "Instruction level single step, stepping into calls. " + "Defaults to current thread unless specified.", + nullptr, eStepTypeTrace, eStepScopeInstruction))); + + LoadSubCommand("step-inst-over", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-inst-over", + "Instruction level single step, stepping over calls. " + "Defaults to current thread unless specified.", + nullptr, eStepTypeTraceOver, eStepScopeInstruction))); + + LoadSubCommand( + "step-scripted", + CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope( + interpreter, "thread step-scripted", + "Step as instructed by the script class passed in the -C option.", + nullptr, eStepTypeScripted, eStepScopeSource))); + + LoadSubCommand("plan", CommandObjectSP(new CommandObjectMultiwordThreadPlan( + interpreter))); } CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default; diff --git a/lldb/source/Commands/CommandObjectThread.h b/lldb/source/Commands/CommandObjectThread.h index 90f8236b442..589031e0a03 100644 --- a/lldb/source/Commands/CommandObjectThread.h +++ b/lldb/source/Commands/CommandObjectThread.h @@ -18,13 +18,11 @@ namespace lldb_private { -class CommandObjectMultiwordThread : public CommandObjectMultiword -{ +class CommandObjectMultiwordThread : public CommandObjectMultiword { public: + CommandObjectMultiwordThread(CommandInterpreter &interpreter); - CommandObjectMultiwordThread (CommandInterpreter &interpreter); - - ~CommandObjectMultiwordThread() override; + ~CommandObjectMultiwordThread() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectType.cpp b/lldb/source/Commands/CommandObjectType.cpp index 0ddd65b5f72..60ff00a0330 100644 --- a/lldb/source/Commands/CommandObjectType.cpp +++ b/lldb/source/Commands/CommandObjectType.cpp @@ -29,11 +29,11 @@ #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandObject.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionGroupFormat.h" #include "lldb/Interpreter/OptionValueBoolean.h" #include "lldb/Interpreter/OptionValueLanguage.h" #include "lldb/Interpreter/OptionValueString.h" +#include "lldb/Interpreter/Options.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Language.h" #include "lldb/Target/Process.h" @@ -45,697 +45,558 @@ using namespace lldb; using namespace lldb_private; -class ScriptAddOptions -{ +class ScriptAddOptions { public: - TypeSummaryImpl::Flags m_flags; - StringList m_target_types; - bool m_regex; - ConstString m_name; - std::string m_category; - - ScriptAddOptions(const TypeSummaryImpl::Flags& flags, - bool regx, - const ConstString& name, - std::string catg) : - m_flags(flags), - m_regex(regx), - m_name(name), - m_category(catg) - { - } - - typedef std::shared_ptr SharedPointer; + TypeSummaryImpl::Flags m_flags; + StringList m_target_types; + bool m_regex; + ConstString m_name; + std::string m_category; + + ScriptAddOptions(const TypeSummaryImpl::Flags &flags, bool regx, + const ConstString &name, std::string catg) + : m_flags(flags), m_regex(regx), m_name(name), m_category(catg) {} + + typedef std::shared_ptr SharedPointer; }; -class SynthAddOptions -{ +class SynthAddOptions { public: - bool m_skip_pointers; - bool m_skip_references; - bool m_cascade; - bool m_regex; - StringList m_target_types; - std::string m_category; - - SynthAddOptions(bool sptr, - bool sref, - bool casc, - bool regx, - std::string catg) : - m_skip_pointers(sptr), - m_skip_references(sref), - m_cascade(casc), - m_regex(regx), - m_target_types(), - m_category(catg) - { - } - - typedef std::shared_ptr SharedPointer; + bool m_skip_pointers; + bool m_skip_references; + bool m_cascade; + bool m_regex; + StringList m_target_types; + std::string m_category; + + SynthAddOptions(bool sptr, bool sref, bool casc, bool regx, std::string catg) + : m_skip_pointers(sptr), m_skip_references(sref), m_cascade(casc), + m_regex(regx), m_target_types(), m_category(catg) {} + + typedef std::shared_ptr SharedPointer; }; -static bool -WarnOnPotentialUnquotedUnsignedType (Args& command, CommandReturnObject &result) -{ - for (unsigned idx = 0; idx < command.GetArgumentCount(); idx++) - { - const char* arg = command.GetArgumentAtIndex(idx); - if (idx+1 < command.GetArgumentCount()) - { - if (arg && 0 == strcmp(arg,"unsigned")) - { - const char* next = command.GetArgumentAtIndex(idx+1); - if (next && - (0 == strcmp(next, "int") || - 0 == strcmp(next, "short") || - 0 == strcmp(next, "char") || - 0 == strcmp(next, "long"))) - { - result.AppendWarningWithFormat("%s %s being treated as two types. if you meant the combined type name use quotes, as in \"%s %s\"\n", - arg,next,arg,next); - return true; - } - } - } - } - return false; +static bool WarnOnPotentialUnquotedUnsignedType(Args &command, + CommandReturnObject &result) { + for (unsigned idx = 0; idx < command.GetArgumentCount(); idx++) { + const char *arg = command.GetArgumentAtIndex(idx); + if (idx + 1 < command.GetArgumentCount()) { + if (arg && 0 == strcmp(arg, "unsigned")) { + const char *next = command.GetArgumentAtIndex(idx + 1); + if (next && (0 == strcmp(next, "int") || 0 == strcmp(next, "short") || + 0 == strcmp(next, "char") || 0 == strcmp(next, "long"))) { + result.AppendWarningWithFormat("%s %s being treated as two types. if " + "you meant the combined type name use " + "quotes, as in \"%s %s\"\n", + arg, next, arg, next); + return true; + } + } + } + } + return false; } -class CommandObjectTypeSummaryAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectTypeSummaryAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { private: - class CommandOptions : public Options - { - public: - CommandOptions (CommandInterpreter &interpreter) : - Options() - { - } + class CommandOptions : public Options { + public: + CommandOptions(CommandInterpreter &interpreter) : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override; + + void OptionParsingStarting(ExecutionContext *execution_context) override; + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + TypeSummaryImpl::Flags m_flags; + bool m_regex; + std::string m_format_string; + ConstString m_name; + std::string m_python_script; + std::string m_python_function; + bool m_is_add_script; + std::string m_category; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + + bool Execute_ScriptSummary(Args &command, CommandReturnObject &result); + + bool Execute_StringSummary(Args &command, CommandReturnObject &result); - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override; - - void - OptionParsingStarting(ExecutionContext *execution_context) override; - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - TypeSummaryImpl::Flags m_flags; - bool m_regex; - std::string m_format_string; - ConstString m_name; - std::string m_python_script; - std::string m_python_function; - bool m_is_add_script; - std::string m_category; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; - } - - bool - Execute_ScriptSummary (Args& command, CommandReturnObject &result); - - bool - Execute_StringSummary (Args& command, CommandReturnObject &result); - public: - enum SummaryFormatType - { - eRegularSummary, - eRegexSummary, - eNamedSummary - }; - - CommandObjectTypeSummaryAdd (CommandInterpreter &interpreter); + enum SummaryFormatType { eRegularSummary, eRegexSummary, eNamedSummary }; - ~CommandObjectTypeSummaryAdd() override = default; + CommandObjectTypeSummaryAdd(CommandInterpreter &interpreter); - void - IOHandlerActivated (IOHandler &io_handler) override - { - static const char *g_summary_addreader_instructions = "Enter your Python command(s). Type 'DONE' to end.\n" + ~CommandObjectTypeSummaryAdd() override = default; + + void IOHandlerActivated(IOHandler &io_handler) override { + static const char *g_summary_addreader_instructions = + "Enter your Python command(s). Type 'DONE' to end.\n" "def function (valobj,internal_dict):\n" - " \"\"\"valobj: an SBValue which you want to provide a summary for\n" + " \"\"\"valobj: an SBValue which you want to provide a summary " + "for\n" " internal_dict: an LLDB support object not to be used\"\"\"\n"; - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString(g_summary_addreader_instructions); - output_sp->Flush(); - } + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString(g_summary_addreader_instructions); + output_sp->Flush(); } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) override { + StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override - { - StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - #ifndef LLDB_DISABLE_PYTHON - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (interpreter) - { - StringList lines; - lines.SplitIntoLines(data); - if (lines.GetSize() > 0) - { - ScriptAddOptions *options_ptr = ((ScriptAddOptions*)io_handler.GetUserData()); - if (options_ptr) - { - ScriptAddOptions::SharedPointer options(options_ptr); // this will ensure that we get rid of the pointer when going out of scope - - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (interpreter) - { - std::string funct_name_str; - if (interpreter->GenerateTypeScriptFunction (lines, funct_name_str)) - { - if (funct_name_str.empty()) - { - error_sp->Printf ("unable to obtain a valid function name from the script interpreter.\n"); - error_sp->Flush(); - } - else - { - // now I have a valid function name, let's add this as script for every type in the list - - TypeSummaryImplSP script_format; - script_format.reset(new ScriptSummaryFormat(options->m_flags, - funct_name_str.c_str(), - lines.CopyList(" ").c_str())); - - Error error; - - for (size_t i = 0; i < options->m_target_types.GetSize(); i++) - { - const char *type_name = options->m_target_types.GetStringAtIndex(i); - CommandObjectTypeSummaryAdd::AddSummary(ConstString(type_name), - script_format, - (options->m_regex ? CommandObjectTypeSummaryAdd::eRegexSummary : CommandObjectTypeSummaryAdd::eRegularSummary), - options->m_category, - &error); - if (error.Fail()) - { - error_sp->Printf ("error: %s", error.AsCString()); - error_sp->Flush(); - } - } - - if (options->m_name) - { - CommandObjectTypeSummaryAdd::AddSummary (options->m_name, - script_format, - CommandObjectTypeSummaryAdd::eNamedSummary, - options->m_category, - &error); - if (error.Fail()) - { - CommandObjectTypeSummaryAdd::AddSummary (options->m_name, - script_format, - CommandObjectTypeSummaryAdd::eNamedSummary, - options->m_category, - &error); - if (error.Fail()) - { - error_sp->Printf ("error: %s", error.AsCString()); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: %s", error.AsCString()); - error_sp->Flush(); - } - } - else - { - if (error.AsCString()) - { - error_sp->Printf ("error: %s", error.AsCString()); - error_sp->Flush(); - } - } - } - } - else - { - error_sp->Printf ("error: unable to generate a function.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: no script interpreter.\n"); - error_sp->Flush(); - } + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (interpreter) { + StringList lines; + lines.SplitIntoLines(data); + if (lines.GetSize() > 0) { + ScriptAddOptions *options_ptr = + ((ScriptAddOptions *)io_handler.GetUserData()); + if (options_ptr) { + ScriptAddOptions::SharedPointer options( + options_ptr); // this will ensure that we get rid of the pointer + // when going out of scope + + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (interpreter) { + std::string funct_name_str; + if (interpreter->GenerateTypeScriptFunction(lines, + funct_name_str)) { + if (funct_name_str.empty()) { + error_sp->Printf("unable to obtain a valid function name from " + "the script interpreter.\n"); + error_sp->Flush(); + } else { + // now I have a valid function name, let's add this as script + // for every type in the list + + TypeSummaryImplSP script_format; + script_format.reset(new ScriptSummaryFormat( + options->m_flags, funct_name_str.c_str(), + lines.CopyList(" ").c_str())); + + Error error; + + for (size_t i = 0; i < options->m_target_types.GetSize(); i++) { + const char *type_name = + options->m_target_types.GetStringAtIndex(i); + CommandObjectTypeSummaryAdd::AddSummary( + ConstString(type_name), script_format, + (options->m_regex + ? CommandObjectTypeSummaryAdd::eRegexSummary + : CommandObjectTypeSummaryAdd::eRegularSummary), + options->m_category, &error); + if (error.Fail()) { + error_sp->Printf("error: %s", error.AsCString()); + error_sp->Flush(); + } } - else - { - error_sp->Printf ("error: internal synchronization information missing or invalid.\n"); + + if (options->m_name) { + CommandObjectTypeSummaryAdd::AddSummary( + options->m_name, script_format, + CommandObjectTypeSummaryAdd::eNamedSummary, + options->m_category, &error); + if (error.Fail()) { + CommandObjectTypeSummaryAdd::AddSummary( + options->m_name, script_format, + CommandObjectTypeSummaryAdd::eNamedSummary, + options->m_category, &error); + if (error.Fail()) { + error_sp->Printf("error: %s", error.AsCString()); + error_sp->Flush(); + } + } else { + error_sp->Printf("error: %s", error.AsCString()); + error_sp->Flush(); + } + } else { + if (error.AsCString()) { + error_sp->Printf("error: %s", error.AsCString()); error_sp->Flush(); + } } + } + } else { + error_sp->Printf("error: unable to generate a function.\n"); + error_sp->Flush(); } - else - { - error_sp->Printf ("error: empty function, didn't add python command.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: script interpreter missing, didn't add python command.\n"); + } else { + error_sp->Printf("error: no script interpreter.\n"); error_sp->Flush(); - } -#endif // LLDB_DISABLE_PYTHON - io_handler.SetIsDone(true); + } + } else { + error_sp->Printf("error: internal synchronization information " + "missing or invalid.\n"); + error_sp->Flush(); + } + } else { + error_sp->Printf("error: empty function, didn't add python command.\n"); + error_sp->Flush(); + } + } else { + error_sp->Printf( + "error: script interpreter missing, didn't add python command.\n"); + error_sp->Flush(); } - - static bool - AddSummary(ConstString type_name, - lldb::TypeSummaryImplSP entry, - SummaryFormatType type, - std::string category, - Error* error = nullptr); +#endif // LLDB_DISABLE_PYTHON + io_handler.SetIsDone(true); + } + + static bool AddSummary(ConstString type_name, lldb::TypeSummaryImplSP entry, + SummaryFormatType type, std::string category, + Error *error = nullptr); protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override; + bool DoExecute(Args &command, CommandReturnObject &result) override; }; -static const char *g_synth_addreader_instructions = "Enter your Python command(s). Type 'DONE' to end.\n" -"You must define a Python class with these methods:\n" -" def __init__(self, valobj, dict):\n" -" def num_children(self):\n" -" def get_child_at_index(self, index):\n" -" def get_child_index(self, name):\n" -" def update(self):\n" -" '''Optional'''\n" -"class synthProvider:\n"; - -class CommandObjectTypeSynthAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +static const char *g_synth_addreader_instructions = + "Enter your Python command(s). Type 'DONE' to end.\n" + "You must define a Python class with these methods:\n" + " def __init__(self, valobj, dict):\n" + " def num_children(self):\n" + " def get_child_at_index(self, index):\n" + " def get_child_index(self, name):\n" + " def update(self):\n" + " '''Optional'''\n" + "class synthProvider:\n"; + +class CommandObjectTypeSynthAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { private: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success; + + switch (short_option) { + case 'C': + m_cascade = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat("invalid value for cascade: %s", + option_arg); + break; + case 'P': + handwrite_python = true; + break; + case 'l': + m_class_name = std::string(option_arg); + is_class_based = true; + break; + case 'p': + m_skip_pointers = true; + break; + case 'r': + m_skip_references = true; + break; + case 'w': + m_category = std::string(option_arg); + break; + case 'x': + m_regex = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_cascade = true; + m_class_name = ""; + m_skip_pointers = false; + m_skip_references = false; + m_category = "default"; + is_class_based = false; + handwrite_python = false; + m_regex = false; + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + bool m_cascade; + bool m_skip_references; + bool m_skip_pointers; + std::string m_class_name; + bool m_input_python; + std::string m_category; + bool is_class_based; + bool handwrite_python; + bool m_regex; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + + bool Execute_HandwritePython(Args &command, CommandReturnObject &result); + + bool Execute_PythonClass(Args &command, CommandReturnObject &result); - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success; - - switch (short_option) - { - case 'C': - m_cascade = Args::StringToBoolean(option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid value for cascade: %s", option_arg); - break; - case 'P': - handwrite_python = true; - break; - case 'l': - m_class_name = std::string(option_arg); - is_class_based = true; - break; - case 'p': - m_skip_pointers = true; - break; - case 'r': - m_skip_references = true; - break; - case 'w': - m_category = std::string(option_arg); - break; - case 'x': - m_regex = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_cascade = true; - m_class_name = ""; - m_skip_pointers = false; - m_skip_references = false; - m_category = "default"; - is_class_based = false; - handwrite_python = false; - m_regex = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_cascade; - bool m_skip_references; - bool m_skip_pointers; - std::string m_class_name; - bool m_input_python; - std::string m_category; - bool is_class_based; - bool handwrite_python; - bool m_regex; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; - } - - bool - Execute_HandwritePython (Args& command, CommandReturnObject &result); - - bool - Execute_PythonClass (Args& command, CommandReturnObject &result); - protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - WarnOnPotentialUnquotedUnsignedType(command, result); - - if (m_options.handwrite_python) - return Execute_HandwritePython(command, result); - else if (m_options.is_class_based) - return Execute_PythonClass(command, result); - else - { - result.AppendError("must either provide a children list, a Python class name, or use -P and type a Python class line-by-line"); - result.SetStatus(eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + WarnOnPotentialUnquotedUnsignedType(command, result); + + if (m_options.handwrite_python) + return Execute_HandwritePython(command, result); + else if (m_options.is_class_based) + return Execute_PythonClass(command, result); + else { + result.AppendError("must either provide a children list, a Python class " + "name, or use -P and type a Python class " + "line-by-line"); + result.SetStatus(eReturnStatusFailed); + return false; } - - void - IOHandlerActivated (IOHandler &io_handler) override - { - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString(g_synth_addreader_instructions); - output_sp->Flush(); - } + } + + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString(g_synth_addreader_instructions); + output_sp->Flush(); } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &data) override { + StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override - { - StreamFileSP error_sp = io_handler.GetErrorStreamFile(); - #ifndef LLDB_DISABLE_PYTHON - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (interpreter) - { - StringList lines; - lines.SplitIntoLines(data); - if (lines.GetSize() > 0) - { - SynthAddOptions *options_ptr = ((SynthAddOptions*)io_handler.GetUserData()); - if (options_ptr) - { - SynthAddOptions::SharedPointer options(options_ptr); // this will ensure that we get rid of the pointer when going out of scope - - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (interpreter) - { - std::string class_name_str; - if (interpreter->GenerateTypeSynthClass (lines, class_name_str)) - { - if (class_name_str.empty()) - { - error_sp->Printf ("error: unable to obtain a proper name for the class.\n"); - error_sp->Flush(); - } - else - { - // everything should be fine now, let's add the synth provider class - - SyntheticChildrenSP synth_provider; - synth_provider.reset(new ScriptedSyntheticChildren(SyntheticChildren::Flags().SetCascades(options->m_cascade). - SetSkipPointers(options->m_skip_pointers). - SetSkipReferences(options->m_skip_references), - class_name_str.c_str())); - - - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(options->m_category.c_str()), category); - - Error error; - - for (size_t i = 0; i < options->m_target_types.GetSize(); i++) - { - const char *type_name = options->m_target_types.GetStringAtIndex(i); - ConstString const_type_name(type_name); - if (const_type_name) - { - if (!CommandObjectTypeSynthAdd::AddSynth(const_type_name, - synth_provider, - options->m_regex ? CommandObjectTypeSynthAdd::eRegexSynth : CommandObjectTypeSynthAdd::eRegularSynth, - options->m_category, - &error)) - { - error_sp->Printf("error: %s\n", error.AsCString()); - error_sp->Flush(); - break; - } - } - else - { - error_sp->Printf ("error: invalid type name.\n"); - error_sp->Flush(); - break; - } - } - } - } - else - { - error_sp->Printf ("error: unable to generate a class.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: no script interpreter.\n"); - error_sp->Flush(); + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (interpreter) { + StringList lines; + lines.SplitIntoLines(data); + if (lines.GetSize() > 0) { + SynthAddOptions *options_ptr = + ((SynthAddOptions *)io_handler.GetUserData()); + if (options_ptr) { + SynthAddOptions::SharedPointer options( + options_ptr); // this will ensure that we get rid of the pointer + // when going out of scope + + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (interpreter) { + std::string class_name_str; + if (interpreter->GenerateTypeSynthClass(lines, class_name_str)) { + if (class_name_str.empty()) { + error_sp->Printf( + "error: unable to obtain a proper name for the class.\n"); + error_sp->Flush(); + } else { + // everything should be fine now, let's add the synth provider + // class + + SyntheticChildrenSP synth_provider; + synth_provider.reset(new ScriptedSyntheticChildren( + SyntheticChildren::Flags() + .SetCascades(options->m_cascade) + .SetSkipPointers(options->m_skip_pointers) + .SetSkipReferences(options->m_skip_references), + class_name_str.c_str())); + + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory( + ConstString(options->m_category.c_str()), category); + + Error error; + + for (size_t i = 0; i < options->m_target_types.GetSize(); i++) { + const char *type_name = + options->m_target_types.GetStringAtIndex(i); + ConstString const_type_name(type_name); + if (const_type_name) { + if (!CommandObjectTypeSynthAdd::AddSynth( + const_type_name, synth_provider, + options->m_regex + ? CommandObjectTypeSynthAdd::eRegexSynth + : CommandObjectTypeSynthAdd::eRegularSynth, + options->m_category, &error)) { + error_sp->Printf("error: %s\n", error.AsCString()); + error_sp->Flush(); + break; } - } - else - { - error_sp->Printf ("error: internal synchronization data missing.\n"); + } else { + error_sp->Printf("error: invalid type name.\n"); error_sp->Flush(); + break; + } } + } + } else { + error_sp->Printf("error: unable to generate a class.\n"); + error_sp->Flush(); } - else - { - error_sp->Printf ("error: empty function, didn't add python command.\n"); - error_sp->Flush(); - } - } - else - { - error_sp->Printf ("error: script interpreter missing, didn't add python command.\n"); + } else { + error_sp->Printf("error: no script interpreter.\n"); error_sp->Flush(); + } + } else { + error_sp->Printf("error: internal synchronization data missing.\n"); + error_sp->Flush(); } - -#endif // LLDB_DISABLE_PYTHON - io_handler.SetIsDone(true); + } else { + error_sp->Printf("error: empty function, didn't add python command.\n"); + error_sp->Flush(); + } + } else { + error_sp->Printf( + "error: script interpreter missing, didn't add python command.\n"); + error_sp->Flush(); } +#endif // LLDB_DISABLE_PYTHON + io_handler.SetIsDone(true); + } + public: - enum SynthFormatType - { - eRegularSynth, - eRegexSynth - }; - - CommandObjectTypeSynthAdd (CommandInterpreter &interpreter); + enum SynthFormatType { eRegularSynth, eRegexSynth }; + + CommandObjectTypeSynthAdd(CommandInterpreter &interpreter); - ~CommandObjectTypeSynthAdd() override = default; + ~CommandObjectTypeSynthAdd() override = default; - static bool - AddSynth(ConstString type_name, - lldb::SyntheticChildrenSP entry, - SynthFormatType type, - std::string category_name, - Error* error); + static bool AddSynth(ConstString type_name, lldb::SyntheticChildrenSP entry, + SynthFormatType type, std::string category_name, + Error *error); }; //------------------------------------------------------------------------- // CommandObjectTypeFormatAdd //------------------------------------------------------------------------- -class CommandObjectTypeFormatAdd : public CommandObjectParsed -{ +class CommandObjectTypeFormatAdd : public CommandObjectParsed { private: - class CommandOptions : public OptionGroup - { - public: - CommandOptions () : - OptionGroup() - { - } + class CommandOptions : public OptionGroup { + public: + CommandOptions() : OptionGroup() {} + + ~CommandOptions() override = default; + + uint32_t GetNumDefinitions() override; + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_cascade = true; + m_skip_pointers = false; + m_skip_references = false; + m_regex = false; + m_category.assign("default"); + m_custom_type_name.clear(); + } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + const int short_option = g_option_table[option_idx].short_option; + bool success; + + switch (short_option) { + case 'C': + m_cascade = Args::StringToBoolean(option_value, true, &success); + if (!success) + error.SetErrorStringWithFormat("invalid value for cascade: %s", + option_value); + break; + case 'p': + m_skip_pointers = true; + break; + case 'w': + m_category.assign(option_value); + break; + case 'r': + m_skip_references = true; + break; + case 'x': + m_regex = true; + break; + case 't': + m_custom_type_name.assign(option_value); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. - ~CommandOptions() override = default; + bool m_cascade; + bool m_skip_references; + bool m_skip_pointers; + bool m_regex; + std::string m_category; + std::string m_custom_type_name; + }; - uint32_t - GetNumDefinitions () override; - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_cascade = true; - m_skip_pointers = false; - m_skip_references = false; - m_regex = false; - m_category.assign("default"); - m_custom_type_name.clear(); - } + OptionGroupOptions m_option_group; + OptionGroupFormat m_format_options; + CommandOptions m_command_options; + + Options *GetOptions() override { return &m_option_group; } - Error - SetOptionValue(uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = g_option_table[option_idx].short_option; - bool success; - - switch (short_option) - { - case 'C': - m_cascade = Args::StringToBoolean(option_value, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid value for cascade: %s", option_value); - break; - case 'p': - m_skip_pointers = true; - break; - case 'w': - m_category.assign(option_value); - break; - case 'r': - m_skip_references = true; - break; - case 'x': - m_regex = true; - break; - case 't': - m_custom_type_name.assign(option_value); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_cascade; - bool m_skip_references; - bool m_skip_pointers; - bool m_regex; - std::string m_category; - std::string m_custom_type_name; - }; - - OptionGroupOptions m_option_group; - OptionGroupFormat m_format_options; - CommandOptions m_command_options; - - Options * - GetOptions () override - { - return &m_option_group; - } - public: - CommandObjectTypeFormatAdd (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type format add", - "Add a new formatting style for a type.", - nullptr), - m_option_group(), - m_format_options(eFormatInvalid), - m_command_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - - SetHelpLong( -R"( + CommandObjectTypeFormatAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type format add", + "Add a new formatting style for a type.", nullptr), + m_option_group(), m_format_options(eFormatInvalid), + m_command_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + + SetHelpLong( + R"( The following examples of 'type format add' refer to this code snippet for context: typedef int Aint; @@ -754,8 +615,10 @@ Adding default formatting: (lldb) type format add -f hex AInt (lldb) frame variable iy -)" " Produces hexadecimal display of iy, because no formatter is available for Bint and \ -the one for Aint is used instead." R"( +)" + " Produces hexadecimal display of iy, because no formatter is available for Bint and \ +the one for Aint is used instead." + R"( To prevent this use the cascade option '-C no' to prevent evaluation of typedef chains: @@ -766,99 +629,97 @@ Similar reasoning applies to this: (lldb) type format add -f hex -C no float -p -)" " All float values and float references are now formatted as hexadecimal, but not \ -pointers to floats. Nor will it change the default display for Afloat and Bfloat objects." - ); - - // Add the "--format" to all options groups - m_option_group.Append (&m_format_options, OptionGroupFormat::OPTION_GROUP_FORMAT, LLDB_OPT_SET_1); - m_option_group.Append (&m_command_options); - m_option_group.Finalize(); - } +)" + " All float values and float references are now formatted as hexadecimal, but not \ +pointers to floats. Nor will it change the default display for Afloat and Bfloat objects."); + + // Add the "--format" to all options groups + m_option_group.Append(&m_format_options, + OptionGroupFormat::OPTION_GROUP_FORMAT, + LLDB_OPT_SET_1); + m_option_group.Append(&m_command_options); + m_option_group.Finalize(); + } - ~CommandObjectTypeFormatAdd() override = default; + ~CommandObjectTypeFormatAdd() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes one or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - const Format format = m_format_options.GetFormat(); - if (format == eFormatInvalid && m_command_options.m_custom_type_name.empty()) - { - result.AppendErrorWithFormat ("%s needs a valid format.\n", m_cmd_name.c_str()); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1) { + result.AppendErrorWithFormat("%s takes one or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const Format format = m_format_options.GetFormat(); + if (format == eFormatInvalid && + m_command_options.m_custom_type_name.empty()) { + result.AppendErrorWithFormat("%s needs a valid format.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + TypeFormatImplSP entry; + + if (m_command_options.m_custom_type_name.empty()) + entry.reset(new TypeFormatImpl_Format( + format, TypeFormatImpl::Flags() + .SetCascades(m_command_options.m_cascade) + .SetSkipPointers(m_command_options.m_skip_pointers) + .SetSkipReferences(m_command_options.m_skip_references))); + else + entry.reset(new TypeFormatImpl_EnumType( + ConstString(m_command_options.m_custom_type_name.c_str()), + TypeFormatImpl::Flags() + .SetCascades(m_command_options.m_cascade) + .SetSkipPointers(m_command_options.m_skip_pointers) + .SetSkipReferences(m_command_options.m_skip_references))); + + // now I have a valid format, let's add it to every type + + TypeCategoryImplSP category_sp; + DataVisualization::Categories::GetCategory( + ConstString(m_command_options.m_category), category_sp); + if (!category_sp) + return false; + + WarnOnPotentialUnquotedUnsignedType(command, result); + + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); + if (typeCS) { + if (m_command_options.m_regex) { + RegularExpressionSP typeRX(new RegularExpression()); + if (!typeRX->Compile(typeCS.GetCString())) { + result.AppendError( + "regex format error (maybe this is not really a regex?)"); result.SetStatus(eReturnStatusFailed); return false; - } - - TypeFormatImplSP entry; - - if (m_command_options.m_custom_type_name.empty()) - entry.reset(new TypeFormatImpl_Format(format, - TypeFormatImpl::Flags().SetCascades(m_command_options.m_cascade). - SetSkipPointers(m_command_options.m_skip_pointers). - SetSkipReferences(m_command_options.m_skip_references))); - else - entry.reset(new TypeFormatImpl_EnumType(ConstString(m_command_options.m_custom_type_name.c_str()), - TypeFormatImpl::Flags().SetCascades(m_command_options.m_cascade). - SetSkipPointers(m_command_options.m_skip_pointers). - SetSkipReferences(m_command_options.m_skip_references))); - - // now I have a valid format, let's add it to every type - - TypeCategoryImplSP category_sp; - DataVisualization::Categories::GetCategory(ConstString(m_command_options.m_category), category_sp); - if (!category_sp) - return false; - - WarnOnPotentialUnquotedUnsignedType(command, result); - - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - if (typeCS) - { - if (m_command_options.m_regex) - { - RegularExpressionSP typeRX(new RegularExpression()); - if (!typeRX->Compile(typeCS.GetCString())) - { - result.AppendError("regex format error (maybe this is not really a regex?)"); - result.SetStatus(eReturnStatusFailed); - return false; - } - category_sp->GetRegexTypeSummariesContainer()->Delete(typeCS); - category_sp->GetRegexTypeFormatsContainer()->Add(typeRX, entry); - } - else - category_sp->GetTypeFormatsContainer()->Add(typeCS, entry); - } - else - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); + } + category_sp->GetRegexTypeSummariesContainer()->Delete(typeCS); + category_sp->GetRegexTypeFormatsContainer()->Add(typeRX, entry); + } else + category_sp->GetTypeFormatsContainer()->Add(typeCS, entry); + } else { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } } + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); + } }; -OptionDefinition -CommandObjectTypeFormatAdd::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectTypeFormatAdd::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Add this to the given category instead of the default one."}, {LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, cascade through typedef chains."}, {LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects."}, @@ -866,615 +727,506 @@ CommandObjectTypeFormatAdd::CommandOptions::g_option_table[] = {LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Type names are actually regular expressions."}, {LLDB_OPT_SET_2, false, "type", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Format variables as if they were of this type."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -uint32_t -CommandObjectTypeFormatAdd::CommandOptions::GetNumDefinitions () -{ - return sizeof(g_option_table) / sizeof (OptionDefinition); +uint32_t CommandObjectTypeFormatAdd::CommandOptions::GetNumDefinitions() { + return sizeof(g_option_table) / sizeof(OptionDefinition); } -class CommandObjectTypeFormatterDelete : public CommandObjectParsed -{ +class CommandObjectTypeFormatterDelete : public CommandObjectParsed { protected: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - m_delete_all = true; - break; - case 'w': - m_category = std::string(option_arg); - break; - case 'l': - m_language = Language::GetLanguageTypeFromString(option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_delete_all = false; - m_category = "default"; - m_language = lldb::eLanguageTypeUnknown; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_delete_all; - std::string m_category; - lldb::LanguageType m_language; - }; - - CommandOptions m_options; - uint32_t m_formatter_kind_mask; - - Options * - GetOptions () override - { - return &m_options; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': + m_delete_all = true; + break; + case 'w': + m_category = std::string(option_arg); + break; + case 'l': + m_language = Language::GetLanguageTypeFromString(option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - -public: - CommandObjectTypeFormatterDelete (CommandInterpreter &interpreter, - uint32_t formatter_kind_mask, - const char* name, - const char* help) : - CommandObjectParsed(interpreter, - name, - help, - nullptr), - m_options(), - m_formatter_kind_mask(formatter_kind_mask) - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlain; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_delete_all = false; + m_category = "default"; + m_language = lldb::eLanguageTypeUnknown; } - ~CommandObjectTypeFormatterDelete() override = default; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + bool m_delete_all; + std::string m_category; + lldb::LanguageType m_language; + }; + + CommandOptions m_options; + uint32_t m_formatter_kind_mask; + + Options *GetOptions() override { return &m_options; } + +public: + CommandObjectTypeFormatterDelete(CommandInterpreter &interpreter, + uint32_t formatter_kind_mask, + const char *name, const char *help) + : CommandObjectParsed(interpreter, name, help, nullptr), m_options(), + m_formatter_kind_mask(formatter_kind_mask) { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlain; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeFormatterDelete() override = default; protected: - virtual bool - FormatterSpecificDeletion (ConstString typeCS) - { - return false; + virtual bool FormatterSpecificDeletion(ConstString typeCS) { return false; } + + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc != 1) { + result.AppendErrorWithFormat("%s takes 1 arg.\n", m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc != 1) - { - result.AppendErrorWithFormat ("%s takes 1 arg.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - const char* typeA = command.GetArgumentAtIndex(0); - ConstString typeCS(typeA); - - if (!typeCS) - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (m_options.m_delete_all) - { - DataVisualization::Categories::ForEach( [this, typeCS] (const lldb::TypeCategoryImplSP& category_sp) -> bool { - category_sp->Delete(typeCS, m_formatter_kind_mask); - return true; - }); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); - } - - bool delete_category = false; - bool extra_deletion = false; - - if (m_options.m_language != lldb::eLanguageTypeUnknown) - { - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(m_options.m_language, category); - if (category) - delete_category = category->Delete(typeCS, m_formatter_kind_mask); - extra_deletion = FormatterSpecificDeletion(typeCS); - } - else - { - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(m_options.m_category.c_str()), category); - if (category) - delete_category = category->Delete(typeCS, m_formatter_kind_mask); - extra_deletion = FormatterSpecificDeletion(typeCS); - } - - if (delete_category || extra_deletion) - { - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); - } - else - { - result.AppendErrorWithFormat ("no custom formatter for %s.\n", typeA); - result.SetStatus(eReturnStatusFailed); - return false; - } + + const char *typeA = command.GetArgumentAtIndex(0); + ConstString typeCS(typeA); + + if (!typeCS) { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; } + + if (m_options.m_delete_all) { + DataVisualization::Categories::ForEach( + [this, typeCS](const lldb::TypeCategoryImplSP &category_sp) -> bool { + category_sp->Delete(typeCS, m_formatter_kind_mask); + return true; + }); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); + } + + bool delete_category = false; + bool extra_deletion = false; + + if (m_options.m_language != lldb::eLanguageTypeUnknown) { + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory(m_options.m_language, + category); + if (category) + delete_category = category->Delete(typeCS, m_formatter_kind_mask); + extra_deletion = FormatterSpecificDeletion(typeCS); + } else { + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory( + ConstString(m_options.m_category.c_str()), category); + if (category) + delete_category = category->Delete(typeCS, m_formatter_kind_mask); + extra_deletion = FormatterSpecificDeletion(typeCS); + } + + if (delete_category || extra_deletion) { + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); + } else { + result.AppendErrorWithFormat("no custom formatter for %s.\n", typeA); + result.SetStatus(eReturnStatusFailed); + return false; + } + } }; OptionDefinition -CommandObjectTypeFormatterDelete::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTypeFormatterDelete::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "all", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Delete from every category."}, {LLDB_OPT_SET_2, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Delete from given category."}, {LLDB_OPT_SET_3, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Delete from given language's category."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; -class CommandObjectTypeFormatterClear : public CommandObjectParsed -{ +class CommandObjectTypeFormatterClear : public CommandObjectParsed { private: - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'a': - m_delete_all = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_delete_all = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - bool m_delete_all; - }; - - CommandOptions m_options; - uint32_t m_formatter_kind_mask; + ~CommandOptions() override = default; - Options * - GetOptions () override - { - return &m_options; + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'a': + m_delete_all = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - -public: - CommandObjectTypeFormatterClear (CommandInterpreter &interpreter, - uint32_t formatter_kind_mask, - const char* name, - const char* help) : - CommandObjectParsed(interpreter, - name, - help, - nullptr), - m_options(), - m_formatter_kind_mask(formatter_kind_mask) - { + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_delete_all = false; } - ~CommandObjectTypeFormatterClear() override = default; + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + bool m_delete_all; + }; + + CommandOptions m_options; + uint32_t m_formatter_kind_mask; + + Options *GetOptions() override { return &m_options; } + +public: + CommandObjectTypeFormatterClear(CommandInterpreter &interpreter, + uint32_t formatter_kind_mask, + const char *name, const char *help) + : CommandObjectParsed(interpreter, name, help, nullptr), m_options(), + m_formatter_kind_mask(formatter_kind_mask) {} + + ~CommandObjectTypeFormatterClear() override = default; protected: - virtual void - FormatterSpecificDeletion () - { - } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - if (m_options.m_delete_all) - { - DataVisualization::Categories::ForEach( [this] (const TypeCategoryImplSP& category_sp) -> bool { - category_sp->Clear(m_formatter_kind_mask); - return true; - }); - } - else - { - lldb::TypeCategoryImplSP category; - if (command.GetArgumentCount() > 0) - { - const char* cat_name = command.GetArgumentAtIndex(0); - ConstString cat_nameCS(cat_name); - DataVisualization::Categories::GetCategory(cat_nameCS, category); - } - else - { - DataVisualization::Categories::GetCategory(ConstString(nullptr), category); - } - category->Clear(m_formatter_kind_mask); - } - - FormatterSpecificDeletion(); - - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); - } + virtual void FormatterSpecificDeletion() {} + + bool DoExecute(Args &command, CommandReturnObject &result) override { + if (m_options.m_delete_all) { + DataVisualization::Categories::ForEach( + [this](const TypeCategoryImplSP &category_sp) -> bool { + category_sp->Clear(m_formatter_kind_mask); + return true; + }); + } else { + lldb::TypeCategoryImplSP category; + if (command.GetArgumentCount() > 0) { + const char *cat_name = command.GetArgumentAtIndex(0); + ConstString cat_nameCS(cat_name); + DataVisualization::Categories::GetCategory(cat_nameCS, category); + } else { + DataVisualization::Categories::GetCategory(ConstString(nullptr), + category); + } + category->Clear(m_formatter_kind_mask); + } + + FormatterSpecificDeletion(); + + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; OptionDefinition -CommandObjectTypeFormatterClear::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTypeFormatterClear::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "all", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Clear every category."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectTypeFormatDelete //------------------------------------------------------------------------- -class CommandObjectTypeFormatDelete : public CommandObjectTypeFormatterDelete -{ +class CommandObjectTypeFormatDelete : public CommandObjectTypeFormatterDelete { public: - CommandObjectTypeFormatDelete (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterDelete (interpreter, - eFormatCategoryItemValue | eFormatCategoryItemRegexValue, - "type format delete", - "Delete an existing formatting style for a type.") - { - } - - ~CommandObjectTypeFormatDelete() override = default; + CommandObjectTypeFormatDelete(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterDelete( + interpreter, + eFormatCategoryItemValue | eFormatCategoryItemRegexValue, + "type format delete", + "Delete an existing formatting style for a type.") {} + + ~CommandObjectTypeFormatDelete() override = default; }; //------------------------------------------------------------------------- // CommandObjectTypeFormatClear //------------------------------------------------------------------------- -class CommandObjectTypeFormatClear : public CommandObjectTypeFormatterClear -{ +class CommandObjectTypeFormatClear : public CommandObjectTypeFormatterClear { public: - CommandObjectTypeFormatClear (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterClear (interpreter, - eFormatCategoryItemValue | eFormatCategoryItemRegexValue, - "type format clear", - "Delete all existing format styles.") - { - } + CommandObjectTypeFormatClear(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterClear( + interpreter, + eFormatCategoryItemValue | eFormatCategoryItemRegexValue, + "type format clear", "Delete all existing format styles.") {} }; template -class CommandObjectTypeFormatterList : public CommandObjectParsed -{ - typedef typename FormatterType::SharedPointer FormatterSharedPointer; - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_category_regex("",""), - m_category_language(lldb::eLanguageTypeUnknown, lldb::eLanguageTypeUnknown) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'w': - m_category_regex.SetCurrentValue(option_arg); - m_category_regex.SetOptionWasSet(); - break; - case 'l': - error = m_category_language.SetValueFromString(option_arg); - if (error.Success()) - m_category_language.SetOptionWasSet(); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_category_regex.Clear(); - m_category_language.Clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - static OptionDefinition g_option_table[] = - { - // clang-format off +class CommandObjectTypeFormatterList : public CommandObjectParsed { + typedef typename FormatterType::SharedPointer FormatterSharedPointer; + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_category_regex("", ""), + m_category_language(lldb::eLanguageTypeUnknown, + lldb::eLanguageTypeUnknown) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'w': + m_category_regex.SetCurrentValue(option_arg); + m_category_regex.SetOptionWasSet(); + break; + case 'l': + error = m_category_language.SetValueFromString(option_arg); + if (error.Success()) + m_category_language.SetOptionWasSet(); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_category_regex.Clear(); + m_category_language.Clear(); + } + + const OptionDefinition *GetDefinitions() override { + static OptionDefinition g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "category-regex", 'w', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Only show categories matching this filter."}, {LLDB_OPT_SET_2, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Only show the category for a specific language."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on - }; + // clang-format on + }; - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - OptionValueString m_category_regex; - OptionValueLanguage m_category_language; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; + return g_option_table; } + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + OptionValueString m_category_regex; + OptionValueLanguage m_category_language; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + public: - CommandObjectTypeFormatterList (CommandInterpreter &interpreter, - const char* name, - const char* help) : - CommandObjectParsed(interpreter, - name, - help, - nullptr), - m_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatOptional; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - } + CommandObjectTypeFormatterList(CommandInterpreter &interpreter, + const char *name, const char *help) + : CommandObjectParsed(interpreter, name, help, nullptr), m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatOptional; - ~CommandObjectTypeFormatterList() override = default; + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeFormatterList() override = default; protected: - virtual bool - FormatterSpecificList (CommandReturnObject &result) - { + virtual bool FormatterSpecificList(CommandReturnObject &result) { + return false; + } + + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + std::unique_ptr category_regex; + std::unique_ptr formatter_regex; + + if (m_options.m_category_regex.OptionWasSet()) { + category_regex.reset(new RegularExpression()); + if (!category_regex->Compile( + m_options.m_category_regex.GetCurrentValue())) { + result.AppendErrorWithFormat( + "syntax error in category regular expression '%s'", + m_options.m_category_regex.GetCurrentValue()); + result.SetStatus(eReturnStatusFailed); return false; + } } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - std::unique_ptr category_regex; - std::unique_ptr formatter_regex; - - if (m_options.m_category_regex.OptionWasSet()) - { - category_regex.reset(new RegularExpression()); - if (!category_regex->Compile(m_options.m_category_regex.GetCurrentValue())) - { - result.AppendErrorWithFormat("syntax error in category regular expression '%s'", m_options.m_category_regex.GetCurrentValue()); - result.SetStatus(eReturnStatusFailed); - return false; + + if (argc == 1) { + const char *arg = command.GetArgumentAtIndex(0); + formatter_regex.reset(new RegularExpression()); + if (!formatter_regex->Compile(arg)) { + result.AppendErrorWithFormat("syntax error in regular expression '%s'", + arg); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + bool any_printed = false; + + auto category_closure = [&result, &formatter_regex, &any_printed]( + const lldb::TypeCategoryImplSP &category) -> void { + result.GetOutputStream().Printf( + "-----------------------\nCategory: %s%s\n-----------------------\n", + category->GetName(), category->IsEnabled() ? "" : " (disabled)"); + + TypeCategoryImpl::ForEachCallbacks foreach; + foreach + .SetExact([&result, &formatter_regex, &any_printed]( + ConstString name, + const FormatterSharedPointer &format_sp) -> bool { + if (formatter_regex) { + bool escape = true; + if (0 == strcmp(name.AsCString(), formatter_regex->GetText())) { + escape = false; + } else if (formatter_regex->Execute(name.AsCString())) { + escape = false; } - } - - if (argc == 1) - { - const char* arg = command.GetArgumentAtIndex(0); - formatter_regex.reset(new RegularExpression()); - if (!formatter_regex->Compile(arg)) - { - result.AppendErrorWithFormat("syntax error in regular expression '%s'", arg); - result.SetStatus(eReturnStatusFailed); - return false; + + if (escape) + return true; + } + + any_printed = true; + result.GetOutputStream().Printf("%s: %s\n", name.AsCString(), + format_sp->GetDescription().c_str()); + return true; + }); + + foreach + .SetWithRegex([&result, &formatter_regex, &any_printed]( + RegularExpressionSP regex_sp, + const FormatterSharedPointer &format_sp) -> bool { + if (formatter_regex) { + bool escape = true; + if (0 == strcmp(regex_sp->GetText(), formatter_regex->GetText())) { + escape = false; + } else if (formatter_regex->Execute(regex_sp->GetText())) { + escape = false; } - } - - bool any_printed = false; - - auto category_closure = [&result, &formatter_regex, &any_printed] (const lldb::TypeCategoryImplSP& category) -> void { - result.GetOutputStream().Printf("-----------------------\nCategory: %s%s\n-----------------------\n", - category->GetName(), - category->IsEnabled() ? "" : " (disabled)"); - - TypeCategoryImpl::ForEachCallbacks foreach; - foreach.SetExact([&result, &formatter_regex, &any_printed] (ConstString name, const FormatterSharedPointer& format_sp) -> bool { - if (formatter_regex) - { - bool escape = true; - if (0 == strcmp(name.AsCString(), formatter_regex->GetText())) - { - escape = false; - } - else if (formatter_regex->Execute(name.AsCString())) - { - escape = false; - } - - if (escape) - return true; - } - any_printed = true; - result.GetOutputStream().Printf ("%s: %s\n", name.AsCString(), format_sp->GetDescription().c_str()); - return true; - }); - - foreach.SetWithRegex([&result, &formatter_regex, &any_printed] (RegularExpressionSP regex_sp, const FormatterSharedPointer& format_sp) -> bool { - if (formatter_regex) - { - bool escape = true; - if (0 == strcmp(regex_sp->GetText(), formatter_regex->GetText())) - { - escape = false; - } - else if (formatter_regex->Execute(regex_sp->GetText())) - { - escape = false; - } - - if (escape) - return true; - } - - any_printed = true; - result.GetOutputStream().Printf ("%s: %s\n", regex_sp->GetText(), format_sp->GetDescription().c_str()); - return true; - }); - - category->ForEach(foreach); - }; - - if (m_options.m_category_language.OptionWasSet()) - { - lldb::TypeCategoryImplSP category_sp; - DataVisualization::Categories::GetCategory(m_options.m_category_language.GetCurrentValue(), category_sp); - if (category_sp) - category_closure(category_sp); - } - else - { - DataVisualization::Categories::ForEach( [this, &command, &result, &category_regex, &formatter_regex, &category_closure] (const lldb::TypeCategoryImplSP& category) -> bool { - if (category_regex) - { - bool escape = true; - if (0 == strcmp(category->GetName(), category_regex->GetText())) - { - escape = false; - } - else if (category_regex->Execute(category->GetName())) - { - escape = false; - } - - if (escape) - return true; - } - - category_closure(category); - + if (escape) + return true; + } + + any_printed = true; + result.GetOutputStream().Printf("%s: %s\n", regex_sp->GetText(), + format_sp->GetDescription().c_str()); + return true; + }); + + category->ForEach(foreach); + }; + + if (m_options.m_category_language.OptionWasSet()) { + lldb::TypeCategoryImplSP category_sp; + DataVisualization::Categories::GetCategory( + m_options.m_category_language.GetCurrentValue(), category_sp); + if (category_sp) + category_closure(category_sp); + } else { + DataVisualization::Categories::ForEach( + [this, &command, &result, &category_regex, &formatter_regex, + &category_closure]( + const lldb::TypeCategoryImplSP &category) -> bool { + if (category_regex) { + bool escape = true; + if (0 == strcmp(category->GetName(), category_regex->GetText())) { + escape = false; + } else if (category_regex->Execute(category->GetName())) { + escape = false; + } + + if (escape) return true; - }); - - any_printed = FormatterSpecificList(result) | any_printed; - } - - if (any_printed) - result.SetStatus(eReturnStatusSuccessFinishResult); - else - { - result.GetOutputStream().PutCString("no matching results found.\n"); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - return result.Succeeded(); + } + + category_closure(category); + + return true; + }); + + any_printed = FormatterSpecificList(result) | any_printed; + } + + if (any_printed) + result.SetStatus(eReturnStatusSuccessFinishResult); + else { + result.GetOutputStream().PutCString("no matching results found.\n"); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectTypeFormatList //------------------------------------------------------------------------- -class CommandObjectTypeFormatList : public CommandObjectTypeFormatterList -{ +class CommandObjectTypeFormatList + : public CommandObjectTypeFormatterList { public: - - CommandObjectTypeFormatList (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterList(interpreter, - "type format list", - "Show a list of current formats.") - { - } + CommandObjectTypeFormatList(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterList(interpreter, "type format list", + "Show a list of current formats.") {} }; #ifndef LLDB_DISABLE_PYTHON @@ -1485,338 +1237,316 @@ public: #endif // LLDB_DISABLE_PYTHON -Error -CommandObjectTypeSummaryAdd::CommandOptions::SetOptionValue(uint32_t option_idx, - const char - *option_arg, - ExecutionContext - *execution_context) -{ - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success; - - switch (short_option) - { - case 'C': - m_flags.SetCascades(Args::StringToBoolean(option_arg, true, &success)); - if (!success) - error.SetErrorStringWithFormat("invalid value for cascade: %s", option_arg); - break; - case 'e': - m_flags.SetDontShowChildren(false); - break; - case 'h': - m_flags.SetHideEmptyAggregates(true); - break; - case 'v': - m_flags.SetDontShowValue(true); - break; - case 'c': - m_flags.SetShowMembersOneLiner(true); - break; - case 's': - m_format_string = std::string(option_arg); - break; - case 'p': - m_flags.SetSkipPointers(true); - break; - case 'r': - m_flags.SetSkipReferences(true); - break; - case 'x': - m_regex = true; - break; - case 'n': - m_name.SetCString(option_arg); - break; - case 'o': - m_python_script = std::string(option_arg); - m_is_add_script = true; - break; - case 'F': - m_python_function = std::string(option_arg); - m_is_add_script = true; - break; - case 'P': - m_is_add_script = true; - break; - case 'w': - m_category = std::string(option_arg); - break; - case 'O': - m_flags.SetHideItemNames(true); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; +Error CommandObjectTypeSummaryAdd::CommandOptions::SetOptionValue( + uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success; + + switch (short_option) { + case 'C': + m_flags.SetCascades(Args::StringToBoolean(option_arg, true, &success)); + if (!success) + error.SetErrorStringWithFormat("invalid value for cascade: %s", + option_arg); + break; + case 'e': + m_flags.SetDontShowChildren(false); + break; + case 'h': + m_flags.SetHideEmptyAggregates(true); + break; + case 'v': + m_flags.SetDontShowValue(true); + break; + case 'c': + m_flags.SetShowMembersOneLiner(true); + break; + case 's': + m_format_string = std::string(option_arg); + break; + case 'p': + m_flags.SetSkipPointers(true); + break; + case 'r': + m_flags.SetSkipReferences(true); + break; + case 'x': + m_regex = true; + break; + case 'n': + m_name.SetCString(option_arg); + break; + case 'o': + m_python_script = std::string(option_arg); + m_is_add_script = true; + break; + case 'F': + m_python_function = std::string(option_arg); + m_is_add_script = true; + break; + case 'P': + m_is_add_script = true; + break; + case 'w': + m_category = std::string(option_arg); + break; + case 'O': + m_flags.SetHideItemNames(true); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); + break; + } + + return error; } -void -CommandObjectTypeSummaryAdd::CommandOptions::OptionParsingStarting( - ExecutionContext *execution_context) -{ - m_flags.Clear().SetCascades().SetDontShowChildren().SetDontShowValue(false); - m_flags.SetShowMembersOneLiner(false).SetSkipPointers(false).SetSkipReferences(false).SetHideItemNames(false); - - m_regex = false; - m_name.Clear(); - m_python_script = ""; - m_python_function = ""; - m_format_string = ""; - m_is_add_script = false; - m_category = "default"; +void CommandObjectTypeSummaryAdd::CommandOptions::OptionParsingStarting( + ExecutionContext *execution_context) { + m_flags.Clear().SetCascades().SetDontShowChildren().SetDontShowValue(false); + m_flags.SetShowMembersOneLiner(false) + .SetSkipPointers(false) + .SetSkipReferences(false) + .SetHideItemNames(false); + + m_regex = false; + m_name.Clear(); + m_python_script = ""; + m_python_function = ""; + m_format_string = ""; + m_is_add_script = false; + m_category = "default"; } #ifndef LLDB_DISABLE_PYTHON -bool -CommandObjectTypeSummaryAdd::Execute_ScriptSummary (Args& command, CommandReturnObject &result) -{ - const size_t argc = command.GetArgumentCount(); - - if (argc < 1 && !m_options.m_name) - { - result.AppendErrorWithFormat ("%s takes one or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - TypeSummaryImplSP script_format; - - if (!m_options.m_python_function.empty()) // we have a Python function ready to use - { - const char *funct_name = m_options.m_python_function.c_str(); - if (!funct_name || !funct_name[0]) - { - result.AppendError ("function name empty.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - std::string code = (" " + m_options.m_python_function + "(valobj,internal_dict)"); - - script_format.reset(new ScriptSummaryFormat(m_options.m_flags, - funct_name, - code.c_str())); - - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - - if (interpreter && !interpreter->CheckObjectExists(funct_name)) - result.AppendWarningWithFormat("The provided function \"%s\" does not exist - " - "please define it before attempting to use this summary.\n", - funct_name); - } - else if (!m_options.m_python_script.empty()) // we have a quick 1-line script, just use it - { - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - if (!interpreter) - { - result.AppendError ("script interpreter missing - unable to generate function wrapper.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - StringList funct_sl; - funct_sl << m_options.m_python_script.c_str(); - std::string funct_name_str; - if (!interpreter->GenerateTypeScriptFunction (funct_sl, - funct_name_str)) - { - result.AppendError ("unable to generate function wrapper.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - if (funct_name_str.empty()) - { - result.AppendError ("script interpreter failed to generate a valid function name.\n"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - std::string code = " " + m_options.m_python_script; - - script_format.reset(new ScriptSummaryFormat(m_options.m_flags, - funct_name_str.c_str(), - code.c_str())); - } - else - { - // Use an IOHandler to grab Python code from the user - ScriptAddOptions *options = new ScriptAddOptions(m_options.m_flags, - m_options.m_regex, - m_options.m_name, - m_options.m_category); - - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - if (typeA && *typeA) - options->m_target_types << typeA; - else - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - m_interpreter.GetPythonCommandsFromIOHandler (" ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - options); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions - result.SetStatus(eReturnStatusSuccessFinishNoResult); - - return result.Succeeded(); - } - - // if I am here, script_format must point to something good, so I can add that - // as a script summary to all interested parties - - Error error; - - for (size_t i = 0; i < command.GetArgumentCount(); i++) - { - const char *type_name = command.GetArgumentAtIndex(i); - CommandObjectTypeSummaryAdd::AddSummary(ConstString(type_name), - script_format, - (m_options.m_regex ? eRegexSummary : eRegularSummary), - m_options.m_category, - &error); - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - if (m_options.m_name) - { - AddSummary(m_options.m_name, script_format, eNamedSummary, m_options.m_category, &error); - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.AppendError("added to types, but not given a name"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - return result.Succeeded(); -} +bool CommandObjectTypeSummaryAdd::Execute_ScriptSummary( + Args &command, CommandReturnObject &result) { + const size_t argc = command.GetArgumentCount(); -#endif // LLDB_DISABLE_PYTHON + if (argc < 1 && !m_options.m_name) { + result.AppendErrorWithFormat("%s takes one or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } -bool -CommandObjectTypeSummaryAdd::Execute_StringSummary (Args& command, CommandReturnObject &result) -{ - const size_t argc = command.GetArgumentCount(); - - if (argc < 1 && !m_options.m_name) - { - result.AppendErrorWithFormat ("%s takes one or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (!m_options.m_flags.GetShowMembersOneLiner() && m_options.m_format_string.empty()) - { - result.AppendError("empty summary strings not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - const char* format_cstr = (m_options.m_flags.GetShowMembersOneLiner() ? "" : m_options.m_format_string.c_str()); - - // ${var%S} is an endless recursion, prevent it - if (strcmp(format_cstr, "${var%S}") == 0) - { - result.AppendError("recursive summary not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - std::unique_ptr string_format(new StringSummaryFormat(m_options.m_flags, format_cstr)); - if (!string_format) - { - result.AppendError("summary creation failed"); - result.SetStatus(eReturnStatusFailed); - return false; + TypeSummaryImplSP script_format; + + if (!m_options.m_python_function + .empty()) // we have a Python function ready to use + { + const char *funct_name = m_options.m_python_function.c_str(); + if (!funct_name || !funct_name[0]) { + result.AppendError("function name empty.\n"); + result.SetStatus(eReturnStatusFailed); + return false; } - if (string_format->m_error.Fail()) - { - result.AppendErrorWithFormat("syntax error: %s", string_format->m_error.AsCString("")); + + std::string code = + (" " + m_options.m_python_function + "(valobj,internal_dict)"); + + script_format.reset( + new ScriptSummaryFormat(m_options.m_flags, funct_name, code.c_str())); + + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + + if (interpreter && !interpreter->CheckObjectExists(funct_name)) + result.AppendWarningWithFormat( + "The provided function \"%s\" does not exist - " + "please define it before attempting to use this summary.\n", + funct_name); + } else if (!m_options.m_python_script + .empty()) // we have a quick 1-line script, just use it + { + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + if (!interpreter) { + result.AppendError("script interpreter missing - unable to generate " + "function wrapper.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + StringList funct_sl; + funct_sl << m_options.m_python_script.c_str(); + std::string funct_name_str; + if (!interpreter->GenerateTypeScriptFunction(funct_sl, funct_name_str)) { + result.AppendError("unable to generate function wrapper.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (funct_name_str.empty()) { + result.AppendError( + "script interpreter failed to generate a valid function name.\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + std::string code = " " + m_options.m_python_script; + + script_format.reset(new ScriptSummaryFormat( + m_options.m_flags, funct_name_str.c_str(), code.c_str())); + } else { + // Use an IOHandler to grab Python code from the user + ScriptAddOptions *options = + new ScriptAddOptions(m_options.m_flags, m_options.m_regex, + m_options.m_name, m_options.m_category); + + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + if (typeA && *typeA) + options->m_target_types << typeA; + else { + result.AppendError("empty typenames not allowed"); result.SetStatus(eReturnStatusFailed); return false; + } } - lldb::TypeSummaryImplSP entry(string_format.release()); - - // now I have a valid format, let's add it to every type - Error error; - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - if (!typeA || typeA[0] == '\0') - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - ConstString typeCS(typeA); - - AddSummary(typeCS, - entry, - (m_options.m_regex ? eRegexSummary : eRegularSummary), - m_options.m_category, - &error); - - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - if (m_options.m_name) - { - AddSummary(m_options.m_name, entry, eNamedSummary, m_options.m_category, &error); - if (error.Fail()) - { - result.AppendError(error.AsCString()); - result.AppendError("added to types, but not given a name"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - + + m_interpreter.GetPythonCommandsFromIOHandler( + " ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + options); // Baton for the "io_handler" that will be passed back into + // our IOHandlerDelegate functions result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); + } + + // if I am here, script_format must point to something good, so I can add that + // as a script summary to all interested parties + + Error error; + + for (size_t i = 0; i < command.GetArgumentCount(); i++) { + const char *type_name = command.GetArgumentAtIndex(i); + CommandObjectTypeSummaryAdd::AddSummary( + ConstString(type_name), script_format, + (m_options.m_regex ? eRegexSummary : eRegularSummary), + m_options.m_category, &error); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + if (m_options.m_name) { + AddSummary(m_options.m_name, script_format, eNamedSummary, + m_options.m_category, &error); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.AppendError("added to types, but not given a name"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + return result.Succeeded(); +} + +#endif // LLDB_DISABLE_PYTHON + +bool CommandObjectTypeSummaryAdd::Execute_StringSummary( + Args &command, CommandReturnObject &result) { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1 && !m_options.m_name) { + result.AppendErrorWithFormat("%s takes one or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (!m_options.m_flags.GetShowMembersOneLiner() && + m_options.m_format_string.empty()) { + result.AppendError("empty summary strings not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + const char *format_cstr = (m_options.m_flags.GetShowMembersOneLiner() + ? "" + : m_options.m_format_string.c_str()); + + // ${var%S} is an endless recursion, prevent it + if (strcmp(format_cstr, "${var%S}") == 0) { + result.AppendError("recursive summary not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + std::unique_ptr string_format( + new StringSummaryFormat(m_options.m_flags, format_cstr)); + if (!string_format) { + result.AppendError("summary creation failed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (string_format->m_error.Fail()) { + result.AppendErrorWithFormat("syntax error: %s", + string_format->m_error.AsCString("")); + result.SetStatus(eReturnStatusFailed); + return false; + } + lldb::TypeSummaryImplSP entry(string_format.release()); + + // now I have a valid format, let's add it to every type + Error error; + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + if (!typeA || typeA[0] == '\0') { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + ConstString typeCS(typeA); + + AddSummary(typeCS, entry, + (m_options.m_regex ? eRegexSummary : eRegularSummary), + m_options.m_category, &error); + + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + if (m_options.m_name) { + AddSummary(m_options.m_name, entry, eNamedSummary, m_options.m_category, + &error); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.AppendError("added to types, but not given a name"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); } -CommandObjectTypeSummaryAdd::CommandObjectTypeSummaryAdd (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type summary add", - "Add a new summary style for a type.", - nullptr), - IOHandlerDelegateMultiline ("DONE"), - m_options (interpreter) -{ - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - - SetHelpLong( -R"( +CommandObjectTypeSummaryAdd::CommandObjectTypeSummaryAdd( + CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type summary add", + "Add a new summary style for a type.", nullptr), + IOHandlerDelegateMultiline("DONE"), m_options(interpreter) { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + + SetHelpLong( + R"( The following examples of 'type summary add' refer to this code snippet for context: struct JustADemo @@ -1838,51 +1568,65 @@ The following examples of 'type summary add' refer to this code snippet for cont Subsequently displaying demo_instance with 'frame variable' or 'expression' will display "the answer is 42 and the question is 3.14" -)" "Alternatively, you could define formatting for all pointers to integers and \ -rely on that when formatting JustADemo to obtain the same result:" R"( +)" + "Alternatively, you could define formatting for all pointers to integers and \ +rely on that when formatting JustADemo to obtain the same result:" + R"( (lldb) type summary add --summary-string "${var%V} -> ${*var}" "int *" (lldb) type summary add --summary-string "the answer is ${var.ptr}, and the question is ${var.value}" JustADemo -)" "Type summaries are automatically applied to derived typedefs, so the examples \ +)" + "Type summaries are automatically applied to derived typedefs, so the examples \ above apply to both JustADemo and NewDemo. The cascade option can be used to \ -suppress this behavior:" R"( +suppress this behavior:" + R"( (lldb) type summary add --summary-string "${var.ptr}, ${var.value},{${var.byte}}" JustADemo -C no The summary will now be used for values of JustADemo but not NewDemo. -)" "By default summaries are shown for pointers and references to values of the \ +)" + "By default summaries are shown for pointers and references to values of the \ specified type. To suppress formatting for pointers use the -p option, or apply \ -the corresponding -r option to suppress formatting for references:" R"( +the corresponding -r option to suppress formatting for references:" + R"( (lldb) type summary add -p -r --summary-string "${var.ptr}, ${var.value},{${var.byte}}" JustADemo -)" "One-line summaries including all fields in a type can be inferred without supplying an \ -explicit summary string by passing the -c option:" R"( +)" + "One-line summaries including all fields in a type can be inferred without supplying an \ +explicit summary string by passing the -c option:" + R"( (lldb) type summary add -c JustADemo (lldb) frame variable demo_instance (ptr=
, value=3.14) -)" "Type summaries normally suppress the nested display of individual fields. To \ -supply a summary to supplement the default structure add the -e option:" R"( +)" + "Type summaries normally suppress the nested display of individual fields. To \ +supply a summary to supplement the default structure add the -e option:" + R"( (lldb) type summary add -e --summary-string "*ptr = ${*var.ptr}" JustADemo -)" "Now when displaying JustADemo values the int* is displayed, followed by the \ -standard LLDB sequence of children, one per line:" R"( +)" + "Now when displaying JustADemo values the int* is displayed, followed by the \ +standard LLDB sequence of children, one per line:" + R"( *ptr = 42 { ptr =
value = 3.14 } -)" "You can also add summaries written in Python. These scripts use lldb public API to \ +)" + "You can also add summaries written in Python. These scripts use lldb public API to \ gather information from your variables and produce a meaningful summary. To start a \ multi-line script use the -P option. The function declaration will be displayed along with \ a comment describing the two arguments. End your script with the word 'DONE' on a line by \ -itself:" R"( +itself:" + R"( (lldb) type summary add JustADemo -P def function (valobj,internal_dict): @@ -1894,96 +1638,82 @@ internal_dict: an LLDB support object not to be used""" Alternatively, the -o option can be used when providing a simple one-line Python script: -(lldb) type summary add JustADemo -o "value = valobj.GetChildMemberWithName('value'); return 'My value is ' + value.GetValue();")" - ); +(lldb) type summary add JustADemo -o "value = valobj.GetChildMemberWithName('value'); return 'My value is ' + value.GetValue();")"); } -bool -CommandObjectTypeSummaryAdd::DoExecute (Args& command, CommandReturnObject &result) -{ - WarnOnPotentialUnquotedUnsignedType(command, result); +bool CommandObjectTypeSummaryAdd::DoExecute(Args &command, + CommandReturnObject &result) { + WarnOnPotentialUnquotedUnsignedType(command, result); - if (m_options.m_is_add_script) - { + if (m_options.m_is_add_script) { #ifndef LLDB_DISABLE_PYTHON - return Execute_ScriptSummary(command, result); + return Execute_ScriptSummary(command, result); #else - result.AppendError ("python is disabled"); - result.SetStatus(eReturnStatusFailed); - return false; + result.AppendError("python is disabled"); + result.SetStatus(eReturnStatusFailed); + return false; #endif // LLDB_DISABLE_PYTHON - } - - return Execute_StringSummary(command, result); -} + } -static bool -FixArrayTypeNameWithRegex (ConstString &type_name) -{ - llvm::StringRef type_name_ref(type_name.GetStringRef()); - - if (type_name_ref.endswith("[]")) - { - std::string type_name_str(type_name.GetCString()); - type_name_str.resize(type_name_str.length()-2); - if (type_name_str.back() != ' ') - type_name_str.append(" \\[[0-9]+\\]"); - else - type_name_str.append("\\[[0-9]+\\]"); - type_name.SetCString(type_name_str.c_str()); - return true; - } - return false; + return Execute_StringSummary(command, result); } -bool -CommandObjectTypeSummaryAdd::AddSummary(ConstString type_name, - TypeSummaryImplSP entry, - SummaryFormatType type, - std::string category_name, - Error* error) -{ - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), category); - - if (type == eRegularSummary) - { - if (FixArrayTypeNameWithRegex (type_name)) - type = eRegexSummary; - } - - if (type == eRegexSummary) - { - RegularExpressionSP typeRX(new RegularExpression()); - if (!typeRX->Compile(type_name.GetCString())) - { - if (error) - error->SetErrorString("regex format error (maybe this is not really a regex?)"); - return false; - } - - category->GetRegexTypeSummariesContainer()->Delete(type_name); - category->GetRegexTypeSummariesContainer()->Add(typeRX, entry); - - return true; - } - else if (type == eNamedSummary) - { - // system named summaries do not exist (yet?) - DataVisualization::NamedSummaryFormats::Add(type_name,entry); - return true; - } +static bool FixArrayTypeNameWithRegex(ConstString &type_name) { + llvm::StringRef type_name_ref(type_name.GetStringRef()); + + if (type_name_ref.endswith("[]")) { + std::string type_name_str(type_name.GetCString()); + type_name_str.resize(type_name_str.length() - 2); + if (type_name_str.back() != ' ') + type_name_str.append(" \\[[0-9]+\\]"); else - { - category->GetTypeSummariesContainer()->Add(type_name, entry); - return true; - } -} + type_name_str.append("\\[[0-9]+\\]"); + type_name.SetCString(type_name_str.c_str()); + return true; + } + return false; +} -OptionDefinition -CommandObjectTypeSummaryAdd::CommandOptions::g_option_table[] = -{ - // clang-format off +bool CommandObjectTypeSummaryAdd::AddSummary(ConstString type_name, + TypeSummaryImplSP entry, + SummaryFormatType type, + std::string category_name, + Error *error) { + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), + category); + + if (type == eRegularSummary) { + if (FixArrayTypeNameWithRegex(type_name)) + type = eRegexSummary; + } + + if (type == eRegexSummary) { + RegularExpressionSP typeRX(new RegularExpression()); + if (!typeRX->Compile(type_name.GetCString())) { + if (error) + error->SetErrorString( + "regex format error (maybe this is not really a regex?)"); + return false; + } + + category->GetRegexTypeSummariesContainer()->Delete(type_name); + category->GetRegexTypeSummariesContainer()->Add(typeRX, entry); + + return true; + } else if (type == eNamedSummary) { + // system named summaries do not exist (yet?) + DataVisualization::NamedSummaryFormats::Add(type_name, entry); + return true; + } else { + category->GetTypeSummariesContainer()->Add(type_name, entry); + return true; + } +} + +OptionDefinition CommandObjectTypeSummaryAdd::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "category", 'w', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Add this to the given category instead of the default one."}, {LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, cascade through typedef chains."}, {LLDB_OPT_SET_ALL, false, "no-value", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't show the value, just show the summary, for this type."}, @@ -2000,678 +1730,563 @@ CommandObjectTypeSummaryAdd::CommandOptions::g_option_table[] = {LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "hide-empty", 'h', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Do not expand aggregate data types with no children."}, {LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "A name for this summary string."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectTypeSummaryDelete //------------------------------------------------------------------------- -class CommandObjectTypeSummaryDelete : public CommandObjectTypeFormatterDelete -{ +class CommandObjectTypeSummaryDelete : public CommandObjectTypeFormatterDelete { public: - CommandObjectTypeSummaryDelete (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterDelete (interpreter, - eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary, - "type summary delete", - "Delete an existing summary for a type.") - { - } + CommandObjectTypeSummaryDelete(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterDelete( + interpreter, + eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary, + "type summary delete", "Delete an existing summary for a type.") {} - ~CommandObjectTypeSummaryDelete() override = default; + ~CommandObjectTypeSummaryDelete() override = default; protected: - bool - FormatterSpecificDeletion (ConstString typeCS) override - { - if (m_options.m_language != lldb::eLanguageTypeUnknown) - return false; - return DataVisualization::NamedSummaryFormats::Delete(typeCS); - } + bool FormatterSpecificDeletion(ConstString typeCS) override { + if (m_options.m_language != lldb::eLanguageTypeUnknown) + return false; + return DataVisualization::NamedSummaryFormats::Delete(typeCS); + } }; -class CommandObjectTypeSummaryClear : public CommandObjectTypeFormatterClear -{ +class CommandObjectTypeSummaryClear : public CommandObjectTypeFormatterClear { public: - CommandObjectTypeSummaryClear (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterClear (interpreter, - eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary, - "type summary clear", - "Delete all existing summaries.") - { - } - + CommandObjectTypeSummaryClear(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterClear( + interpreter, + eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary, + "type summary clear", "Delete all existing summaries.") {} + protected: - void - FormatterSpecificDeletion () override - { - DataVisualization::NamedSummaryFormats::Clear(); - } + void FormatterSpecificDeletion() override { + DataVisualization::NamedSummaryFormats::Clear(); + } }; //------------------------------------------------------------------------- // CommandObjectTypeSummaryList //------------------------------------------------------------------------- -class CommandObjectTypeSummaryList : public CommandObjectTypeFormatterList -{ +class CommandObjectTypeSummaryList + : public CommandObjectTypeFormatterList { public: - CommandObjectTypeSummaryList (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterList(interpreter, - "type summary list", - "Show a list of current summaries.") - { - } - + CommandObjectTypeSummaryList(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterList(interpreter, "type summary list", + "Show a list of current summaries.") {} + protected: - bool - FormatterSpecificList (CommandReturnObject &result) override - { - if (DataVisualization::NamedSummaryFormats::GetCount() > 0) - { - result.GetOutputStream().Printf("Named summaries:\n"); - DataVisualization::NamedSummaryFormats::ForEach( [&result] (ConstString name, const TypeSummaryImplSP& summary_sp) -> bool { - result.GetOutputStream().Printf ("%s: %s\n", name.AsCString(), summary_sp->GetDescription().c_str()); - return true; - }); + bool FormatterSpecificList(CommandReturnObject &result) override { + if (DataVisualization::NamedSummaryFormats::GetCount() > 0) { + result.GetOutputStream().Printf("Named summaries:\n"); + DataVisualization::NamedSummaryFormats::ForEach( + [&result](ConstString name, + const TypeSummaryImplSP &summary_sp) -> bool { + result.GetOutputStream().Printf( + "%s: %s\n", name.AsCString(), + summary_sp->GetDescription().c_str()); return true; - } - return false; + }); + return true; } + return false; + } }; //------------------------------------------------------------------------- // CommandObjectTypeCategoryDefine //------------------------------------------------------------------------- -class CommandObjectTypeCategoryDefine : public CommandObjectParsed -{ - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_define_enabled(false,false), - m_cate_language(eLanguageTypeUnknown,eLanguageTypeUnknown) - { - } +class CommandObjectTypeCategoryDefine : public CommandObjectParsed { + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_define_enabled(false, false), + m_cate_language(eLanguageTypeUnknown, eLanguageTypeUnknown) {} - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'e': - m_define_enabled.SetValueFromString("true"); - break; - case 'l': - error = m_cate_language.SetValueFromString(option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_define_enabled.Clear(); - m_cate_language.Clear(); - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - OptionValueBoolean m_define_enabled; - OptionValueLanguage m_cate_language; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'e': + m_define_enabled.SetValueFromString("true"); + break; + case 'l': + error = m_cate_language.SetValueFromString(option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_define_enabled.Clear(); + m_cate_language.Clear(); } + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + OptionValueBoolean m_define_enabled; + OptionValueLanguage m_cate_language; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + public: - CommandObjectTypeCategoryDefine (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type category define", + CommandObjectTypeCategoryDefine(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type category define", "Define a new category as a source of formatters.", nullptr), - m_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - } + m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); - ~CommandObjectTypeCategoryDefine() override = default; + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeCategoryDefine() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes 1 or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - for (size_t i = 0; i < argc; i++) - { - const char* cateName = command.GetArgumentAtIndex(i); - TypeCategoryImplSP category_sp; - if (DataVisualization::Categories::GetCategory(ConstString(cateName), category_sp) && category_sp) - { - category_sp->AddLanguage(m_options.m_cate_language.GetCurrentValue()); - if (m_options.m_define_enabled.GetCurrentValue()) - DataVisualization::Categories::Enable(category_sp, TypeCategoryMap::Default); - } - } - - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1) { + result.AppendErrorWithFormat("%s takes 1 or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + for (size_t i = 0; i < argc; i++) { + const char *cateName = command.GetArgumentAtIndex(i); + TypeCategoryImplSP category_sp; + if (DataVisualization::Categories::GetCategory(ConstString(cateName), + category_sp) && + category_sp) { + category_sp->AddLanguage(m_options.m_cate_language.GetCurrentValue()); + if (m_options.m_define_enabled.GetCurrentValue()) + DataVisualization::Categories::Enable(category_sp, + TypeCategoryMap::Default); + } } + + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; OptionDefinition -CommandObjectTypeCategoryDefine::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTypeCategoryDefine::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "enabled", 'e', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "If specified, this category will be created enabled."}, {LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Specify the language that this category is supported for."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectTypeCategoryEnable //------------------------------------------------------------------------- -class CommandObjectTypeCategoryEnable : public CommandObjectParsed -{ - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } +class CommandObjectTypeCategoryEnable : public CommandObjectParsed { + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'l': - if (option_arg) - { - m_language = Language::GetLanguageTypeFromString(option_arg); - if (m_language == lldb::eLanguageTypeUnknown) - error.SetErrorStringWithFormat ("unrecognized language '%s'", option_arg); - } - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_language = lldb::eLanguageTypeUnknown; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'l': + if (option_arg) { + m_language = Language::GetLanguageTypeFromString(option_arg); + if (m_language == lldb::eLanguageTypeUnknown) + error.SetErrorStringWithFormat("unrecognized language '%s'", + option_arg); } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - lldb::LanguageType m_language; - - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_language = lldb::eLanguageTypeUnknown; + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + lldb::LanguageType m_language; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + public: - CommandObjectTypeCategoryEnable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type category enable", + CommandObjectTypeCategoryEnable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type category enable", "Enable a category as a source of formatters.", nullptr), - m_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - - } + m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); - ~CommandObjectTypeCategoryEnable() override = default; + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeCategoryEnable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1 && - m_options.m_language == lldb::eLanguageTypeUnknown) - { - result.AppendErrorWithFormat ("%s takes arguments and/or a language", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (argc == 1 && strcmp(command.GetArgumentAtIndex(0),"*") == 0) - { - DataVisualization::Categories::EnableStar(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1 && m_options.m_language == lldb::eLanguageTypeUnknown) { + result.AppendErrorWithFormat("%s takes arguments and/or a language", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (argc == 1 && strcmp(command.GetArgumentAtIndex(0), "*") == 0) { + DataVisualization::Categories::EnableStar(); + } else if (argc > 0) { + for (int i = argc - 1; i >= 0; i--) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); + + if (!typeCS) { + result.AppendError("empty category name not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; } - else if (argc > 0) - { - for (int i = argc - 1; i >= 0; i--) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - - if (!typeCS) - { - result.AppendError("empty category name not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - DataVisualization::Categories::Enable(typeCS); - lldb::TypeCategoryImplSP cate; - if (DataVisualization::Categories::GetCategory(typeCS, cate) && cate) - { - if (cate->GetCount() == 0) - { - result.AppendWarning("empty category enabled (typo?)"); - } - } - } + DataVisualization::Categories::Enable(typeCS); + lldb::TypeCategoryImplSP cate; + if (DataVisualization::Categories::GetCategory(typeCS, cate) && cate) { + if (cate->GetCount() == 0) { + result.AppendWarning("empty category enabled (typo?)"); + } } - - if (m_options.m_language != lldb::eLanguageTypeUnknown) - DataVisualization::Categories::Enable(m_options.m_language); - - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); + } } + + if (m_options.m_language != lldb::eLanguageTypeUnknown) + DataVisualization::Categories::Enable(m_options.m_language); + + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; OptionDefinition -CommandObjectTypeCategoryEnable::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTypeCategoryEnable::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Enable the category for this language."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectTypeCategoryDelete //------------------------------------------------------------------------- -class CommandObjectTypeCategoryDelete : public CommandObjectParsed -{ +class CommandObjectTypeCategoryDelete : public CommandObjectParsed { public: - CommandObjectTypeCategoryDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type category delete", + CommandObjectTypeCategoryDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type category delete", "Delete a category and all associated formatters.", - nullptr) - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - } + nullptr) { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; - ~CommandObjectTypeCategoryDelete() override = default; + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeCategoryDelete() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes 1 or more arg.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - bool success = true; - - // the order is not relevant here - for (int i = argc - 1; i >= 0; i--) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - - if (!typeCS) - { - result.AppendError("empty category name not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - if (!DataVisualization::Categories::Delete(typeCS)) - success = false; // keep deleting even if we hit an error - } - if (success) - { - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); - } - else - { - result.AppendError("cannot delete one or more categories\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1) { + result.AppendErrorWithFormat("%s takes 1 or more arg.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; } + + bool success = true; + + // the order is not relevant here + for (int i = argc - 1; i >= 0; i--) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); + + if (!typeCS) { + result.AppendError("empty category name not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + if (!DataVisualization::Categories::Delete(typeCS)) + success = false; // keep deleting even if we hit an error + } + if (success) { + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } else { + result.AppendError("cannot delete one or more categories\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } }; //------------------------------------------------------------------------- // CommandObjectTypeCategoryDisable //------------------------------------------------------------------------- -class CommandObjectTypeCategoryDisable : public CommandObjectParsed -{ - class CommandOptions : public Options - { - public: - CommandOptions() : - Options() - { - } +class CommandObjectTypeCategoryDisable : public CommandObjectParsed { + class CommandOptions : public Options { + public: + CommandOptions() : Options() {} - ~CommandOptions() override = default; - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'l': - if (option_arg) - { - m_language = Language::GetLanguageTypeFromString(option_arg); - if (m_language == lldb::eLanguageTypeUnknown) - error.SetErrorStringWithFormat ("unrecognized language '%s'", option_arg); - } - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_language = lldb::eLanguageTypeUnknown; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'l': + if (option_arg) { + m_language = Language::GetLanguageTypeFromString(option_arg); + if (m_language == lldb::eLanguageTypeUnknown) + error.SetErrorStringWithFormat("unrecognized language '%s'", + option_arg); } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - lldb::LanguageType m_language; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_language = lldb::eLanguageTypeUnknown; + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. + + lldb::LanguageType m_language; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + public: - CommandObjectTypeCategoryDisable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type category disable", + CommandObjectTypeCategoryDisable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type category disable", "Disable a category as a source of formatters.", nullptr), - m_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - } + m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; - ~CommandObjectTypeCategoryDisable() override = default; + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeCategoryDisable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1 && - m_options.m_language == lldb::eLanguageTypeUnknown) - { - result.AppendErrorWithFormat ("%s takes arguments and/or a language", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (argc == 1 && strcmp(command.GetArgumentAtIndex(0),"*") == 0) - { - DataVisualization::Categories::DisableStar(); - } - else if (argc > 0) - { - // the order is not relevant here - for (int i = argc - 1; i >= 0; i--) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - - if (!typeCS) - { - result.AppendError("empty category name not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - DataVisualization::Categories::Disable(typeCS); - } - } - - if (m_options.m_language != lldb::eLanguageTypeUnknown) - DataVisualization::Categories::Disable(m_options.m_language); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1 && m_options.m_language == lldb::eLanguageTypeUnknown) { + result.AppendErrorWithFormat("%s takes arguments and/or a language", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (argc == 1 && strcmp(command.GetArgumentAtIndex(0), "*") == 0) { + DataVisualization::Categories::DisableStar(); + } else if (argc > 0) { + // the order is not relevant here + for (int i = argc - 1; i >= 0; i--) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); + if (!typeCS) { + result.AppendError("empty category name not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + DataVisualization::Categories::Disable(typeCS); + } } + + if (m_options.m_language != lldb::eLanguageTypeUnknown) + DataVisualization::Categories::Disable(m_options.m_language); + + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; OptionDefinition -CommandObjectTypeCategoryDisable::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectTypeCategoryDisable::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Enable the category for this language."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectTypeCategoryList //------------------------------------------------------------------------- -class CommandObjectTypeCategoryList : public CommandObjectParsed -{ +class CommandObjectTypeCategoryList : public CommandObjectParsed { public: - CommandObjectTypeCategoryList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type category list", + CommandObjectTypeCategoryList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type category list", "Provide a list of all existing categories.", - nullptr) - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatOptional; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - } + nullptr) { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatOptional; + + type_arg.push_back(type_style_arg); - ~CommandObjectTypeCategoryList() override = default; + m_arguments.push_back(type_arg); + } + + ~CommandObjectTypeCategoryList() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - std::unique_ptr regex; - - if (argc == 1) - { - regex.reset(new RegularExpression()); - const char* arg = command.GetArgumentAtIndex(0); - if (!regex->Compile(arg)) - { - result.AppendErrorWithFormat("syntax error in category regular expression '%s'", arg); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else if (argc != 0) - { - result.AppendErrorWithFormat ("%s takes 0 or one arg.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - DataVisualization::Categories::ForEach( [®ex, &result] (const lldb::TypeCategoryImplSP& category_sp) -> bool { - if (regex) - { - bool escape = true; - if (0 == strcmp(category_sp->GetName(), regex->GetText())) - { - escape = false; - } - else if (regex->Execute(category_sp->GetName())) - { - escape = false; - } - - if (escape) - return true; + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + std::unique_ptr regex; + + if (argc == 1) { + regex.reset(new RegularExpression()); + const char *arg = command.GetArgumentAtIndex(0); + if (!regex->Compile(arg)) { + result.AppendErrorWithFormat( + "syntax error in category regular expression '%s'", arg); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else if (argc != 0) { + result.AppendErrorWithFormat("%s takes 0 or one arg.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + DataVisualization::Categories::ForEach( + [®ex, &result](const lldb::TypeCategoryImplSP &category_sp) -> bool { + if (regex) { + bool escape = true; + if (0 == strcmp(category_sp->GetName(), regex->GetText())) { + escape = false; + } else if (regex->Execute(category_sp->GetName())) { + escape = false; } - - result.GetOutputStream().Printf("Category: %s\n", category_sp->GetDescription().c_str()); - - return true; + + if (escape) + return true; + } + + result.GetOutputStream().Printf( + "Category: %s\n", category_sp->GetDescription().c_str()); + + return true; }); - - result.SetStatus(eReturnStatusSuccessFinishResult); - return result.Succeeded(); - } + + result.SetStatus(eReturnStatusSuccessFinishResult); + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectTypeFilterList //------------------------------------------------------------------------- -class CommandObjectTypeFilterList : public CommandObjectTypeFormatterList -{ +class CommandObjectTypeFilterList + : public CommandObjectTypeFormatterList { public: - CommandObjectTypeFilterList (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterList(interpreter, - "type filter list", - "Show a list of current filters.") - { - } + CommandObjectTypeFilterList(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterList(interpreter, "type filter list", + "Show a list of current filters.") {} }; #ifndef LLDB_DISABLE_PYTHON @@ -2680,15 +2295,13 @@ public: // CommandObjectTypeSynthList //------------------------------------------------------------------------- -class CommandObjectTypeSynthList : public CommandObjectTypeFormatterList -{ +class CommandObjectTypeSynthList + : public CommandObjectTypeFormatterList { public: - CommandObjectTypeSynthList (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterList(interpreter, - "type synthetic list", - "Show a list of current synthetic providers.") - { - } + CommandObjectTypeSynthList(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterList( + interpreter, "type synthetic list", + "Show a list of current synthetic providers.") {} }; #endif // LLDB_DISABLE_PYTHON @@ -2697,18 +2310,15 @@ public: // CommandObjectTypeFilterDelete //------------------------------------------------------------------------- -class CommandObjectTypeFilterDelete : public CommandObjectTypeFormatterDelete -{ +class CommandObjectTypeFilterDelete : public CommandObjectTypeFormatterDelete { public: - CommandObjectTypeFilterDelete (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterDelete (interpreter, - eFormatCategoryItemFilter | eFormatCategoryItemRegexFilter, - "type filter delete", - "Delete an existing filter for a type.") - { - } + CommandObjectTypeFilterDelete(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterDelete( + interpreter, + eFormatCategoryItemFilter | eFormatCategoryItemRegexFilter, + "type filter delete", "Delete an existing filter for a type.") {} - ~CommandObjectTypeFilterDelete() override = default; + ~CommandObjectTypeFilterDelete() override = default; }; #ifndef LLDB_DISABLE_PYTHON @@ -2717,18 +2327,16 @@ public: // CommandObjectTypeSynthDelete //------------------------------------------------------------------------- -class CommandObjectTypeSynthDelete : public CommandObjectTypeFormatterDelete -{ +class CommandObjectTypeSynthDelete : public CommandObjectTypeFormatterDelete { public: - CommandObjectTypeSynthDelete (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterDelete (interpreter, - eFormatCategoryItemSynth | eFormatCategoryItemRegexSynth, - "type synthetic delete", - "Delete an existing synthetic provider for a type.") - { - } - - ~CommandObjectTypeSynthDelete() override = default; + CommandObjectTypeSynthDelete(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterDelete( + interpreter, + eFormatCategoryItemSynth | eFormatCategoryItemRegexSynth, + "type synthetic delete", + "Delete an existing synthetic provider for a type.") {} + + ~CommandObjectTypeSynthDelete() override = default; }; #endif // LLDB_DISABLE_PYTHON @@ -2737,16 +2345,13 @@ public: // CommandObjectTypeFilterClear //------------------------------------------------------------------------- -class CommandObjectTypeFilterClear : public CommandObjectTypeFormatterClear -{ +class CommandObjectTypeFilterClear : public CommandObjectTypeFormatterClear { public: - CommandObjectTypeFilterClear (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterClear (interpreter, - eFormatCategoryItemFilter | eFormatCategoryItemRegexFilter, - "type filter clear", - "Delete all existing filter.") - { - } + CommandObjectTypeFilterClear(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterClear( + interpreter, + eFormatCategoryItemFilter | eFormatCategoryItemRegexFilter, + "type filter clear", "Delete all existing filter.") {} }; #ifndef LLDB_DISABLE_PYTHON @@ -2754,190 +2359,173 @@ public: // CommandObjectTypeSynthClear //------------------------------------------------------------------------- -class CommandObjectTypeSynthClear : public CommandObjectTypeFormatterClear -{ +class CommandObjectTypeSynthClear : public CommandObjectTypeFormatterClear { public: - CommandObjectTypeSynthClear (CommandInterpreter &interpreter) : - CommandObjectTypeFormatterClear (interpreter, - eFormatCategoryItemSynth | eFormatCategoryItemRegexSynth, - "type synthetic clear", - "Delete all existing synthetic providers.") - { - } + CommandObjectTypeSynthClear(CommandInterpreter &interpreter) + : CommandObjectTypeFormatterClear( + interpreter, + eFormatCategoryItemSynth | eFormatCategoryItemRegexSynth, + "type synthetic clear", + "Delete all existing synthetic providers.") {} }; -bool -CommandObjectTypeSynthAdd::Execute_HandwritePython (Args& command, CommandReturnObject &result) -{ - SynthAddOptions *options = new SynthAddOptions ( m_options.m_skip_pointers, - m_options.m_skip_references, - m_options.m_cascade, - m_options.m_regex, - m_options.m_category); - - const size_t argc = command.GetArgumentCount(); - - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - if (typeA && *typeA) - options->m_target_types << typeA; - else - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - m_interpreter.GetPythonCommandsFromIOHandler (" ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - options); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); +bool CommandObjectTypeSynthAdd::Execute_HandwritePython( + Args &command, CommandReturnObject &result) { + SynthAddOptions *options = new SynthAddOptions( + m_options.m_skip_pointers, m_options.m_skip_references, + m_options.m_cascade, m_options.m_regex, m_options.m_category); + + const size_t argc = command.GetArgumentCount(); + + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + if (typeA && *typeA) + options->m_target_types << typeA; + else { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + + m_interpreter.GetPythonCommandsFromIOHandler( + " ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + options); // Baton for the "io_handler" that will be passed back into our + // IOHandlerDelegate functions + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); } -bool -CommandObjectTypeSynthAdd::Execute_PythonClass (Args& command, CommandReturnObject &result) -{ - const size_t argc = command.GetArgumentCount(); - - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes one or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (m_options.m_class_name.empty() && !m_options.m_input_python) - { - result.AppendErrorWithFormat ("%s needs either a Python class name or -P to directly input Python code.\n", m_cmd_name.c_str()); +bool CommandObjectTypeSynthAdd::Execute_PythonClass( + Args &command, CommandReturnObject &result) { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1) { + result.AppendErrorWithFormat("%s takes one or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_options.m_class_name.empty() && !m_options.m_input_python) { + result.AppendErrorWithFormat("%s needs either a Python class name or -P to " + "directly input Python code.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + SyntheticChildrenSP entry; + + ScriptedSyntheticChildren *impl = new ScriptedSyntheticChildren( + SyntheticChildren::Flags() + .SetCascades(m_options.m_cascade) + .SetSkipPointers(m_options.m_skip_pointers) + .SetSkipReferences(m_options.m_skip_references), + m_options.m_class_name.c_str()); + + entry.reset(impl); + + ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); + + if (interpreter && + !interpreter->CheckObjectExists(impl->GetPythonClassName())) + result.AppendWarning("The provided class does not exist - please define it " + "before attempting to use this synthetic provider"); + + // now I have a valid provider, let's add it to every type + + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory( + ConstString(m_options.m_category.c_str()), category); + + Error error; + + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); + if (typeCS) { + if (!AddSynth(typeCS, entry, + m_options.m_regex ? eRegexSynth : eRegularSynth, + m_options.m_category, &error)) { + result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); return false; + } + } else { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; } - - SyntheticChildrenSP entry; - - ScriptedSyntheticChildren* impl = new ScriptedSyntheticChildren(SyntheticChildren::Flags(). - SetCascades(m_options.m_cascade). - SetSkipPointers(m_options.m_skip_pointers). - SetSkipReferences(m_options.m_skip_references), - m_options.m_class_name.c_str()); - - entry.reset(impl); - - ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter(); - - if (interpreter && !interpreter->CheckObjectExists(impl->GetPythonClassName())) - result.AppendWarning("The provided class does not exist - please define it before attempting to use this synthetic provider"); - - // now I have a valid provider, let's add it to every type - - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(m_options.m_category.c_str()), category); - - Error error; - - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - if (typeCS) - { - if (!AddSynth(typeCS, - entry, - m_options.m_regex ? eRegexSynth : eRegularSynth, - m_options.m_category, - &error)) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); + } + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); } - -CommandObjectTypeSynthAdd::CommandObjectTypeSynthAdd (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type synthetic add", - "Add a new synthetic provider for a type.", - nullptr), - IOHandlerDelegateMultiline ("DONE"), - m_options() -{ - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); + +CommandObjectTypeSynthAdd::CommandObjectTypeSynthAdd( + CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type synthetic add", + "Add a new synthetic provider for a type.", nullptr), + IOHandlerDelegateMultiline("DONE"), m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); } -bool -CommandObjectTypeSynthAdd::AddSynth(ConstString type_name, - SyntheticChildrenSP entry, - SynthFormatType type, - std::string category_name, - Error* error) -{ - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), category); - - if (type == eRegularSynth) - { - if (FixArrayTypeNameWithRegex (type_name)) - type = eRegexSynth; - } - - if (category->AnyMatches(type_name, - eFormatCategoryItemFilter | eFormatCategoryItemRegexFilter, - false)) - { - if (error) - error->SetErrorStringWithFormat("cannot add synthetic for type %s when filter is defined in same category!", type_name.AsCString()); - return false; - } - - if (type == eRegexSynth) - { - RegularExpressionSP typeRX(new RegularExpression()); - if (!typeRX->Compile(type_name.GetCString())) - { - if (error) - error->SetErrorString("regex format error (maybe this is not really a regex?)"); - return false; - } - - category->GetRegexTypeSyntheticsContainer()->Delete(type_name); - category->GetRegexTypeSyntheticsContainer()->Add(typeRX, entry); - - return true; - } - else - { - category->GetTypeSyntheticsContainer()->Add(type_name, entry); - return true; +bool CommandObjectTypeSynthAdd::AddSynth(ConstString type_name, + SyntheticChildrenSP entry, + SynthFormatType type, + std::string category_name, + Error *error) { + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), + category); + + if (type == eRegularSynth) { + if (FixArrayTypeNameWithRegex(type_name)) + type = eRegexSynth; + } + + if (category->AnyMatches(type_name, eFormatCategoryItemFilter | + eFormatCategoryItemRegexFilter, + false)) { + if (error) + error->SetErrorStringWithFormat("cannot add synthetic for type %s when " + "filter is defined in same category!", + type_name.AsCString()); + return false; + } + + if (type == eRegexSynth) { + RegularExpressionSP typeRX(new RegularExpression()); + if (!typeRX->Compile(type_name.GetCString())) { + if (error) + error->SetErrorString( + "regex format error (maybe this is not really a regex?)"); + return false; } + + category->GetRegexTypeSyntheticsContainer()->Delete(type_name); + category->GetRegexTypeSyntheticsContainer()->Add(typeRX, entry); + + return true; + } else { + category->GetTypeSyntheticsContainer()->Add(type_name, entry); + return true; + } } -OptionDefinition -CommandObjectTypeSynthAdd::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectTypeSynthAdd::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, cascade through typedef chains."}, {LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects."}, {LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't use this format for references-to-type objects."}, @@ -2946,182 +2534,154 @@ CommandObjectTypeSynthAdd::CommandOptions::g_option_table[] = {LLDB_OPT_SET_3, false, "input-python", 'P', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Type Python code to generate a class that provides synthetic children."}, {LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Type names are actually regular expressions."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; #endif // LLDB_DISABLE_PYTHON -class CommandObjectTypeFilterAdd : public CommandObjectParsed -{ +class CommandObjectTypeFilterAdd : public CommandObjectParsed { private: - class CommandOptions : public Options - { - typedef std::vector option_vector; + class CommandOptions : public Options { + typedef std::vector option_vector; + + public: + CommandOptions() : Options() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + bool success; + + switch (short_option) { + case 'C': + m_cascade = Args::StringToBoolean(option_arg, true, &success); + if (!success) + error.SetErrorStringWithFormat("invalid value for cascade: %s", + option_arg); + break; + case 'c': + m_expr_paths.push_back(option_arg); + has_child_list = true; + break; + case 'p': + m_skip_pointers = true; + break; + case 'r': + m_skip_references = true; + break; + case 'w': + m_category = std::string(option_arg); + break; + case 'x': + m_regex = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; + } + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_cascade = true; + m_skip_pointers = false; + m_skip_references = false; + m_category = "default"; + m_expr_paths.clear(); + has_child_list = false; + m_regex = false; + } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + + // Instance variables to hold the values for command options. - public: - CommandOptions() : - Options() - { - } + bool m_cascade; + bool m_skip_references; + bool m_skip_pointers; + bool m_input_python; + option_vector m_expr_paths; + std::string m_category; + bool has_child_list; + bool m_regex; - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - bool success; - - switch (short_option) - { - case 'C': - m_cascade = Args::StringToBoolean(option_arg, true, &success); - if (!success) - error.SetErrorStringWithFormat("invalid value for cascade: %s", option_arg); - break; - case 'c': - m_expr_paths.push_back(option_arg); - has_child_list = true; - break; - case 'p': - m_skip_pointers = true; - break; - case 'r': - m_skip_references = true; - break; - case 'w': - m_category = std::string(option_arg); - break; - case 'x': - m_regex = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_cascade = true; - m_skip_pointers = false; - m_skip_references = false; - m_category = "default"; - m_expr_paths.clear(); - has_child_list = false; - m_regex = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - - // Instance variables to hold the values for command options. - - bool m_cascade; - bool m_skip_references; - bool m_skip_pointers; - bool m_input_python; - option_vector m_expr_paths; - std::string m_category; - bool has_child_list; - bool m_regex; - - typedef option_vector::iterator ExpressionPathsIterator; - }; - - CommandOptions m_options; - - Options * - GetOptions () override - { - return &m_options; + typedef option_vector::iterator ExpressionPathsIterator; + }; + + CommandOptions m_options; + + Options *GetOptions() override { return &m_options; } + + enum FilterFormatType { eRegularFilter, eRegexFilter }; + + bool AddFilter(ConstString type_name, TypeFilterImplSP entry, + FilterFormatType type, std::string category_name, + Error *error) { + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory( + ConstString(category_name.c_str()), category); + + if (type == eRegularFilter) { + if (FixArrayTypeNameWithRegex(type_name)) + type = eRegexFilter; } - - enum FilterFormatType - { - eRegularFilter, - eRegexFilter - }; - - bool - AddFilter(ConstString type_name, - TypeFilterImplSP entry, - FilterFormatType type, - std::string category_name, - Error* error) - { - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), category); - - if (type == eRegularFilter) - { - if (FixArrayTypeNameWithRegex (type_name)) - type = eRegexFilter; - } - - if (category->AnyMatches(type_name, - eFormatCategoryItemSynth | eFormatCategoryItemRegexSynth, - false)) - { - if (error) - error->SetErrorStringWithFormat("cannot add filter for type %s when synthetic is defined in same category!", type_name.AsCString()); - return false; - } - - if (type == eRegexFilter) - { - RegularExpressionSP typeRX(new RegularExpression()); - if (!typeRX->Compile(type_name.GetCString())) - { - if (error) - error->SetErrorString("regex format error (maybe this is not really a regex?)"); - return false; - } - - category->GetRegexTypeFiltersContainer()->Delete(type_name); - category->GetRegexTypeFiltersContainer()->Add(typeRX, entry); - - return true; - } - else - { - category->GetTypeFiltersContainer()->Add(type_name, entry); - return true; - } + + if (category->AnyMatches(type_name, eFormatCategoryItemSynth | + eFormatCategoryItemRegexSynth, + false)) { + if (error) + error->SetErrorStringWithFormat("cannot add filter for type %s when " + "synthetic is defined in same " + "category!", + type_name.AsCString()); + return false; + } + + if (type == eRegexFilter) { + RegularExpressionSP typeRX(new RegularExpression()); + if (!typeRX->Compile(type_name.GetCString())) { + if (error) + error->SetErrorString( + "regex format error (maybe this is not really a regex?)"); + return false; + } + + category->GetRegexTypeFiltersContainer()->Delete(type_name); + category->GetRegexTypeFiltersContainer()->Add(typeRX, entry); + + return true; + } else { + category->GetTypeFiltersContainer()->Add(type_name, entry); + return true; } + } public: - CommandObjectTypeFilterAdd (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "type filter add", - "Add a new filter for a type.", - nullptr), - m_options() - { - CommandArgumentEntry type_arg; - CommandArgumentData type_style_arg; - - type_style_arg.arg_type = eArgTypeName; - type_style_arg.arg_repetition = eArgRepeatPlus; - - type_arg.push_back (type_style_arg); - - m_arguments.push_back (type_arg); - - SetHelpLong( -R"( + CommandObjectTypeFilterAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "type filter add", + "Add a new filter for a type.", nullptr), + m_options() { + CommandArgumentEntry type_arg; + CommandArgumentData type_style_arg; + + type_style_arg.arg_type = eArgTypeName; + type_style_arg.arg_repetition = eArgRepeatPlus; + + type_arg.push_back(type_style_arg); + + m_arguments.push_back(type_arg); + + SetHelpLong( + R"( The following examples of 'type filter add' refer to this code snippet for context: class Foo { @@ -3142,94 +2702,90 @@ Adding a simple filter: (lldb) type filter add --child a --child g Foo (lldb) frame variable my_foo -)" "Produces output where only a and g are displayed. Other children of my_foo \ -(b, c, d, e, f, h and i) are available by asking for them explicitly:" R"( +)" + "Produces output where only a and g are displayed. Other children of my_foo \ +(b, c, d, e, f, h and i) are available by asking for them explicitly:" + R"( (lldb) frame variable my_foo.b my_foo.c my_foo.i -)" "The formatting option --raw on frame variable bypasses the filter, showing \ -all children of my_foo as if no filter was defined:" R"( +)" + "The formatting option --raw on frame variable bypasses the filter, showing \ +all children of my_foo as if no filter was defined:" + R"( -(lldb) frame variable my_foo --raw)" - ); - } +(lldb) frame variable my_foo --raw)"); + } - ~CommandObjectTypeFilterAdd() override = default; + ~CommandObjectTypeFilterAdd() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - const size_t argc = command.GetArgumentCount(); - - if (argc < 1) - { - result.AppendErrorWithFormat ("%s takes one or more args.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (m_options.m_expr_paths.empty()) - { - result.AppendErrorWithFormat ("%s needs one or more children.\n", m_cmd_name.c_str()); - result.SetStatus(eReturnStatusFailed); - return false; - } - - TypeFilterImplSP entry(new TypeFilterImpl(SyntheticChildren::Flags().SetCascades(m_options.m_cascade). - SetSkipPointers(m_options.m_skip_pointers). - SetSkipReferences(m_options.m_skip_references))); - - // go through the expression paths - CommandOptions::ExpressionPathsIterator begin, end = m_options.m_expr_paths.end(); - - for (begin = m_options.m_expr_paths.begin(); begin != end; begin++) - entry->AddExpressionPath(*begin); - - - // now I have a valid provider, let's add it to every type - - lldb::TypeCategoryImplSP category; - DataVisualization::Categories::GetCategory(ConstString(m_options.m_category.c_str()), category); - - Error error; - - WarnOnPotentialUnquotedUnsignedType(command, result); - - for (size_t i = 0; i < argc; i++) - { - const char* typeA = command.GetArgumentAtIndex(i); - ConstString typeCS(typeA); - if (typeCS) - { - if (!AddFilter(typeCS, - entry, - m_options.m_regex ? eRegexFilter : eRegularFilter, - m_options.m_category, - &error)) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - else - { - result.AppendError("empty typenames not allowed"); - result.SetStatus(eReturnStatusFailed); - return false; - } - } - - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return result.Succeeded(); + bool DoExecute(Args &command, CommandReturnObject &result) override { + const size_t argc = command.GetArgumentCount(); + + if (argc < 1) { + result.AppendErrorWithFormat("%s takes one or more args.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_options.m_expr_paths.empty()) { + result.AppendErrorWithFormat("%s needs one or more children.\n", + m_cmd_name.c_str()); + result.SetStatus(eReturnStatusFailed); + return false; + } + + TypeFilterImplSP entry(new TypeFilterImpl( + SyntheticChildren::Flags() + .SetCascades(m_options.m_cascade) + .SetSkipPointers(m_options.m_skip_pointers) + .SetSkipReferences(m_options.m_skip_references))); + + // go through the expression paths + CommandOptions::ExpressionPathsIterator begin, + end = m_options.m_expr_paths.end(); + + for (begin = m_options.m_expr_paths.begin(); begin != end; begin++) + entry->AddExpressionPath(*begin); + + // now I have a valid provider, let's add it to every type + + lldb::TypeCategoryImplSP category; + DataVisualization::Categories::GetCategory( + ConstString(m_options.m_category.c_str()), category); + + Error error; + + WarnOnPotentialUnquotedUnsignedType(command, result); + + for (size_t i = 0; i < argc; i++) { + const char *typeA = command.GetArgumentAtIndex(i); + ConstString typeCS(typeA); + if (typeCS) { + if (!AddFilter(typeCS, entry, + m_options.m_regex ? eRegexFilter : eRegularFilter, + m_options.m_category, &error)) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } else { + result.AppendError("empty typenames not allowed"); + result.SetStatus(eReturnStatusFailed); + return false; + } } + + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return result.Succeeded(); + } }; -OptionDefinition -CommandObjectTypeFilterAdd::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectTypeFilterAdd::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_ALL, false, "cascade", 'C', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, cascade through typedef chains."}, {LLDB_OPT_SET_ALL, false, "skip-pointers", 'p', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't use this format for pointers-to-type objects."}, {LLDB_OPT_SET_ALL, false, "skip-references", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Don't use this format for references-to-type objects."}, @@ -3237,484 +2793,466 @@ CommandObjectTypeFilterAdd::CommandOptions::g_option_table[] = {LLDB_OPT_SET_ALL, false, "child", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeExpressionPath, "Include this expression path in the synthetic view."}, {LLDB_OPT_SET_ALL, false, "regex", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Type names are actually regular expressions."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //---------------------------------------------------------------------- // "type lookup" //---------------------------------------------------------------------- -class CommandObjectTypeLookup : public CommandObjectRaw -{ +class CommandObjectTypeLookup : public CommandObjectRaw { protected: - // this function is allowed to do a more aggressive job at guessing languages than the expression parser - // is comfortable with - so leave the original call alone and add one that is specific to type lookup - lldb::LanguageType - GuessLanguage (StackFrame *frame) - { - lldb::LanguageType lang_type = lldb::eLanguageTypeUnknown; - - if (!frame) - return lang_type; - - lang_type = frame->GuessLanguage(); - if (lang_type != lldb::eLanguageTypeUnknown) - return lang_type; - - Symbol *s = frame->GetSymbolContext(eSymbolContextSymbol).symbol; - if (s) - lang_type = s->GetMangled().GuessLanguage(); - - return lang_type; - } - - class CommandOptions : public OptionGroup - { - public: - CommandOptions () : - OptionGroup(), - m_show_help(false), - m_language(eLanguageTypeUnknown) - {} - - ~CommandOptions() override = default; - - uint32_t - GetNumDefinitions () override - { - return 3; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } - - Error - SetOptionValue (uint32_t option_idx, - const char *option_value, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = g_option_table[option_idx].short_option; - - switch (short_option) - { - case 'h': - m_show_help = true; - break; - - case 'l': - m_language = Language::GetLanguageTypeFromString(option_value); - break; - - default: - error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_show_help = false; - m_language = eLanguageTypeUnknown; - } - - // Options table: Required for subclasses of Options. - - static OptionDefinition g_option_table[]; - bool m_show_help; - lldb::LanguageType m_language; - }; - - OptionGroupOptions m_option_group; - CommandOptions m_command_options; - -public: - CommandObjectTypeLookup (CommandInterpreter &interpreter) : - CommandObjectRaw (interpreter, - "type lookup", - "Lookup types and declarations in the current target, following language-specific naming conventions.", - "type lookup ", - eCommandRequiresTarget), - m_option_group(), - m_command_options() - { - m_option_group.Append(&m_command_options); - m_option_group.Finalize(); - } + // this function is allowed to do a more aggressive job at guessing languages + // than the expression parser + // is comfortable with - so leave the original call alone and add one that is + // specific to type lookup + lldb::LanguageType GuessLanguage(StackFrame *frame) { + lldb::LanguageType lang_type = lldb::eLanguageTypeUnknown; - ~CommandObjectTypeLookup() override = default; + if (!frame) + return lang_type; - Options * - GetOptions () override - { - return &m_option_group; + lang_type = frame->GuessLanguage(); + if (lang_type != lldb::eLanguageTypeUnknown) + return lang_type; + + Symbol *s = frame->GetSymbolContext(eSymbolContextSymbol).symbol; + if (s) + lang_type = s->GetMangled().GuessLanguage(); + + return lang_type; + } + + class CommandOptions : public OptionGroup { + public: + CommandOptions() + : OptionGroup(), m_show_help(false), m_language(eLanguageTypeUnknown) {} + + ~CommandOptions() override = default; + + uint32_t GetNumDefinitions() override { return 3; } + + const OptionDefinition *GetDefinitions() override { return g_option_table; } + + Error SetOptionValue(uint32_t option_idx, const char *option_value, + ExecutionContext *execution_context) override { + Error error; + + const int short_option = g_option_table[option_idx].short_option; + + switch (short_option) { + case 'h': + m_show_help = true; + break; + + case 'l': + m_language = Language::GetLanguageTypeFromString(option_value); + break; + + default: + error.SetErrorStringWithFormat("invalid short option character '%c'", + short_option); + break; + } + + return error; } - - const char* - GetHelpLong () override - { - if (m_cmd_help_long.empty()) - { - StreamString stream; - // FIXME: hardcoding languages is not good - lldb::LanguageType languages[] = {eLanguageTypeObjC,eLanguageTypeC_plus_plus}; - - for(const auto lang_type : languages) - { - if (auto language = Language::FindPlugin(lang_type)) - { - if (const char* help = language->GetLanguageSpecificTypeLookupHelp()) - { - stream.Printf("%s\n", help); - } - } - } - - if (stream.GetData()) - m_cmd_help_long.assign(stream.GetString()); - } - return this->CommandObject::GetHelpLong(); + + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_show_help = false; + m_language = eLanguageTypeUnknown; } - - bool - DoExecute (const char *raw_command_line, CommandReturnObject &result) override - { - if (!raw_command_line || !raw_command_line[0]) - { - result.SetError("type lookup cannot be invoked without a type name as argument"); - return false; - } - auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); - m_option_group.NotifyOptionParsingStarting(&exe_ctx); - - const char * name_of_type = nullptr; - - if (raw_command_line[0] == '-') - { - // We have some options and these options MUST end with --. - const char *end_options = nullptr; - const char *s = raw_command_line; - while (s && s[0]) - { - end_options = ::strstr (s, "--"); - if (end_options) - { - end_options += 2; // Get past the "--" - if (::isspace (end_options[0])) - { - name_of_type = end_options; - while (::isspace (*name_of_type)) - ++name_of_type; - break; - } - } - s = end_options; - } - - if (end_options) - { - Args args (llvm::StringRef(raw_command_line, end_options - raw_command_line)); - if (!ParseOptions (args, result)) - return false; - - Error error(m_option_group.NotifyOptionParsingFinished( - &exe_ctx)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } - if (nullptr == name_of_type) - name_of_type = raw_command_line; - - // TargetSP target_sp(GetCommandInterpreter().GetDebugger().GetSelectedTarget()); - // const bool fill_all_in = true; - // ExecutionContext exe_ctx(target_sp.get(), fill_all_in); - ExecutionContextScope *best_scope = exe_ctx.GetBestExecutionContextScope(); - - bool any_found = false; - - std::vector languages; - - bool is_global_search = false; - LanguageType guessed_language = lldb::eLanguageTypeUnknown; - - if ( (is_global_search = (m_command_options.m_language == eLanguageTypeUnknown)) ) - { - // FIXME: hardcoding languages is not good - languages.push_back(Language::FindPlugin(eLanguageTypeObjC)); - languages.push_back(Language::FindPlugin(eLanguageTypeC_plus_plus)); - } - else - { - languages.push_back(Language::FindPlugin(m_command_options.m_language)); - } - - // This is not the most efficient way to do this, but we support very few languages - // so the cost of the sort is going to be dwarfed by the actual lookup anyway - if (StackFrame* frame = m_exe_ctx.GetFramePtr()) - { - guessed_language = GuessLanguage(frame); - if (guessed_language != eLanguageTypeUnknown) - { - std::sort(languages.begin(), - languages.end(), - [guessed_language] (Language* lang1, - Language* lang2) -> bool { - if (!lang1 || !lang2) return false; - LanguageType lt1 = lang1->GetLanguageType(); - LanguageType lt2 = lang2->GetLanguageType(); - if (lt1 == guessed_language) return true; // make the selected frame's language come first - if (lt2 == guessed_language) return false; // make the selected frame's language come first - return (lt1 < lt2); // normal comparison otherwise - }); - } - } - - bool is_first_language = true; - - for (Language* language : languages) - { - if (!language) - continue; - - if (auto scavenger = language->GetTypeScavenger()) - { - Language::TypeScavenger::ResultSet search_results; - if (scavenger->Find(best_scope, name_of_type, search_results) > 0) - { - for (const auto& search_result : search_results) - { - if (search_result && search_result->IsValid()) - { - any_found = true; - search_result->DumpToStream(result.GetOutputStream(), this->m_command_options.m_show_help); - } - } - } - } - // this is "type lookup SomeName" and we did find a match, so get out - if (any_found && is_global_search) - break; - else if (is_first_language && is_global_search && guessed_language != lldb::eLanguageTypeUnknown) - { - is_first_language = false; - result.GetOutputStream().Printf("no type was found in the current language %s matching '%s'; performing a global search across all languages\n", - Language::GetNameForLanguageType(guessed_language), - name_of_type); - } - } - - if (!any_found) - result.AppendMessageWithFormat("no type was found matching '%s'\n", name_of_type); - - result.SetStatus (any_found ? lldb::eReturnStatusSuccessFinishResult : lldb::eReturnStatusSuccessFinishNoResult); - return true; + // Options table: Required for subclasses of Options. + + static OptionDefinition g_option_table[]; + bool m_show_help; + lldb::LanguageType m_language; + }; + + OptionGroupOptions m_option_group; + CommandOptions m_command_options; + +public: + CommandObjectTypeLookup(CommandInterpreter &interpreter) + : CommandObjectRaw(interpreter, "type lookup", + "Lookup types and declarations in the current target, " + "following language-specific naming conventions.", + "type lookup ", + eCommandRequiresTarget), + m_option_group(), m_command_options() { + m_option_group.Append(&m_command_options); + m_option_group.Finalize(); + } + + ~CommandObjectTypeLookup() override = default; + + Options *GetOptions() override { return &m_option_group; } + + const char *GetHelpLong() override { + if (m_cmd_help_long.empty()) { + StreamString stream; + // FIXME: hardcoding languages is not good + lldb::LanguageType languages[] = {eLanguageTypeObjC, + eLanguageTypeC_plus_plus}; + + for (const auto lang_type : languages) { + if (auto language = Language::FindPlugin(lang_type)) { + if (const char *help = + language->GetLanguageSpecificTypeLookupHelp()) { + stream.Printf("%s\n", help); + } + } + } + + if (stream.GetData()) + m_cmd_help_long.assign(stream.GetString()); + } + return this->CommandObject::GetHelpLong(); + } + + bool DoExecute(const char *raw_command_line, + CommandReturnObject &result) override { + if (!raw_command_line || !raw_command_line[0]) { + result.SetError( + "type lookup cannot be invoked without a type name as argument"); + return false; + } + + auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); + m_option_group.NotifyOptionParsingStarting(&exe_ctx); + + const char *name_of_type = nullptr; + + if (raw_command_line[0] == '-') { + // We have some options and these options MUST end with --. + const char *end_options = nullptr; + const char *s = raw_command_line; + while (s && s[0]) { + end_options = ::strstr(s, "--"); + if (end_options) { + end_options += 2; // Get past the "--" + if (::isspace(end_options[0])) { + name_of_type = end_options; + while (::isspace(*name_of_type)) + ++name_of_type; + break; + } + } + s = end_options; + } + + if (end_options) { + Args args( + llvm::StringRef(raw_command_line, end_options - raw_command_line)); + if (!ParseOptions(args, result)) + return false; + + Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; + } + } + } + if (nullptr == name_of_type) + name_of_type = raw_command_line; + + // TargetSP + // target_sp(GetCommandInterpreter().GetDebugger().GetSelectedTarget()); + // const bool fill_all_in = true; + // ExecutionContext exe_ctx(target_sp.get(), fill_all_in); + ExecutionContextScope *best_scope = exe_ctx.GetBestExecutionContextScope(); + + bool any_found = false; + + std::vector languages; + + bool is_global_search = false; + LanguageType guessed_language = lldb::eLanguageTypeUnknown; + + if ((is_global_search = + (m_command_options.m_language == eLanguageTypeUnknown))) { + // FIXME: hardcoding languages is not good + languages.push_back(Language::FindPlugin(eLanguageTypeObjC)); + languages.push_back(Language::FindPlugin(eLanguageTypeC_plus_plus)); + } else { + languages.push_back(Language::FindPlugin(m_command_options.m_language)); + } + + // This is not the most efficient way to do this, but we support very few + // languages + // so the cost of the sort is going to be dwarfed by the actual lookup + // anyway + if (StackFrame *frame = m_exe_ctx.GetFramePtr()) { + guessed_language = GuessLanguage(frame); + if (guessed_language != eLanguageTypeUnknown) { + std::sort( + languages.begin(), languages.end(), + [guessed_language](Language *lang1, Language *lang2) -> bool { + if (!lang1 || !lang2) + return false; + LanguageType lt1 = lang1->GetLanguageType(); + LanguageType lt2 = lang2->GetLanguageType(); + if (lt1 == guessed_language) + return true; // make the selected frame's language come first + if (lt2 == guessed_language) + return false; // make the selected frame's language come first + return (lt1 < lt2); // normal comparison otherwise + }); + } } + + bool is_first_language = true; + + for (Language *language : languages) { + if (!language) + continue; + + if (auto scavenger = language->GetTypeScavenger()) { + Language::TypeScavenger::ResultSet search_results; + if (scavenger->Find(best_scope, name_of_type, search_results) > 0) { + for (const auto &search_result : search_results) { + if (search_result && search_result->IsValid()) { + any_found = true; + search_result->DumpToStream(result.GetOutputStream(), + this->m_command_options.m_show_help); + } + } + } + } + // this is "type lookup SomeName" and we did find a match, so get out + if (any_found && is_global_search) + break; + else if (is_first_language && is_global_search && + guessed_language != lldb::eLanguageTypeUnknown) { + is_first_language = false; + result.GetOutputStream().Printf( + "no type was found in the current language %s matching '%s'; " + "performing a global search across all languages\n", + Language::GetNameForLanguageType(guessed_language), name_of_type); + } + } + + if (!any_found) + result.AppendMessageWithFormat("no type was found matching '%s'\n", + name_of_type); + + result.SetStatus(any_found ? lldb::eReturnStatusSuccessFinishResult + : lldb::eReturnStatusSuccessFinishNoResult); + return true; + } }; -OptionDefinition -CommandObjectTypeLookup::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectTypeLookup::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "show-help", 'h', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display available help for types"}, {LLDB_OPT_SET_ALL, false, "language", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLanguage, "Which language's types should the search scope be"}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; template -class CommandObjectFormatterInfo : public CommandObjectRaw -{ +class CommandObjectFormatterInfo : public CommandObjectRaw { public: - typedef std::function DiscoveryFunction; - CommandObjectFormatterInfo (CommandInterpreter &interpreter, - const char* formatter_name, - DiscoveryFunction discovery_func) : - CommandObjectRaw(interpreter, - nullptr, - nullptr, - nullptr, - eCommandRequiresFrame), - m_formatter_name(formatter_name ? formatter_name : ""), - m_discovery_function(discovery_func) - { - StreamString name; - name.Printf("type %s info", formatter_name); - SetCommandName(name.GetData()); - StreamString help; - help.Printf("This command evaluates the provided expression and shows which %s is applied to the resulting value (if any).", formatter_name); - SetHelp(help.GetData()); - StreamString syntax; - syntax.Printf("type %s info ", formatter_name); - SetSyntax(syntax.GetData()); - } - - ~CommandObjectFormatterInfo() override = default; + typedef std::function + DiscoveryFunction; + CommandObjectFormatterInfo(CommandInterpreter &interpreter, + const char *formatter_name, + DiscoveryFunction discovery_func) + : CommandObjectRaw(interpreter, nullptr, nullptr, nullptr, + eCommandRequiresFrame), + m_formatter_name(formatter_name ? formatter_name : ""), + m_discovery_function(discovery_func) { + StreamString name; + name.Printf("type %s info", formatter_name); + SetCommandName(name.GetData()); + StreamString help; + help.Printf("This command evaluates the provided expression and shows " + "which %s is applied to the resulting value (if any).", + formatter_name); + SetHelp(help.GetData()); + StreamString syntax; + syntax.Printf("type %s info ", formatter_name); + SetSyntax(syntax.GetData()); + } + + ~CommandObjectFormatterInfo() override = default; protected: - bool - DoExecute (const char *command, CommandReturnObject &result) override - { - TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); - Thread *thread = GetDefaultThread(); - if (!thread) - { - result.AppendError("no default thread"); - result.SetStatus(lldb::eReturnStatusFailed); - return false; - } - - StackFrameSP frame_sp = thread->GetSelectedFrame(); - ValueObjectSP result_valobj_sp; - EvaluateExpressionOptions options; - lldb::ExpressionResults expr_result = target_sp->EvaluateExpression(command, frame_sp.get(), result_valobj_sp, options); - if (expr_result == eExpressionCompleted && result_valobj_sp) - { - result_valobj_sp = result_valobj_sp->GetQualifiedRepresentationIfAvailable(target_sp->GetPreferDynamicValue(), target_sp->GetEnableSyntheticValue()); - typename FormatterType::SharedPointer formatter_sp = m_discovery_function(*result_valobj_sp); - if (formatter_sp) - { - std::string description(formatter_sp->GetDescription()); - result.AppendMessageWithFormat("%s applied to (%s) %s is: %s\n", - m_formatter_name.c_str(), - result_valobj_sp->GetDisplayTypeName().AsCString(""), - command, - description.c_str()); - result.SetStatus(lldb::eReturnStatusSuccessFinishResult); - } - else - { - result.AppendMessageWithFormat("no %s applies to (%s) %s\n", - m_formatter_name.c_str(), - result_valobj_sp->GetDisplayTypeName().AsCString(""), - command); - result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); - } - return true; - } - else - { - result.AppendError("failed to evaluate expression"); - result.SetStatus(lldb::eReturnStatusFailed); - return false; - } - } + bool DoExecute(const char *command, CommandReturnObject &result) override { + TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); + Thread *thread = GetDefaultThread(); + if (!thread) { + result.AppendError("no default thread"); + result.SetStatus(lldb::eReturnStatusFailed); + return false; + } + + StackFrameSP frame_sp = thread->GetSelectedFrame(); + ValueObjectSP result_valobj_sp; + EvaluateExpressionOptions options; + lldb::ExpressionResults expr_result = target_sp->EvaluateExpression( + command, frame_sp.get(), result_valobj_sp, options); + if (expr_result == eExpressionCompleted && result_valobj_sp) { + result_valobj_sp = + result_valobj_sp->GetQualifiedRepresentationIfAvailable( + target_sp->GetPreferDynamicValue(), + target_sp->GetEnableSyntheticValue()); + typename FormatterType::SharedPointer formatter_sp = + m_discovery_function(*result_valobj_sp); + if (formatter_sp) { + std::string description(formatter_sp->GetDescription()); + result.AppendMessageWithFormat( + "%s applied to (%s) %s is: %s\n", m_formatter_name.c_str(), + result_valobj_sp->GetDisplayTypeName().AsCString(""), + command, description.c_str()); + result.SetStatus(lldb::eReturnStatusSuccessFinishResult); + } else { + result.AppendMessageWithFormat( + "no %s applies to (%s) %s\n", m_formatter_name.c_str(), + result_valobj_sp->GetDisplayTypeName().AsCString(""), + command); + result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); + } + return true; + } else { + result.AppendError("failed to evaluate expression"); + result.SetStatus(lldb::eReturnStatusFailed); + return false; + } + } private: - std::string m_formatter_name; - DiscoveryFunction m_discovery_function; + std::string m_formatter_name; + DiscoveryFunction m_discovery_function; }; -class CommandObjectTypeFormat : public CommandObjectMultiword -{ +class CommandObjectTypeFormat : public CommandObjectMultiword { public: - CommandObjectTypeFormat(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type format", "Commands for customizing value display formats.", - "type format [] ") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTypeFormatAdd (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectTypeFormatClear (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTypeFormatDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTypeFormatList (interpreter))); - LoadSubCommand ("info", CommandObjectSP (new CommandObjectFormatterInfo(interpreter, - "format", - [](ValueObject& valobj) -> TypeFormatImpl::SharedPointer { - return valobj.GetValueFormat(); - }))); - } - - ~CommandObjectTypeFormat() override = default; + CommandObjectTypeFormat(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "type format", + "Commands for customizing value display formats.", + "type format [] ") { + LoadSubCommand( + "add", CommandObjectSP(new CommandObjectTypeFormatAdd(interpreter))); + LoadSubCommand("clear", CommandObjectSP( + new CommandObjectTypeFormatClear(interpreter))); + LoadSubCommand("delete", CommandObjectSP(new CommandObjectTypeFormatDelete( + interpreter))); + LoadSubCommand( + "list", CommandObjectSP(new CommandObjectTypeFormatList(interpreter))); + LoadSubCommand( + "info", CommandObjectSP(new CommandObjectFormatterInfo( + interpreter, "format", + [](ValueObject &valobj) -> TypeFormatImpl::SharedPointer { + return valobj.GetValueFormat(); + }))); + } + + ~CommandObjectTypeFormat() override = default; }; #ifndef LLDB_DISABLE_PYTHON -class CommandObjectTypeSynth : public CommandObjectMultiword -{ +class CommandObjectTypeSynth : public CommandObjectMultiword { public: - CommandObjectTypeSynth(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type synthetic", - "Commands for operating on synthetic type representations.", - "type synthetic [] ") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTypeSynthAdd (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectTypeSynthClear (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTypeSynthDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTypeSynthList (interpreter))); - LoadSubCommand ("info", CommandObjectSP (new CommandObjectFormatterInfo(interpreter, - "synthetic", - [](ValueObject& valobj) -> SyntheticChildren::SharedPointer { - return valobj.GetSyntheticChildren(); - }))); - } - - ~CommandObjectTypeSynth() override = default; + CommandObjectTypeSynth(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "type synthetic", + "Commands for operating on synthetic type representations.", + "type synthetic [] ") { + LoadSubCommand("add", + CommandObjectSP(new CommandObjectTypeSynthAdd(interpreter))); + LoadSubCommand( + "clear", CommandObjectSP(new CommandObjectTypeSynthClear(interpreter))); + LoadSubCommand("delete", CommandObjectSP(new CommandObjectTypeSynthDelete( + interpreter))); + LoadSubCommand( + "list", CommandObjectSP(new CommandObjectTypeSynthList(interpreter))); + LoadSubCommand( + "info", + CommandObjectSP(new CommandObjectFormatterInfo( + interpreter, "synthetic", + [](ValueObject &valobj) -> SyntheticChildren::SharedPointer { + return valobj.GetSyntheticChildren(); + }))); + } + + ~CommandObjectTypeSynth() override = default; }; #endif // LLDB_DISABLE_PYTHON -class CommandObjectTypeFilter : public CommandObjectMultiword -{ +class CommandObjectTypeFilter : public CommandObjectMultiword { public: - CommandObjectTypeFilter(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type filter", "Commands for operating on type filters.", - "type synthetic [] ") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTypeFilterAdd (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectTypeFilterClear (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTypeFilterDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTypeFilterList (interpreter))); - } - - ~CommandObjectTypeFilter() override = default; + CommandObjectTypeFilter(CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "type filter", + "Commands for operating on type filters.", + "type synthetic [] ") { + LoadSubCommand( + "add", CommandObjectSP(new CommandObjectTypeFilterAdd(interpreter))); + LoadSubCommand("clear", CommandObjectSP( + new CommandObjectTypeFilterClear(interpreter))); + LoadSubCommand("delete", CommandObjectSP(new CommandObjectTypeFilterDelete( + interpreter))); + LoadSubCommand( + "list", CommandObjectSP(new CommandObjectTypeFilterList(interpreter))); + } + + ~CommandObjectTypeFilter() override = default; }; -class CommandObjectTypeCategory : public CommandObjectMultiword -{ +class CommandObjectTypeCategory : public CommandObjectMultiword { public: - CommandObjectTypeCategory(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type category", "Commands for operating on type categories.", - "type category [] ") - { - LoadSubCommand ("define", CommandObjectSP (new CommandObjectTypeCategoryDefine (interpreter))); - LoadSubCommand ("enable", CommandObjectSP (new CommandObjectTypeCategoryEnable (interpreter))); - LoadSubCommand ("disable", CommandObjectSP (new CommandObjectTypeCategoryDisable (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTypeCategoryDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTypeCategoryList (interpreter))); - } - - ~CommandObjectTypeCategory() override = default; + CommandObjectTypeCategory(CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "type category", + "Commands for operating on type categories.", + "type category [] ") { + LoadSubCommand( + "define", + CommandObjectSP(new CommandObjectTypeCategoryDefine(interpreter))); + LoadSubCommand( + "enable", + CommandObjectSP(new CommandObjectTypeCategoryEnable(interpreter))); + LoadSubCommand( + "disable", + CommandObjectSP(new CommandObjectTypeCategoryDisable(interpreter))); + LoadSubCommand( + "delete", + CommandObjectSP(new CommandObjectTypeCategoryDelete(interpreter))); + LoadSubCommand("list", CommandObjectSP( + new CommandObjectTypeCategoryList(interpreter))); + } + + ~CommandObjectTypeCategory() override = default; }; -class CommandObjectTypeSummary : public CommandObjectMultiword -{ +class CommandObjectTypeSummary : public CommandObjectMultiword { public: - CommandObjectTypeSummary(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type summary", "Commands for editing variable summary display options.", - "type summary [] ") - { - LoadSubCommand ("add", CommandObjectSP (new CommandObjectTypeSummaryAdd (interpreter))); - LoadSubCommand ("clear", CommandObjectSP (new CommandObjectTypeSummaryClear (interpreter))); - LoadSubCommand ("delete", CommandObjectSP (new CommandObjectTypeSummaryDelete (interpreter))); - LoadSubCommand ("list", CommandObjectSP (new CommandObjectTypeSummaryList (interpreter))); - LoadSubCommand ("info", CommandObjectSP (new CommandObjectFormatterInfo(interpreter, - "summary", - [](ValueObject& valobj) -> TypeSummaryImpl::SharedPointer { - return valobj.GetSummaryFormat(); - }))); - } - - ~CommandObjectTypeSummary() override = default; + CommandObjectTypeSummary(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "type summary", + "Commands for editing variable summary display options.", + "type summary [] ") { + LoadSubCommand( + "add", CommandObjectSP(new CommandObjectTypeSummaryAdd(interpreter))); + LoadSubCommand("clear", CommandObjectSP(new CommandObjectTypeSummaryClear( + interpreter))); + LoadSubCommand("delete", CommandObjectSP(new CommandObjectTypeSummaryDelete( + interpreter))); + LoadSubCommand( + "list", CommandObjectSP(new CommandObjectTypeSummaryList(interpreter))); + LoadSubCommand( + "info", CommandObjectSP(new CommandObjectFormatterInfo( + interpreter, "summary", + [](ValueObject &valobj) -> TypeSummaryImpl::SharedPointer { + return valobj.GetSummaryFormat(); + }))); + } + + ~CommandObjectTypeSummary() override = default; }; //------------------------------------------------------------------------- @@ -3722,17 +3260,23 @@ public: //------------------------------------------------------------------------- CommandObjectType::CommandObjectType(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "type", "Commands for operating on the type system.", - "type []") -{ - LoadSubCommand ("category", CommandObjectSP (new CommandObjectTypeCategory (interpreter))); - LoadSubCommand ("filter", CommandObjectSP (new CommandObjectTypeFilter (interpreter))); - LoadSubCommand ("format", CommandObjectSP (new CommandObjectTypeFormat (interpreter))); - LoadSubCommand ("summary", CommandObjectSP (new CommandObjectTypeSummary (interpreter))); + : CommandObjectMultiword(interpreter, "type", + "Commands for operating on the type system.", + "type []") { + LoadSubCommand("category", + CommandObjectSP(new CommandObjectTypeCategory(interpreter))); + LoadSubCommand("filter", + CommandObjectSP(new CommandObjectTypeFilter(interpreter))); + LoadSubCommand("format", + CommandObjectSP(new CommandObjectTypeFormat(interpreter))); + LoadSubCommand("summary", + CommandObjectSP(new CommandObjectTypeSummary(interpreter))); #ifndef LLDB_DISABLE_PYTHON - LoadSubCommand ("synthetic", CommandObjectSP (new CommandObjectTypeSynth (interpreter))); + LoadSubCommand("synthetic", + CommandObjectSP(new CommandObjectTypeSynth(interpreter))); #endif // LLDB_DISABLE_PYTHON - LoadSubCommand ("lookup", CommandObjectSP (new CommandObjectTypeLookup (interpreter))); + LoadSubCommand("lookup", + CommandObjectSP(new CommandObjectTypeLookup(interpreter))); } CommandObjectType::~CommandObjectType() = default; diff --git a/lldb/source/Commands/CommandObjectType.h b/lldb/source/Commands/CommandObjectType.h index 54f4a33c6f6..f2f9ce7c1b6 100644 --- a/lldb/source/Commands/CommandObjectType.h +++ b/lldb/source/Commands/CommandObjectType.h @@ -16,18 +16,17 @@ // Other libraries and framework includes // Project includes -#include "lldb/lldb-types.h" #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/Options.h" +#include "lldb/lldb-types.h" namespace lldb_private { -class CommandObjectType : public CommandObjectMultiword -{ +class CommandObjectType : public CommandObjectMultiword { public: - CommandObjectType (CommandInterpreter &interpreter); + CommandObjectType(CommandInterpreter &interpreter); - ~CommandObjectType() override; + ~CommandObjectType() override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectVersion.cpp b/lldb/source/Commands/CommandObjectVersion.cpp index 06962f8648a..8b1f25bfc52 100644 --- a/lldb/source/Commands/CommandObjectVersion.cpp +++ b/lldb/source/Commands/CommandObjectVersion.cpp @@ -13,9 +13,9 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/lldb-private.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; @@ -25,27 +25,18 @@ using namespace lldb_private; //------------------------------------------------------------------------- CommandObjectVersion::CommandObjectVersion(CommandInterpreter &interpreter) - : CommandObjectParsed(interpreter, "version", "Show the LLDB debugger version.", "version") -{ -} - -CommandObjectVersion::~CommandObjectVersion () -{ + : CommandObjectParsed(interpreter, "version", + "Show the LLDB debugger version.", "version") {} + +CommandObjectVersion::~CommandObjectVersion() {} + +bool CommandObjectVersion::DoExecute(Args &args, CommandReturnObject &result) { + if (args.GetArgumentCount() == 0) { + result.AppendMessageWithFormat("%s\n", lldb_private::GetVersion()); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendError("the version command takes no arguments."); + result.SetStatus(eReturnStatusFailed); + } + return true; } - -bool -CommandObjectVersion::DoExecute (Args& args, CommandReturnObject &result) -{ - if (args.GetArgumentCount() == 0) - { - result.AppendMessageWithFormat ("%s\n", lldb_private::GetVersion()); - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendError("the version command takes no arguments."); - result.SetStatus (eReturnStatusFailed); - } - return true; -} - diff --git a/lldb/source/Commands/CommandObjectVersion.h b/lldb/source/Commands/CommandObjectVersion.h index 30ba9d1235d..5f661cc341c 100644 --- a/lldb/source/Commands/CommandObjectVersion.h +++ b/lldb/source/Commands/CommandObjectVersion.h @@ -22,18 +22,14 @@ namespace lldb_private { // CommandObjectVersion //------------------------------------------------------------------------- -class CommandObjectVersion : public CommandObjectParsed -{ +class CommandObjectVersion : public CommandObjectParsed { public: + CommandObjectVersion(CommandInterpreter &interpreter); - CommandObjectVersion (CommandInterpreter &interpreter); - - ~CommandObjectVersion() override; + ~CommandObjectVersion() override; protected: - bool - DoExecute(Args& args, - CommandReturnObject &result) override; + bool DoExecute(Args &args, CommandReturnObject &result) override; }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectWatchpoint.cpp b/lldb/source/Commands/CommandObjectWatchpoint.cpp index b4c5639352a..7ff4cce7457 100644 --- a/lldb/source/Commands/CommandObjectWatchpoint.cpp +++ b/lldb/source/Commands/CommandObjectWatchpoint.cpp @@ -24,9 +24,9 @@ #include "lldb/Core/ValueObject.h" #include "lldb/Core/ValueObjectVariable.h" #include "lldb/Host/StringConvert.h" +#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Symbol/Variable.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/StackFrame.h" @@ -35,126 +35,118 @@ using namespace lldb; using namespace lldb_private; -static void -AddWatchpointDescription(Stream *s, Watchpoint *wp, lldb::DescriptionLevel level) -{ - s->IndentMore(); - wp->GetDescription(s, level); - s->IndentLess(); - s->EOL(); +static void AddWatchpointDescription(Stream *s, Watchpoint *wp, + lldb::DescriptionLevel level) { + s->IndentMore(); + wp->GetDescription(s, level); + s->IndentLess(); + s->EOL(); } -static bool -CheckTargetForWatchpointOperations(Target *target, CommandReturnObject &result) -{ - if (target == nullptr) - { - result.AppendError ("Invalid target. No existing target or watchpoints."); - result.SetStatus (eReturnStatusFailed); - return false; - } - bool process_is_valid = target->GetProcessSP() && target->GetProcessSP()->IsAlive(); - if (!process_is_valid) - { - result.AppendError ("Thre's no process or it is not alive."); - result.SetStatus (eReturnStatusFailed); - return false; - } - // Target passes our checks, return true. - return true; +static bool CheckTargetForWatchpointOperations(Target *target, + CommandReturnObject &result) { + if (target == nullptr) { + result.AppendError("Invalid target. No existing target or watchpoints."); + result.SetStatus(eReturnStatusFailed); + return false; + } + bool process_is_valid = + target->GetProcessSP() && target->GetProcessSP()->IsAlive(); + if (!process_is_valid) { + result.AppendError("Thre's no process or it is not alive."); + result.SetStatus(eReturnStatusFailed); + return false; + } + // Target passes our checks, return true. + return true; } // Equivalent class: {"-", "to", "To", "TO"} of range specifier array. -static const char* RSA[4] = { "-", "to", "To", "TO" }; +static const char *RSA[4] = {"-", "to", "To", "TO"}; // Return the index to RSA if found; otherwise -1 is returned. -static int32_t -WithRSAIndex(llvm::StringRef &Arg) -{ - - uint32_t i; - for (i = 0; i < 4; ++i) - if (Arg.find(RSA[i]) != llvm::StringRef::npos) - return i; - return -1; +static int32_t WithRSAIndex(llvm::StringRef &Arg) { + + uint32_t i; + for (i = 0; i < 4; ++i) + if (Arg.find(RSA[i]) != llvm::StringRef::npos) + return i; + return -1; } // Return true if wp_ids is successfully populated with the watch ids. // False otherwise. -bool -CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(Target *target, Args &args, std::vector &wp_ids) -{ - // Pre-condition: args.GetArgumentCount() > 0. - if (args.GetArgumentCount() == 0) - { - if (target == nullptr) - return false; - WatchpointSP watch_sp = target->GetLastCreatedWatchpoint(); - if (watch_sp) - { - wp_ids.push_back(watch_sp->GetID()); - return true; - } - else - return false; - } - - llvm::StringRef Minus("-"); - std::vector StrRefArgs; - std::pair Pair; - size_t i; - int32_t idx; - // Go through the arguments and make a canonical form of arg list containing - // only numbers with possible "-" in between. - for (i = 0; i < args.GetArgumentCount(); ++i) { - llvm::StringRef Arg(args.GetArgumentAtIndex(i)); - if ((idx = WithRSAIndex(Arg)) == -1) { - StrRefArgs.push_back(Arg); - continue; - } - // The Arg contains the range specifier, split it, then. - Pair = Arg.split(RSA[idx]); - if (!Pair.first.empty()) - StrRefArgs.push_back(Pair.first); - StrRefArgs.push_back(Minus); - if (!Pair.second.empty()) - StrRefArgs.push_back(Pair.second); +bool CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + Target *target, Args &args, std::vector &wp_ids) { + // Pre-condition: args.GetArgumentCount() > 0. + if (args.GetArgumentCount() == 0) { + if (target == nullptr) + return false; + WatchpointSP watch_sp = target->GetLastCreatedWatchpoint(); + if (watch_sp) { + wp_ids.push_back(watch_sp->GetID()); + return true; + } else + return false; + } + + llvm::StringRef Minus("-"); + std::vector StrRefArgs; + std::pair Pair; + size_t i; + int32_t idx; + // Go through the arguments and make a canonical form of arg list containing + // only numbers with possible "-" in between. + for (i = 0; i < args.GetArgumentCount(); ++i) { + llvm::StringRef Arg(args.GetArgumentAtIndex(i)); + if ((idx = WithRSAIndex(Arg)) == -1) { + StrRefArgs.push_back(Arg); + continue; } - // Now process the canonical list and fill in the vector of uint32_t's. - // If there is any error, return false and the client should ignore wp_ids. - uint32_t beg, end, id; - size_t size = StrRefArgs.size(); - bool in_range = false; - for (i = 0; i < size; ++i) { - llvm::StringRef Arg = StrRefArgs[i]; - if (in_range) { - // Look for the 'end' of the range. Note StringRef::getAsInteger() - // returns true to signify error while parsing. - if (Arg.getAsInteger(0, end)) - return false; - // Found a range! Now append the elements. - for (id = beg; id <= end; ++id) - wp_ids.push_back(id); - in_range = false; - continue; - } - if (i < (size - 1) && StrRefArgs[i+1] == Minus) { - if (Arg.getAsInteger(0, beg)) - return false; - // Turn on the in_range flag, we are looking for end of range next. - ++i; in_range = true; - continue; - } - // Otherwise, we have a simple ID. Just append it. - if (Arg.getAsInteger(0, beg)) - return false; - wp_ids.push_back(beg); + // The Arg contains the range specifier, split it, then. + Pair = Arg.split(RSA[idx]); + if (!Pair.first.empty()) + StrRefArgs.push_back(Pair.first); + StrRefArgs.push_back(Minus); + if (!Pair.second.empty()) + StrRefArgs.push_back(Pair.second); + } + // Now process the canonical list and fill in the vector of uint32_t's. + // If there is any error, return false and the client should ignore wp_ids. + uint32_t beg, end, id; + size_t size = StrRefArgs.size(); + bool in_range = false; + for (i = 0; i < size; ++i) { + llvm::StringRef Arg = StrRefArgs[i]; + if (in_range) { + // Look for the 'end' of the range. Note StringRef::getAsInteger() + // returns true to signify error while parsing. + if (Arg.getAsInteger(0, end)) + return false; + // Found a range! Now append the elements. + for (id = beg; id <= end; ++id) + wp_ids.push_back(id); + in_range = false; + continue; } - // It is an error if after the loop, we're still in_range. - if (in_range) + if (i < (size - 1) && StrRefArgs[i + 1] == Minus) { + if (Arg.getAsInteger(0, beg)) return false; - - return true; // Success! + // Turn on the in_range flag, we are looking for end of range next. + ++i; + in_range = true; + continue; + } + // Otherwise, we have a simple ID. Just append it. + if (Arg.getAsInteger(0, beg)) + return false; + wp_ids.push_back(beg); + } + // It is an error if after the loop, we're still in_range. + if (in_range) + return false; + + return true; // Success! } //------------------------------------------------------------------------- @@ -162,162 +154,140 @@ CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(Target *target, Args &args //------------------------------------------------------------------------- #pragma mark List -class CommandObjectWatchpointList : public CommandObjectParsed -{ +class CommandObjectWatchpointList : public CommandObjectParsed { public: - CommandObjectWatchpointList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint list", - "List all watchpoints at configurable levels of detail.", - nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back(arg); + CommandObjectWatchpointList(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "watchpoint list", + "List all watchpoints at configurable levels of detail.", nullptr), + m_options() { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointList() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), + m_level(lldb::eDescriptionLevelBrief) // Watchpoint List defaults to + // brief descriptions + {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'b': + m_level = lldb::eDescriptionLevelBrief; + break; + case 'f': + m_level = lldb::eDescriptionLevelFull; + break; + case 'v': + m_level = lldb::eDescriptionLevelVerbose; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectWatchpointList() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_level = lldb::eDescriptionLevelFull; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_level(lldb::eDescriptionLevelBrief) // Watchpoint List defaults to brief descriptions - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'b': - m_level = lldb::eDescriptionLevelBrief; - break; - case 'f': - m_level = lldb::eDescriptionLevelFull; - break; - case 'v': - m_level = lldb::eDescriptionLevelVerbose; - break; - default: - error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_level = lldb::eDescriptionLevelFull; - } - - const OptionDefinition * - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - lldb::DescriptionLevel m_level; - }; + lldb::DescriptionLevel m_level; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (target == nullptr) - { - result.AppendError ("Invalid target. No current target or watchpoints."); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - return true; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (target == nullptr) { + result.AppendError("Invalid target. No current target or watchpoints."); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } - if (target->GetProcessSP() && target->GetProcessSP()->IsAlive()) - { - uint32_t num_supported_hardware_watchpoints; - Error error = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints); - if (error.Success()) - result.AppendMessageWithFormat("Number of supported hardware watchpoints: %u\n", - num_supported_hardware_watchpoints); - } + if (target->GetProcessSP() && target->GetProcessSP()->IsAlive()) { + uint32_t num_supported_hardware_watchpoints; + Error error = target->GetProcessSP()->GetWatchpointSupportInfo( + num_supported_hardware_watchpoints); + if (error.Success()) + result.AppendMessageWithFormat( + "Number of supported hardware watchpoints: %u\n", + num_supported_hardware_watchpoints); + } - const WatchpointList &watchpoints = target->GetWatchpointList(); + const WatchpointList &watchpoints = target->GetWatchpointList(); - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - size_t num_watchpoints = watchpoints.GetSize(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendMessage("No watchpoints currently set."); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return true; - } + if (num_watchpoints == 0) { + result.AppendMessage("No watchpoints currently set."); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + return true; + } - Stream &output_stream = result.GetOutputStream(); - - if (command.GetArgumentCount() == 0) - { - // No watchpoint selected; show info about all currently set watchpoints. - result.AppendMessage ("Current watchpoints:"); - for (size_t i = 0; i < num_watchpoints; ++i) - { - Watchpoint *wp = watchpoints.GetByIndex(i).get(); - AddWatchpointDescription(&output_stream, wp, m_options.m_level); - } - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular watchpoints selected; enable them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - { - Watchpoint *wp = watchpoints.FindByID(wp_ids[i]).get(); - if (wp) - AddWatchpointDescription(&output_stream, wp, m_options.m_level); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - } + Stream &output_stream = result.GetOutputStream(); + + if (command.GetArgumentCount() == 0) { + // No watchpoint selected; show info about all currently set watchpoints. + result.AppendMessage("Current watchpoints:"); + for (size_t i = 0; i < num_watchpoints; ++i) { + Watchpoint *wp = watchpoints.GetByIndex(i).get(); + AddWatchpointDescription(&output_stream, wp, m_options.m_level); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular watchpoints selected; enable them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) { + Watchpoint *wp = watchpoints.FindByID(wp_ids[i]).get(); + if (wp) + AddWatchpointDescription(&output_stream, wp, m_options.m_level); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; //------------------------------------------------------------------------- @@ -325,15 +295,14 @@ private: //------------------------------------------------------------------------- #pragma mark List::CommandOptions -OptionDefinition -CommandObjectWatchpointList::CommandOptions::g_option_table[] = -{ - // clang-format off +OptionDefinition CommandObjectWatchpointList::CommandOptions::g_option_table[] = + { + // clang-format off {LLDB_OPT_SET_1, false, "brief", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Give a brief description of the watchpoint (no location info)."}, {LLDB_OPT_SET_2, false, "full", 'f', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Give a full description of the watchpoint and its locations."}, {LLDB_OPT_SET_3, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Explain everything we know about the watchpoint (for debugging debugger bugs)."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -341,75 +310,70 @@ CommandObjectWatchpointList::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Enable -class CommandObjectWatchpointEnable : public CommandObjectParsed -{ +class CommandObjectWatchpointEnable : public CommandObjectParsed { public: - CommandObjectWatchpointEnable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "enable", - "Enable the specified disabled watchpoint(s). If no watchpoints are specified, enable all of them.", - nullptr) - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back(arg); - } - - ~CommandObjectWatchpointEnable() override = default; + CommandObjectWatchpointEnable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "enable", + "Enable the specified disabled watchpoint(s). If " + "no watchpoints are specified, enable all of them.", + nullptr) { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointEnable() override = default; protected: - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (!CheckTargetForWatchpointOperations(target, result)) - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (!CheckTargetForWatchpointOperations(target, result)) + return false; - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - const WatchpointList &watchpoints = target->GetWatchpointList(); + const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError("No watchpoints exist to be enabled."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (command.GetArgumentCount() == 0) - { - // No watchpoint selected; enable all currently set watchpoints. - target->EnableAllWatchpoints(); - result.AppendMessageWithFormat("All watchpoints enabled. (%" PRIu64 " watchpoints)\n", (uint64_t)num_watchpoints); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular watchpoints selected; enable them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - int count = 0; - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - if (target->EnableWatchpointByID(wp_ids[i])) - ++count; - result.AppendMessageWithFormat("%d watchpoints enabled.\n", count); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to be enabled."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + // No watchpoint selected; enable all currently set watchpoints. + target->EnableAllWatchpoints(); + result.AppendMessageWithFormat("All watchpoints enabled. (%" PRIu64 + " watchpoints)\n", + (uint64_t)num_watchpoints); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular watchpoints selected; enable them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + int count = 0; + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) + if (target->EnableWatchpointByID(wp_ids[i])) + ++count; + result.AppendMessageWithFormat("%d watchpoints enabled.\n", count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -417,80 +381,74 @@ protected: //------------------------------------------------------------------------- #pragma mark Disable -class CommandObjectWatchpointDisable : public CommandObjectParsed -{ +class CommandObjectWatchpointDisable : public CommandObjectParsed { public: - CommandObjectWatchpointDisable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint disable", - "Disable the specified watchpoint(s) without removing it/them. If no watchpoints are specified, disable them all.", - nullptr) - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back(arg); - } - - ~CommandObjectWatchpointDisable() override = default; + CommandObjectWatchpointDisable(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "watchpoint disable", + "Disable the specified watchpoint(s) without " + "removing it/them. If no watchpoints are " + "specified, disable them all.", + nullptr) { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointDisable() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (!CheckTargetForWatchpointOperations(target, result)) - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (!CheckTargetForWatchpointOperations(target, result)) + return false; - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError("No watchpoints exist to be disabled."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (command.GetArgumentCount() == 0) - { - // No watchpoint selected; disable all currently set watchpoints. - if (target->DisableAllWatchpoints()) - { - result.AppendMessageWithFormat("All watchpoints disabled. (%" PRIu64 " watchpoints)\n", (uint64_t)num_watchpoints); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } - else - { - result.AppendError("Disable all watchpoints failed\n"); - result.SetStatus(eReturnStatusFailed); - } - } - else - { - // Particular watchpoints selected; disable them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - int count = 0; - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - if (target->DisableWatchpointByID(wp_ids[i])) - ++count; - result.AppendMessageWithFormat("%d watchpoints disabled.\n", count); - result.SetStatus(eReturnStatusSuccessFinishNoResult); - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to be disabled."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + // No watchpoint selected; disable all currently set watchpoints. + if (target->DisableAllWatchpoints()) { + result.AppendMessageWithFormat("All watchpoints disabled. (%" PRIu64 + " watchpoints)\n", + (uint64_t)num_watchpoints); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + result.AppendError("Disable all watchpoints failed\n"); + result.SetStatus(eReturnStatusFailed); + } + } else { + // Particular watchpoints selected; disable them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + int count = 0; + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) + if (target->DisableWatchpointByID(wp_ids[i])) + ++count; + result.AppendMessageWithFormat("%d watchpoints disabled.\n", count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- @@ -498,229 +456,202 @@ protected: //------------------------------------------------------------------------- #pragma mark Delete -class CommandObjectWatchpointDelete : public CommandObjectParsed -{ +class CommandObjectWatchpointDelete : public CommandObjectParsed { public: - CommandObjectWatchpointDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint delete", - "Delete the specified watchpoint(s). If no watchpoints are specified, delete them all.", - nullptr) - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back(arg); - } - - ~CommandObjectWatchpointDelete() override = default; + CommandObjectWatchpointDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "watchpoint delete", + "Delete the specified watchpoint(s). If no " + "watchpoints are specified, delete them all.", + nullptr) { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointDelete() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (!CheckTargetForWatchpointOperations(target, result)) - return false; - - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (!CheckTargetForWatchpointOperations(target, result)) + return false; - const WatchpointList &watchpoints = target->GetWatchpointList(); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); - if (num_watchpoints == 0) - { - result.AppendError("No watchpoints exist to be deleted."); - result.SetStatus(eReturnStatusFailed); - return false; - } + size_t num_watchpoints = watchpoints.GetSize(); - if (command.GetArgumentCount() == 0) - { - if (!m_interpreter.Confirm("About to delete all watchpoints, do you want to do that?", true)) - { - result.AppendMessage("Operation cancelled..."); - } - else - { - target->RemoveAllWatchpoints(); - result.AppendMessageWithFormat("All watchpoints removed. (%" PRIu64 " watchpoints)\n", (uint64_t)num_watchpoints); - } - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular watchpoints selected; delete them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - int count = 0; - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - if (target->RemoveWatchpointByID(wp_ids[i])) - ++count; - result.AppendMessageWithFormat("%d watchpoints deleted.\n",count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to be deleted."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + if (!m_interpreter.Confirm( + "About to delete all watchpoints, do you want to do that?", + true)) { + result.AppendMessage("Operation cancelled..."); + } else { + target->RemoveAllWatchpoints(); + result.AppendMessageWithFormat("All watchpoints removed. (%" PRIu64 + " watchpoints)\n", + (uint64_t)num_watchpoints); + } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular watchpoints selected; delete them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + int count = 0; + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) + if (target->RemoveWatchpointByID(wp_ids[i])) + ++count; + result.AppendMessageWithFormat("%d watchpoints deleted.\n", count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectWatchpointIgnore //------------------------------------------------------------------------- -class CommandObjectWatchpointIgnore : public CommandObjectParsed -{ +class CommandObjectWatchpointIgnore : public CommandObjectParsed { public: - CommandObjectWatchpointIgnore (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint ignore", - "Set ignore count on the specified watchpoint(s). If no watchpoints are specified, set them all.", + CommandObjectWatchpointIgnore(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "watchpoint ignore", + "Set ignore count on the specified watchpoint(s). " + "If no watchpoints are specified, set them all.", nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back(arg); + m_options() { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointIgnore() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_ignore_count(0) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'i': + m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); + if (m_ignore_count == UINT32_MAX) + error.SetErrorStringWithFormat("invalid ignore count '%s'", + option_arg); + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectWatchpointIgnore() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_ignore_count = 0; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_ignore_count (0) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'i': - m_ignore_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0); - if (m_ignore_count == UINT32_MAX) - error.SetErrorStringWithFormat ("invalid ignore count '%s'", option_arg); - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_ignore_count = 0; - } - - const OptionDefinition * - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - uint32_t m_ignore_count; - }; + uint32_t m_ignore_count; + }; protected: - bool - DoExecute (Args& command, - CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (!CheckTargetForWatchpointOperations(target, result)) - return false; - - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (!CheckTargetForWatchpointOperations(target, result)) + return false; - const WatchpointList &watchpoints = target->GetWatchpointList(); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); - if (num_watchpoints == 0) - { - result.AppendError("No watchpoints exist to be ignored."); - result.SetStatus(eReturnStatusFailed); - return false; - } + size_t num_watchpoints = watchpoints.GetSize(); - if (command.GetArgumentCount() == 0) - { - target->IgnoreAllWatchpoints(m_options.m_ignore_count); - result.AppendMessageWithFormat("All watchpoints ignored. (%" PRIu64 " watchpoints)\n", (uint64_t)num_watchpoints); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular watchpoints selected; ignore them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - int count = 0; - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - if (target->IgnoreWatchpointByID(wp_ids[i], m_options.m_ignore_count)) - ++count; - result.AppendMessageWithFormat("%d watchpoints ignored.\n",count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to be ignored."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + if (command.GetArgumentCount() == 0) { + target->IgnoreAllWatchpoints(m_options.m_ignore_count); + result.AppendMessageWithFormat("All watchpoints ignored. (%" PRIu64 + " watchpoints)\n", + (uint64_t)num_watchpoints); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular watchpoints selected; ignore them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + int count = 0; + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) + if (target->IgnoreWatchpointByID(wp_ids[i], m_options.m_ignore_count)) + ++count; + result.AppendMessageWithFormat("%d watchpoints ignored.\n", count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; #pragma mark Ignore::CommandOptions OptionDefinition -CommandObjectWatchpointIgnore::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectWatchpointIgnore::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, true, "ignore-count", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Set the number of times this watchpoint is skipped before stopping."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -728,161 +659,136 @@ CommandObjectWatchpointIgnore::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark Modify -class CommandObjectWatchpointModify : public CommandObjectParsed -{ +class CommandObjectWatchpointModify : public CommandObjectParsed { public: - CommandObjectWatchpointModify (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint modify", - "Modify the options on a watchpoint or set of watchpoints in the executable. " - "If no watchpoint is specified, act on the last created watchpoint. " - "Passing an empty argument clears the modification.", - nullptr), - m_options() - { - CommandArgumentEntry arg; - CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, eArgTypeWatchpointIDRange); - // Add the entry for the first argument for this command to the object's arguments vector. - m_arguments.push_back (arg); + CommandObjectWatchpointModify(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "watchpoint modify", + "Modify the options on a watchpoint or set of watchpoints in the " + "executable. " + "If no watchpoint is specified, act on the last created " + "watchpoint. " + "Passing an empty argument clears the modification.", + nullptr), + m_options() { + CommandArgumentEntry arg; + CommandObject::AddIDsArgumentData(arg, eArgTypeWatchpointID, + eArgTypeWatchpointIDRange); + // Add the entry for the first argument for this command to the object's + // arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointModify() override = default; + + Options *GetOptions() override { return &m_options; } + + class CommandOptions : public Options { + public: + CommandOptions() : Options(), m_condition(), m_condition_passed(false) {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'c': + if (option_arg != nullptr) + m_condition.assign(option_arg); + else + m_condition.clear(); + m_condition_passed = true; + break; + default: + error.SetErrorStringWithFormat("unrecognized option '%c'", + short_option); + break; + } + + return error; } - ~CommandObjectWatchpointModify() override = default; - - Options * - GetOptions () override - { - return &m_options; + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_condition.clear(); + m_condition_passed = false; } - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_condition (), - m_condition_passed (false) - { - } - - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'c': - if (option_arg != nullptr) - m_condition.assign (option_arg); - else - m_condition.clear(); - m_condition_passed = true; - break; - default: - error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); - break; - } - - return error; - } - - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_condition.clear(); - m_condition_passed = false; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - std::string m_condition; - bool m_condition_passed; - }; + std::string m_condition; + bool m_condition_passed; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - if (!CheckTargetForWatchpointOperations(target, result)) - return false; + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + if (!CheckTargetForWatchpointOperations(target, result)) + return false; - std::unique_lock lock; - target->GetWatchpointList().GetListMutex(lock); + std::unique_lock lock; + target->GetWatchpointList().GetListMutex(lock); - const WatchpointList &watchpoints = target->GetWatchpointList(); + const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError("No watchpoints exist to be modified."); - result.SetStatus(eReturnStatusFailed); - return false; - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to be modified."); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - WatchpointSP wp_sp = target->GetLastCreatedWatchpoint(); - wp_sp->SetCondition(m_options.m_condition.c_str()); - result.SetStatus (eReturnStatusSuccessFinishNoResult); - } - else - { - // Particular watchpoints selected; set condition on them. - std::vector wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } - - int count = 0; - const size_t size = wp_ids.size(); - for (size_t i = 0; i < size; ++i) - { - WatchpointSP wp_sp = watchpoints.FindByID(wp_ids[i]); - if (wp_sp) - { - wp_sp->SetCondition(m_options.m_condition.c_str()); - ++count; - } - } - result.AppendMessageWithFormat("%d watchpoints modified.\n",count); - result.SetStatus (eReturnStatusSuccessFinishNoResult); + if (command.GetArgumentCount() == 0) { + WatchpointSP wp_sp = target->GetLastCreatedWatchpoint(); + wp_sp->SetCondition(m_options.m_condition.c_str()); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + } else { + // Particular watchpoints selected; set condition on them. + std::vector wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs( + target, command, wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } + + int count = 0; + const size_t size = wp_ids.size(); + for (size_t i = 0; i < size; ++i) { + WatchpointSP wp_sp = watchpoints.FindByID(wp_ids[i]); + if (wp_sp) { + wp_sp->SetCondition(m_options.m_condition.c_str()); + ++count; } - - return result.Succeeded(); + } + result.AppendMessageWithFormat("%d watchpoints modified.\n", count); + result.SetStatus(eReturnStatusSuccessFinishNoResult); } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; #pragma mark Modify::CommandOptions OptionDefinition -CommandObjectWatchpointModify::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectWatchpointModify::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_ALL, false, "condition", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeExpression, "The watchpoint stops only if this condition expression evaluates to true."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr} - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- @@ -890,208 +796,189 @@ CommandObjectWatchpointModify::CommandOptions::g_option_table[] = //------------------------------------------------------------------------- #pragma mark SetVariable -class CommandObjectWatchpointSetVariable : public CommandObjectParsed -{ +class CommandObjectWatchpointSetVariable : public CommandObjectParsed { public: - CommandObjectWatchpointSetVariable (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "watchpoint set variable", - "Set a watchpoint on a variable. " - "Use the '-w' option to specify the type of watchpoint and " - "the '-s' option to specify the byte size to watch for. " - "If no '-w' option is specified, it defaults to write. " - "If no '-s' option is specified, it defaults to the variable's " - "byte size. " - "Note that there are limited hardware resources for watchpoints. " - "If watchpoint setting fails, consider disable/delete existing ones " - "to free up resources.", - nullptr, - eCommandRequiresFrame | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_option_group(), - m_option_watchpoint () - { - SetHelpLong( -R"( + CommandObjectWatchpointSetVariable(CommandInterpreter &interpreter) + : CommandObjectParsed( + interpreter, "watchpoint set variable", + "Set a watchpoint on a variable. " + "Use the '-w' option to specify the type of watchpoint and " + "the '-s' option to specify the byte size to watch for. " + "If no '-w' option is specified, it defaults to write. " + "If no '-s' option is specified, it defaults to the variable's " + "byte size. " + "Note that there are limited hardware resources for watchpoints. " + "If watchpoint setting fails, consider disable/delete existing " + "ones " + "to free up resources.", + nullptr, + eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_option_group(), m_option_watchpoint() { + SetHelpLong( + R"( Examples: (lldb) watchpoint set variable -w read_write my_global_var -)" " Watches my_global_var for read/write access, with the region to watch \ -corresponding to the byte size of the data type." - ); - - CommandArgumentEntry arg; - CommandArgumentData var_name_arg; - - // Define the only variant of this arg. - var_name_arg.arg_type = eArgTypeVarName; - var_name_arg.arg_repetition = eArgRepeatPlain; - - // Push the variant into the argument entry. - arg.push_back (var_name_arg); - - // Push the data for the only argument into the m_arguments vector. - m_arguments.push_back (arg); - - // Absorb the '-w' and '-s' options into our option group. - m_option_group.Append (&m_option_watchpoint, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } +)" + " Watches my_global_var for read/write access, with the region to watch \ +corresponding to the byte size of the data type."); - ~CommandObjectWatchpointSetVariable() override = default; + CommandArgumentEntry arg; + CommandArgumentData var_name_arg; - Options * - GetOptions () override - { - return &m_option_group; - } + // Define the only variant of this arg. + var_name_arg.arg_type = eArgTypeVarName; + var_name_arg.arg_repetition = eArgRepeatPlain; + + // Push the variant into the argument entry. + arg.push_back(var_name_arg); + + // Push the data for the only argument into the m_arguments vector. + m_arguments.push_back(arg); + + // Absorb the '-w' and '-s' options into our option group. + m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Finalize(); + } + + ~CommandObjectWatchpointSetVariable() override = default; + + Options *GetOptions() override { return &m_option_group; } protected: - static size_t GetVariableCallback (void *baton, - const char *name, - VariableList &variable_list) - { - Target *target = static_cast(baton); - if (target) - { - return target->GetImages().FindGlobalVariables (ConstString(name), - true, - UINT32_MAX, - variable_list); - } - return 0; + static size_t GetVariableCallback(void *baton, const char *name, + VariableList &variable_list) { + Target *target = static_cast(baton); + if (target) { + return target->GetImages().FindGlobalVariables(ConstString(name), true, + UINT32_MAX, variable_list); + } + return 0; + } + + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + StackFrame *frame = m_exe_ctx.GetFramePtr(); + + // If no argument is present, issue an error message. There's no way to set + // a watchpoint. + if (command.GetArgumentCount() <= 0) { + result.GetErrorStream().Printf("error: required argument missing; " + "specify your program variable to watch " + "for\n"); + result.SetStatus(eReturnStatusFailed); + return false; } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - StackFrame *frame = m_exe_ctx.GetFramePtr(); - - // If no argument is present, issue an error message. There's no way to set a watchpoint. - if (command.GetArgumentCount() <= 0) - { - result.GetErrorStream().Printf("error: required argument missing; specify your program variable to watch for\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } - // If no '-w' is specified, default to '-w write'. - if (!m_option_watchpoint.watch_type_specified) - { - m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite; - } + // If no '-w' is specified, default to '-w write'. + if (!m_option_watchpoint.watch_type_specified) { + m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite; + } - // We passed the sanity check for the command. - // Proceed to set the watchpoint now. - lldb::addr_t addr = 0; - size_t size = 0; - - VariableSP var_sp; - ValueObjectSP valobj_sp; - Stream &output_stream = result.GetOutputStream(); - - // A simple watch variable gesture allows only one argument. - if (command.GetArgumentCount() != 1) - { - result.GetErrorStream().Printf("error: specify exactly one variable to watch for\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } + // We passed the sanity check for the command. + // Proceed to set the watchpoint now. + lldb::addr_t addr = 0; + size_t size = 0; + + VariableSP var_sp; + ValueObjectSP valobj_sp; + Stream &output_stream = result.GetOutputStream(); + + // A simple watch variable gesture allows only one argument. + if (command.GetArgumentCount() != 1) { + result.GetErrorStream().Printf( + "error: specify exactly one variable to watch for\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } - // Things have checked out ok... - Error error; - uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | - StackFrame::eExpressionPathOptionsAllowDirectIVarAccess; - valobj_sp = frame->GetValueForVariableExpressionPath (command.GetArgumentAtIndex(0), - eNoDynamicValues, - expr_path_options, - var_sp, - error); - - if (!valobj_sp) - { - // Not in the frame; let's check the globals. - - VariableList variable_list; - ValueObjectList valobj_list; - - Error error (Variable::GetValuesForVariableExpressionPath (command.GetArgumentAtIndex(0), - m_exe_ctx.GetBestExecutionContextScope(), - GetVariableCallback, - target, - variable_list, - valobj_list)); - - if (valobj_list.GetSize()) - valobj_sp = valobj_list.GetValueObjectAtIndex(0); - } - - CompilerType compiler_type; - - if (valobj_sp) - { - AddressType addr_type; - addr = valobj_sp->GetAddressOf(false, &addr_type); - if (addr_type == eAddressTypeLoad) - { - // We're in business. - // Find out the size of this variable. - size = m_option_watchpoint.watch_size == 0 ? valobj_sp->GetByteSize() - : m_option_watchpoint.watch_size; - } - compiler_type = valobj_sp->GetCompilerType(); - } - else - { - const char *error_cstr = error.AsCString(nullptr); - if (error_cstr) - result.GetErrorStream().Printf("error: %s\n", error_cstr); - else - result.GetErrorStream().Printf ("error: unable to find any variable expression path that matches '%s'\n", - command.GetArgumentAtIndex(0)); - return false; - } + // Things have checked out ok... + Error error; + uint32_t expr_path_options = + StackFrame::eExpressionPathOptionCheckPtrVsMember | + StackFrame::eExpressionPathOptionsAllowDirectIVarAccess; + valobj_sp = frame->GetValueForVariableExpressionPath( + command.GetArgumentAtIndex(0), eNoDynamicValues, expr_path_options, + var_sp, error); - // Now it's time to create the watchpoint. - uint32_t watch_type = m_option_watchpoint.watch_type; - - error.Clear(); - Watchpoint *wp = target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error).get(); - if (wp) - { - wp->SetWatchSpec(command.GetArgumentAtIndex(0)); - wp->SetWatchVariable(true); - if (var_sp && var_sp->GetDeclaration().GetFile()) - { - StreamString ss; - // True to show fullpath for declaration file. - var_sp->GetDeclaration().DumpStopContext(&ss, true); - wp->SetDeclInfo(ss.GetString()); - } - output_stream.Printf("Watchpoint created: "); - wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull); - output_stream.EOL(); - result.SetStatus(eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat("Watchpoint creation failed (addr=0x%" PRIx64 ", size=%" PRIu64 ", variable expression='%s').\n", - addr, (uint64_t)size, command.GetArgumentAtIndex(0)); - if (error.AsCString(nullptr)) - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - } + if (!valobj_sp) { + // Not in the frame; let's check the globals. + + VariableList variable_list; + ValueObjectList valobj_list; - return result.Succeeded(); + Error error(Variable::GetValuesForVariableExpressionPath( + command.GetArgumentAtIndex(0), + m_exe_ctx.GetBestExecutionContextScope(), GetVariableCallback, target, + variable_list, valobj_list)); + + if (valobj_list.GetSize()) + valobj_sp = valobj_list.GetValueObjectAtIndex(0); + } + + CompilerType compiler_type; + + if (valobj_sp) { + AddressType addr_type; + addr = valobj_sp->GetAddressOf(false, &addr_type); + if (addr_type == eAddressTypeLoad) { + // We're in business. + // Find out the size of this variable. + size = m_option_watchpoint.watch_size == 0 + ? valobj_sp->GetByteSize() + : m_option_watchpoint.watch_size; + } + compiler_type = valobj_sp->GetCompilerType(); + } else { + const char *error_cstr = error.AsCString(nullptr); + if (error_cstr) + result.GetErrorStream().Printf("error: %s\n", error_cstr); + else + result.GetErrorStream().Printf("error: unable to find any variable " + "expression path that matches '%s'\n", + command.GetArgumentAtIndex(0)); + return false; } + // Now it's time to create the watchpoint. + uint32_t watch_type = m_option_watchpoint.watch_type; + + error.Clear(); + Watchpoint *wp = + target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error) + .get(); + if (wp) { + wp->SetWatchSpec(command.GetArgumentAtIndex(0)); + wp->SetWatchVariable(true); + if (var_sp && var_sp->GetDeclaration().GetFile()) { + StreamString ss; + // True to show fullpath for declaration file. + var_sp->GetDeclaration().DumpStopContext(&ss, true); + wp->SetDeclInfo(ss.GetString()); + } + output_stream.Printf("Watchpoint created: "); + wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull); + output_stream.EOL(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat( + "Watchpoint creation failed (addr=0x%" PRIx64 ", size=%" PRIu64 + ", variable expression='%s').\n", + addr, (uint64_t)size, command.GetArgumentAtIndex(0)); + if (error.AsCString(nullptr)) + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + + return result.Succeeded(); + } + private: - OptionGroupOptions m_option_group; - OptionGroupWatchpoint m_option_watchpoint; + OptionGroupOptions m_option_group; + OptionGroupWatchpoint m_option_watchpoint; }; //------------------------------------------------------------------------- @@ -1099,210 +986,195 @@ private: //------------------------------------------------------------------------- #pragma mark Set -class CommandObjectWatchpointSetExpression : public CommandObjectRaw -{ +class CommandObjectWatchpointSetExpression : public CommandObjectRaw { public: - CommandObjectWatchpointSetExpression (CommandInterpreter &interpreter) : - CommandObjectRaw(interpreter, - "watchpoint set expression", - "Set a watchpoint on an address by supplying an expression. " - "Use the '-w' option to specify the type of watchpoint and " - "the '-s' option to specify the byte size to watch for. " - "If no '-w' option is specified, it defaults to write. " - "If no '-s' option is specified, it defaults to the target's " - "pointer byte size. " - "Note that there are limited hardware resources for watchpoints. " - "If watchpoint setting fails, consider disable/delete existing ones " - "to free up resources.", - nullptr, - eCommandRequiresFrame | - eCommandTryTargetAPILock | - eCommandProcessMustBeLaunched | - eCommandProcessMustBePaused ), - m_option_group(), - m_option_watchpoint () - { - SetHelpLong( -R"( + CommandObjectWatchpointSetExpression(CommandInterpreter &interpreter) + : CommandObjectRaw( + interpreter, "watchpoint set expression", + "Set a watchpoint on an address by supplying an expression. " + "Use the '-w' option to specify the type of watchpoint and " + "the '-s' option to specify the byte size to watch for. " + "If no '-w' option is specified, it defaults to write. " + "If no '-s' option is specified, it defaults to the target's " + "pointer byte size. " + "Note that there are limited hardware resources for watchpoints. " + "If watchpoint setting fails, consider disable/delete existing " + "ones " + "to free up resources.", + nullptr, + eCommandRequiresFrame | eCommandTryTargetAPILock | + eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), + m_option_group(), m_option_watchpoint() { + SetHelpLong( + R"( Examples: (lldb) watchpoint set expression -w write -s 1 -- foo + 32 - Watches write access for the 1-byte region pointed to by the address 'foo + 32')" - ); - - CommandArgumentEntry arg; - CommandArgumentData expression_arg; - - // Define the only variant of this arg. - expression_arg.arg_type = eArgTypeExpression; - expression_arg.arg_repetition = eArgRepeatPlain; - - // Push the only variant into the argument entry. - arg.push_back (expression_arg); - - // Push the data for the only argument into the m_arguments vector. - m_arguments.push_back (arg); - - // Absorb the '-w' and '-s' options into our option group. - m_option_group.Append (&m_option_watchpoint, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); - m_option_group.Finalize(); - } + Watches write access for the 1-byte region pointed to by the address 'foo + 32')"); - ~CommandObjectWatchpointSetExpression() override = default; + CommandArgumentEntry arg; + CommandArgumentData expression_arg; - // Overrides base class's behavior where WantsCompletion = !WantsRawCommandString. - bool - WantsCompletion() override { return true; } + // Define the only variant of this arg. + expression_arg.arg_type = eArgTypeExpression; + expression_arg.arg_repetition = eArgRepeatPlain; - Options * - GetOptions () override - { - return &m_option_group; - } + // Push the only variant into the argument entry. + arg.push_back(expression_arg); -protected: - bool - DoExecute (const char *raw_command, CommandReturnObject &result) override - { - auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); - m_option_group.NotifyOptionParsingStarting(&exe_ctx); // This is a raw command, so notify the option group - - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - StackFrame *frame = m_exe_ctx.GetFramePtr(); - - Args command(raw_command); - const char *expr = nullptr; - if (raw_command[0] == '-') - { - // We have some options and these options MUST end with --. - const char *end_options = nullptr; - const char *s = raw_command; - while (s && s[0]) - { - end_options = ::strstr (s, "--"); - if (end_options) - { - end_options += 2; // Get past the "--" - if (::isspace (end_options[0])) - { - expr = end_options; - while (::isspace (*expr)) - ++expr; - break; - } - } - s = end_options; - } - - if (end_options) - { - Args args (llvm::StringRef(raw_command, end_options - raw_command)); - if (!ParseOptions (args, result)) - return false; - - Error error(m_option_group.NotifyOptionParsingFinished( - &exe_ctx)); - if (error.Fail()) - { - result.AppendError (error.AsCString()); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - } + // Push the data for the only argument into the m_arguments vector. + m_arguments.push_back(arg); - if (expr == nullptr) - expr = raw_command; + // Absorb the '-w' and '-s' options into our option group. + m_option_group.Append(&m_option_watchpoint, LLDB_OPT_SET_ALL, + LLDB_OPT_SET_1); + m_option_group.Finalize(); + } - // If no argument is present, issue an error message. There's no way to set a watchpoint. - if (command.GetArgumentCount() == 0) - { - result.GetErrorStream().Printf("error: required argument missing; specify an expression to evaulate into the address to watch for\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } + ~CommandObjectWatchpointSetExpression() override = default; - // If no '-w' is specified, default to '-w write'. - if (!m_option_watchpoint.watch_type_specified) - { - m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite; - } + // Overrides base class's behavior where WantsCompletion = + // !WantsRawCommandString. + bool WantsCompletion() override { return true; } - // We passed the sanity check for the command. - // Proceed to set the watchpoint now. - lldb::addr_t addr = 0; - size_t size = 0; - - ValueObjectSP valobj_sp; - - // Use expression evaluation to arrive at the address to watch. - EvaluateExpressionOptions options; - options.SetCoerceToId(false); - options.SetUnwindOnError(true); - options.SetKeepInMemory(false); - options.SetTryAllThreads(true); - options.SetTimeoutUsec(0); - - ExpressionResults expr_result = target->EvaluateExpression (expr, - frame, - valobj_sp, - options); - if (expr_result != eExpressionCompleted) - { - result.GetErrorStream().Printf("error: expression evaluation of address to watch failed\n"); - result.GetErrorStream().Printf("expression evaluated: %s\n", expr); - result.SetStatus(eReturnStatusFailed); - return false; - } + Options *GetOptions() override { return &m_option_group; } - // Get the address to watch. - bool success = false; - addr = valobj_sp->GetValueAsUnsigned(0, &success); - if (!success) - { - result.GetErrorStream().Printf("error: expression did not evaluate to an address\n"); - result.SetStatus(eReturnStatusFailed); - return false; - } - - if (m_option_watchpoint.watch_size != 0) - size = m_option_watchpoint.watch_size; - else - size = target->GetArchitecture().GetAddressByteSize(); - - // Now it's time to create the watchpoint. - uint32_t watch_type = m_option_watchpoint.watch_type; - - // Fetch the type from the value object, the type of the watched object is the pointee type - /// of the expression, so convert to that if we found a valid type. - CompilerType compiler_type(valobj_sp->GetCompilerType()); - - Error error; - Watchpoint *wp = target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error).get(); - if (wp) - { - Stream &output_stream = result.GetOutputStream(); - output_stream.Printf("Watchpoint created: "); - wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull); - output_stream.EOL(); - result.SetStatus(eReturnStatusSuccessFinishResult); +protected: + bool DoExecute(const char *raw_command, + CommandReturnObject &result) override { + auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); + m_option_group.NotifyOptionParsingStarting( + &exe_ctx); // This is a raw command, so notify the option group + + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + StackFrame *frame = m_exe_ctx.GetFramePtr(); + + Args command(raw_command); + const char *expr = nullptr; + if (raw_command[0] == '-') { + // We have some options and these options MUST end with --. + const char *end_options = nullptr; + const char *s = raw_command; + while (s && s[0]) { + end_options = ::strstr(s, "--"); + if (end_options) { + end_options += 2; // Get past the "--" + if (::isspace(end_options[0])) { + expr = end_options; + while (::isspace(*expr)) + ++expr; + break; + } } - else - { - result.AppendErrorWithFormat("Watchpoint creation failed (addr=0x%" PRIx64 ", size=%" PRIu64 ").\n", - addr, (uint64_t)size); - if (error.AsCString(nullptr)) - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); + s = end_options; + } + + if (end_options) { + Args args(llvm::StringRef(raw_command, end_options - raw_command)); + if (!ParseOptions(args, result)) + return false; + + Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + if (error.Fail()) { + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + return false; } + } + } - return result.Succeeded(); + if (expr == nullptr) + expr = raw_command; + + // If no argument is present, issue an error message. There's no way to set + // a watchpoint. + if (command.GetArgumentCount() == 0) { + result.GetErrorStream().Printf("error: required argument missing; " + "specify an expression to evaulate into " + "the address to watch for\n"); + result.SetStatus(eReturnStatusFailed); + return false; } + // If no '-w' is specified, default to '-w write'. + if (!m_option_watchpoint.watch_type_specified) { + m_option_watchpoint.watch_type = OptionGroupWatchpoint::eWatchWrite; + } + + // We passed the sanity check for the command. + // Proceed to set the watchpoint now. + lldb::addr_t addr = 0; + size_t size = 0; + + ValueObjectSP valobj_sp; + + // Use expression evaluation to arrive at the address to watch. + EvaluateExpressionOptions options; + options.SetCoerceToId(false); + options.SetUnwindOnError(true); + options.SetKeepInMemory(false); + options.SetTryAllThreads(true); + options.SetTimeoutUsec(0); + + ExpressionResults expr_result = + target->EvaluateExpression(expr, frame, valobj_sp, options); + if (expr_result != eExpressionCompleted) { + result.GetErrorStream().Printf( + "error: expression evaluation of address to watch failed\n"); + result.GetErrorStream().Printf("expression evaluated: %s\n", expr); + result.SetStatus(eReturnStatusFailed); + return false; + } + + // Get the address to watch. + bool success = false; + addr = valobj_sp->GetValueAsUnsigned(0, &success); + if (!success) { + result.GetErrorStream().Printf( + "error: expression did not evaluate to an address\n"); + result.SetStatus(eReturnStatusFailed); + return false; + } + + if (m_option_watchpoint.watch_size != 0) + size = m_option_watchpoint.watch_size; + else + size = target->GetArchitecture().GetAddressByteSize(); + + // Now it's time to create the watchpoint. + uint32_t watch_type = m_option_watchpoint.watch_type; + + // Fetch the type from the value object, the type of the watched object is + // the pointee type + /// of the expression, so convert to that if we found a valid type. + CompilerType compiler_type(valobj_sp->GetCompilerType()); + + Error error; + Watchpoint *wp = + target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error) + .get(); + if (wp) { + Stream &output_stream = result.GetOutputStream(); + output_stream.Printf("Watchpoint created: "); + wp->GetDescription(&output_stream, lldb::eDescriptionLevelFull); + output_stream.EOL(); + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Watchpoint creation failed (addr=0x%" PRIx64 + ", size=%" PRIu64 ").\n", + addr, (uint64_t)size); + if (error.AsCString(nullptr)) + result.AppendError(error.AsCString()); + result.SetStatus(eReturnStatusFailed); + } + + return result.Succeeded(); + } + private: - OptionGroupOptions m_option_group; - OptionGroupWatchpoint m_option_watchpoint; + OptionGroupOptions m_option_group; + OptionGroupWatchpoint m_option_watchpoint; }; //------------------------------------------------------------------------- @@ -1310,19 +1182,22 @@ private: //------------------------------------------------------------------------- #pragma mark Set -class CommandObjectWatchpointSet : public CommandObjectMultiword -{ +class CommandObjectWatchpointSet : public CommandObjectMultiword { public: - CommandObjectWatchpointSet(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "watchpoint set", "Commands for setting a watchpoint.", - "watchpoint set []") - { - - LoadSubCommand ("variable", CommandObjectSP (new CommandObjectWatchpointSetVariable (interpreter))); - LoadSubCommand ("expression", CommandObjectSP (new CommandObjectWatchpointSetExpression (interpreter))); - } - - ~CommandObjectWatchpointSet() override = default; + CommandObjectWatchpointSet(CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "watchpoint set", "Commands for setting a watchpoint.", + "watchpoint set []") { + + LoadSubCommand( + "variable", + CommandObjectSP(new CommandObjectWatchpointSetVariable(interpreter))); + LoadSubCommand( + "expression", + CommandObjectSP(new CommandObjectWatchpointSetExpression(interpreter))); + } + + ~CommandObjectWatchpointSet() override = default; }; //------------------------------------------------------------------------- @@ -1330,36 +1205,45 @@ public: //------------------------------------------------------------------------- #pragma mark MultiwordWatchpoint -CommandObjectMultiwordWatchpoint::CommandObjectMultiwordWatchpoint(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "watchpoint", "Commands for operating on watchpoints.", - "watchpoint []") -{ - CommandObjectSP list_command_object (new CommandObjectWatchpointList (interpreter)); - CommandObjectSP enable_command_object (new CommandObjectWatchpointEnable (interpreter)); - CommandObjectSP disable_command_object (new CommandObjectWatchpointDisable (interpreter)); - CommandObjectSP delete_command_object (new CommandObjectWatchpointDelete (interpreter)); - CommandObjectSP ignore_command_object (new CommandObjectWatchpointIgnore (interpreter)); - CommandObjectSP command_command_object (new CommandObjectWatchpointCommand (interpreter)); - CommandObjectSP modify_command_object (new CommandObjectWatchpointModify (interpreter)); - CommandObjectSP set_command_object (new CommandObjectWatchpointSet (interpreter)); - - list_command_object->SetCommandName ("watchpoint list"); - enable_command_object->SetCommandName("watchpoint enable"); - disable_command_object->SetCommandName("watchpoint disable"); - delete_command_object->SetCommandName("watchpoint delete"); - ignore_command_object->SetCommandName("watchpoint ignore"); - command_command_object->SetCommandName ("watchpoint command"); - modify_command_object->SetCommandName("watchpoint modify"); - set_command_object->SetCommandName("watchpoint set"); - - LoadSubCommand ("list", list_command_object); - LoadSubCommand ("enable", enable_command_object); - LoadSubCommand ("disable", disable_command_object); - LoadSubCommand ("delete", delete_command_object); - LoadSubCommand ("ignore", ignore_command_object); - LoadSubCommand ("command", command_command_object); - LoadSubCommand ("modify", modify_command_object); - LoadSubCommand ("set", set_command_object); +CommandObjectMultiwordWatchpoint::CommandObjectMultiwordWatchpoint( + CommandInterpreter &interpreter) + : CommandObjectMultiword(interpreter, "watchpoint", + "Commands for operating on watchpoints.", + "watchpoint []") { + CommandObjectSP list_command_object( + new CommandObjectWatchpointList(interpreter)); + CommandObjectSP enable_command_object( + new CommandObjectWatchpointEnable(interpreter)); + CommandObjectSP disable_command_object( + new CommandObjectWatchpointDisable(interpreter)); + CommandObjectSP delete_command_object( + new CommandObjectWatchpointDelete(interpreter)); + CommandObjectSP ignore_command_object( + new CommandObjectWatchpointIgnore(interpreter)); + CommandObjectSP command_command_object( + new CommandObjectWatchpointCommand(interpreter)); + CommandObjectSP modify_command_object( + new CommandObjectWatchpointModify(interpreter)); + CommandObjectSP set_command_object( + new CommandObjectWatchpointSet(interpreter)); + + list_command_object->SetCommandName("watchpoint list"); + enable_command_object->SetCommandName("watchpoint enable"); + disable_command_object->SetCommandName("watchpoint disable"); + delete_command_object->SetCommandName("watchpoint delete"); + ignore_command_object->SetCommandName("watchpoint ignore"); + command_command_object->SetCommandName("watchpoint command"); + modify_command_object->SetCommandName("watchpoint modify"); + set_command_object->SetCommandName("watchpoint set"); + + LoadSubCommand("list", list_command_object); + LoadSubCommand("enable", enable_command_object); + LoadSubCommand("disable", disable_command_object); + LoadSubCommand("delete", delete_command_object); + LoadSubCommand("ignore", ignore_command_object); + LoadSubCommand("command", command_command_object); + LoadSubCommand("modify", modify_command_object); + LoadSubCommand("set", set_command_object); } CommandObjectMultiwordWatchpoint::~CommandObjectMultiwordWatchpoint() = default; diff --git a/lldb/source/Commands/CommandObjectWatchpoint.h b/lldb/source/Commands/CommandObjectWatchpoint.h index b1926dc2ad7..adc0a81fa69 100644 --- a/lldb/source/Commands/CommandObjectWatchpoint.h +++ b/lldb/source/Commands/CommandObjectWatchpoint.h @@ -16,8 +16,8 @@ // Other libraries and framework includes // Project includes #include "lldb/Interpreter/CommandObjectMultiword.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionGroupWatchpoint.h" +#include "lldb/Interpreter/Options.h" namespace lldb_private { @@ -25,15 +25,14 @@ namespace lldb_private { // CommandObjectMultiwordWatchpoint //------------------------------------------------------------------------- -class CommandObjectMultiwordWatchpoint : public CommandObjectMultiword -{ +class CommandObjectMultiwordWatchpoint : public CommandObjectMultiword { public: - CommandObjectMultiwordWatchpoint (CommandInterpreter &interpreter); + CommandObjectMultiwordWatchpoint(CommandInterpreter &interpreter); - ~CommandObjectMultiwordWatchpoint() override; + ~CommandObjectMultiwordWatchpoint() override; - static bool - VerifyWatchpointIDs(Target *target, Args &args, std::vector &wp_ids); + static bool VerifyWatchpointIDs(Target *target, Args &args, + std::vector &wp_ids); }; } // namespace lldb_private diff --git a/lldb/source/Commands/CommandObjectWatchpointCommand.cpp b/lldb/source/Commands/CommandObjectWatchpointCommand.cpp index cc6df7538ba..1cd253bf89e 100644 --- a/lldb/source/Commands/CommandObjectWatchpointCommand.cpp +++ b/lldb/source/Commands/CommandObjectWatchpointCommand.cpp @@ -13,16 +13,16 @@ // Other libraries and framework includes // Project includes -#include "CommandObjectWatchpointCommand.h" #include "CommandObjectWatchpoint.h" +#include "CommandObjectWatchpointCommand.h" +#include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Breakpoint/Watchpoint.h" #include "lldb/Core/IOHandler.h" +#include "lldb/Core/State.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" -#include "lldb/Breakpoint/Watchpoint.h" -#include "lldb/Breakpoint/StoppointCallbackContext.h" -#include "lldb/Core/State.h" using namespace lldb; using namespace lldb_private; @@ -31,43 +31,50 @@ using namespace lldb_private; // CommandObjectWatchpointCommandAdd //------------------------------------------------------------------------- -class CommandObjectWatchpointCommandAdd : - public CommandObjectParsed, - public IOHandlerDelegateMultiline -{ +class CommandObjectWatchpointCommandAdd : public CommandObjectParsed, + public IOHandlerDelegateMultiline { public: - CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter) - : CommandObjectParsed( - interpreter, "add", - "Add a set of LLDB commands to a watchpoint, to be executed whenever the watchpoint is hit.", nullptr), - IOHandlerDelegateMultiline("DONE", IOHandlerDelegate::Completion::LLDBCommand), - m_options() - { - SetHelpLong ( -R"( + CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "add", + "Add a set of LLDB commands to a watchpoint, to be " + "executed whenever the watchpoint is hit.", + nullptr), + IOHandlerDelegateMultiline("DONE", + IOHandlerDelegate::Completion::LLDBCommand), + m_options() { + SetHelpLong( + R"( General information about entering watchpoint commands ------------------------------------------------------ -)" "This command will prompt for commands to be executed when the specified \ +)" + "This command will prompt for commands to be executed when the specified \ watchpoint is hit. Each command is typed on its own line following the '> ' \ -prompt until 'DONE' is entered." R"( +prompt until 'DONE' is entered." + R"( -)" "Syntactic errors may not be detected when initially entered, and many \ +)" + "Syntactic errors may not be detected when initially entered, and many \ malformed commands can silently fail when executed. If your watchpoint commands \ -do not appear to be executing, double-check the command syntax." R"( +do not appear to be executing, double-check the command syntax." + R"( -)" "Note: You may enter any debugger command exactly as you would at the debugger \ +)" + "Note: You may enter any debugger command exactly as you would at the debugger \ prompt. There is no limit to the number of commands supplied, but do NOT enter \ -more than one command per line." R"( +more than one command per line." + R"( Special information about PYTHON watchpoint commands ---------------------------------------------------- -)" "You may enter either one or more lines of Python, including function \ +)" + "You may enter either one or more lines of Python, including function \ definitions or calls to functions that will have been imported by the time \ the code executes. Single line watchpoint commands will be interpreted 'as is' \ when the watchpoint is hit. Multiple lines of Python will be wrapped in a \ -generated function, and a call to the function will be attached to the watchpoint." R"( +generated function, and a call to the function will be attached to the watchpoint." + R"( This auto-generated function is passed in three arguments: @@ -75,8 +82,10 @@ This auto-generated function is passed in three arguments: wp: the watchpoint that was hit. -)" "When specifying a python function with the --python-function option, you need \ -to supply the function name prepended by the module name:" R"( +)" + "When specifying a python function with the --python-function option, you need \ +to supply the function name prepended by the module name:" + R"( --python-function myutils.watchpoint_callback @@ -85,16 +94,20 @@ The function itself must have the following prototype: def watchpoint_callback(frame, wp): # Your code goes here -)" "The arguments are the same as the arguments passed to generated functions as \ +)" + "The arguments are the same as the arguments passed to generated functions as \ described above. Note that the global variable 'lldb.frame' will NOT be updated when \ this function is called, so be sure to use the 'frame' argument. The 'frame' argument \ can get you to the thread via frame.GetThread(), the thread can get you to the \ process via thread.GetProcess(), and the process can get you back to the target \ -via process.GetTarget()." R"( +via process.GetTarget()." + R"( -)" "Important Note: As Python code gets collected into functions, access to global \ +)" + "Important Note: As Python code gets collected into functions, access to global \ variables requires explicit scoping using the 'global' keyword. Be sure to use correct \ -Python syntax, including indentation, when entering Python watchpoint commands." R"( +Python syntax, including indentation, when entering Python watchpoint commands." + R"( Example Python one-line watchpoint command: @@ -139,585 +152,540 @@ Enter your Python command(s). Type 'DONE' to end. > print "Hit this watchpoint " + repr(wp_count) + " times!" > DONE -)" "In this case, since there is a reference to a global variable, \ +)" + "In this case, since there is a reference to a global variable, \ 'wp_count', you will also need to make sure 'wp_count' exists and is \ -initialized:" R"( +initialized:" + R"( (lldb) script >>> wp_count = 0 >>> quit() -)" "Final Note: A warning that no watchpoint command was generated when there \ -are no syntax errors may indicate that a function was declared but never called." - ); +)" + "Final Note: A warning that no watchpoint command was generated when there \ +are no syntax errors may indicate that a function was declared but never called."); - CommandArgumentEntry arg; - CommandArgumentData wp_id_arg; + CommandArgumentEntry arg; + CommandArgumentData wp_id_arg; - // Define the first (and only) variant of this arg. - wp_id_arg.arg_type = eArgTypeWatchpointID; - wp_id_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + wp_id_arg.arg_type = eArgTypeWatchpointID; + wp_id_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (wp_id_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(wp_id_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectWatchpointCommandAdd() override = default; + ~CommandObjectWatchpointCommandAdd() override = default; - Options * - GetOptions () override - { - return &m_options; - } + Options *GetOptions() override { return &m_options; } - void - IOHandlerActivated (IOHandler &io_handler) override - { - StreamFileSP output_sp(io_handler.GetOutputStreamFile()); - if (output_sp) - { - output_sp->PutCString("Enter your debugger command(s). Type 'DONE' to end.\n"); - output_sp->Flush(); - } + void IOHandlerActivated(IOHandler &io_handler) override { + StreamFileSP output_sp(io_handler.GetOutputStreamFile()); + if (output_sp) { + output_sp->PutCString( + "Enter your debugger command(s). Type 'DONE' to end.\n"); + output_sp->Flush(); } - - void - IOHandlerInputComplete (IOHandler &io_handler, std::string &line) override - { - io_handler.SetIsDone(true); - - // The WatchpointOptions object is owned by the watchpoint or watchpoint location - WatchpointOptions *wp_options = (WatchpointOptions *) io_handler.GetUserData(); - if (wp_options) - { - std::unique_ptr data_ap(new WatchpointOptions::CommandData()); - if (data_ap) - { - data_ap->user_source.SplitIntoLines(line); - BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); - wp_options->SetCallback (WatchpointOptionsCallbackFunction, baton_sp); - } - } + } + + void IOHandlerInputComplete(IOHandler &io_handler, + std::string &line) override { + io_handler.SetIsDone(true); + + // The WatchpointOptions object is owned by the watchpoint or watchpoint + // location + WatchpointOptions *wp_options = + (WatchpointOptions *)io_handler.GetUserData(); + if (wp_options) { + std::unique_ptr data_ap( + new WatchpointOptions::CommandData()); + if (data_ap) { + data_ap->user_source.SplitIntoLines(line); + BatonSP baton_sp( + new WatchpointOptions::CommandBaton(data_ap.release())); + wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); + } } - - void - CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options, - CommandReturnObject &result) - { - m_interpreter.GetLLDBCommandsFromIOHandler ("> ", // Prompt - *this, // IOHandlerDelegate - true, // Run IOHandler in async mode - wp_options); // Baton for the "io_handler" that will be passed back into our IOHandlerDelegate functions + } + + void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, + CommandReturnObject &result) { + m_interpreter.GetLLDBCommandsFromIOHandler( + "> ", // Prompt + *this, // IOHandlerDelegate + true, // Run IOHandler in async mode + wp_options); // Baton for the "io_handler" that will be passed back into + // our IOHandlerDelegate functions + } + + /// Set a one-liner as the callback for the watchpoint. + void SetWatchpointCommandCallback(WatchpointOptions *wp_options, + const char *oneliner) { + std::unique_ptr data_ap( + new WatchpointOptions::CommandData()); + + // It's necessary to set both user_source and script_source to the oneliner. + // The former is used to generate callback description (as in watchpoint + // command list) + // while the latter is used for Python to interpret during the actual + // callback. + data_ap->user_source.AppendString(oneliner); + data_ap->script_source.assign(oneliner); + data_ap->stop_on_error = m_options.m_stop_on_error; + + BatonSP baton_sp(new WatchpointOptions::CommandBaton(data_ap.release())); + wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); + } + + static bool + WatchpointOptionsCallbackFunction(void *baton, + StoppointCallbackContext *context, + lldb::user_id_t watch_id) { + bool ret_value = true; + if (baton == nullptr) + return true; + + WatchpointOptions::CommandData *data = + (WatchpointOptions::CommandData *)baton; + StringList &commands = data->user_source; + + if (commands.GetSize() > 0) { + ExecutionContext exe_ctx(context->exe_ctx_ref); + Target *target = exe_ctx.GetTargetPtr(); + if (target) { + CommandReturnObject result; + Debugger &debugger = target->GetDebugger(); + // Rig up the results secondary output stream to the debugger's, so the + // output will come out synchronously + // if the debugger is set up that way. + + StreamSP output_stream(debugger.GetAsyncOutputStream()); + StreamSP error_stream(debugger.GetAsyncErrorStream()); + result.SetImmediateOutputStream(output_stream); + result.SetImmediateErrorStream(error_stream); + + CommandInterpreterRunOptions options; + options.SetStopOnContinue(true); + options.SetStopOnError(data->stop_on_error); + options.SetEchoCommands(false); + options.SetPrintResults(true); + options.SetAddToHistory(false); + + debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx, + options, result); + result.GetImmediateOutputStream()->Flush(); + result.GetImmediateErrorStream()->Flush(); + } } - - /// Set a one-liner as the callback for the watchpoint. - void - SetWatchpointCommandCallback (WatchpointOptions *wp_options, - const char *oneliner) - { - std::unique_ptr data_ap(new WatchpointOptions::CommandData()); - - // It's necessary to set both user_source and script_source to the oneliner. - // The former is used to generate callback description (as in watchpoint command list) - // while the latter is used for Python to interpret during the actual callback. - data_ap->user_source.AppendString (oneliner); - data_ap->script_source.assign (oneliner); - data_ap->stop_on_error = m_options.m_stop_on_error; - - BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release())); - wp_options->SetCallback (WatchpointOptionsCallbackFunction, baton_sp); + return ret_value; + } + + class CommandOptions : public Options { + public: + CommandOptions() + : Options(), m_use_commands(false), m_use_script_language(false), + m_script_language(eScriptLanguageNone), m_use_one_liner(false), + m_one_liner(), m_function_name() {} + + ~CommandOptions() override = default; + + Error SetOptionValue(uint32_t option_idx, const char *option_arg, + ExecutionContext *execution_context) override { + Error error; + const int short_option = m_getopt_table[option_idx].val; + + switch (short_option) { + case 'o': + m_use_one_liner = true; + m_one_liner = option_arg; + break; + + case 's': + m_script_language = (lldb::ScriptLanguage)Args::StringToOptionEnum( + option_arg, g_option_table[option_idx].enum_values, + eScriptLanguageNone, error); + + m_use_script_language = (m_script_language == eScriptLanguagePython || + m_script_language == eScriptLanguageDefault); + break; + + case 'e': { + bool success = false; + m_stop_on_error = Args::StringToBoolean(option_arg, false, &success); + if (!success) + error.SetErrorStringWithFormat( + "invalid value for stop-on-error: \"%s\"", option_arg); + } break; + + case 'F': + m_use_one_liner = false; + m_use_script_language = true; + m_function_name.assign(option_arg); + break; + + default: + break; + } + return error; } - - static bool - WatchpointOptionsCallbackFunction (void *baton, - StoppointCallbackContext *context, - lldb::user_id_t watch_id) - { - bool ret_value = true; - if (baton == nullptr) - return true; - - WatchpointOptions::CommandData *data = (WatchpointOptions::CommandData *) baton; - StringList &commands = data->user_source; - - if (commands.GetSize() > 0) - { - ExecutionContext exe_ctx (context->exe_ctx_ref); - Target *target = exe_ctx.GetTargetPtr(); - if (target) - { - CommandReturnObject result; - Debugger &debugger = target->GetDebugger(); - // Rig up the results secondary output stream to the debugger's, so the output will come out synchronously - // if the debugger is set up that way. - - StreamSP output_stream (debugger.GetAsyncOutputStream()); - StreamSP error_stream (debugger.GetAsyncErrorStream()); - result.SetImmediateOutputStream (output_stream); - result.SetImmediateErrorStream (error_stream); - - CommandInterpreterRunOptions options; - options.SetStopOnContinue (true); - options.SetStopOnError (data->stop_on_error); - options.SetEchoCommands (false); - options.SetPrintResults (true); - options.SetAddToHistory (false); - - debugger.GetCommandInterpreter().HandleCommands (commands, - &exe_ctx, - options, - result); - result.GetImmediateOutputStream()->Flush(); - result.GetImmediateErrorStream()->Flush(); - } - } - return ret_value; - } - - class CommandOptions : public Options - { - public: - CommandOptions() : - Options(), - m_use_commands (false), - m_use_script_language (false), - m_script_language (eScriptLanguageNone), - m_use_one_liner (false), - m_one_liner(), - m_function_name() - { - } - ~CommandOptions() override = default; - - Error - SetOptionValue(uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - const int short_option = m_getopt_table[option_idx].val; - - switch (short_option) - { - case 'o': - m_use_one_liner = true; - m_one_liner = option_arg; - break; - - case 's': - m_script_language = (lldb::ScriptLanguage) Args::StringToOptionEnum (option_arg, - g_option_table[option_idx].enum_values, - eScriptLanguageNone, - error); - - m_use_script_language = - (m_script_language == eScriptLanguagePython || m_script_language == eScriptLanguageDefault); - break; - - case 'e': - { - bool success = false; - m_stop_on_error = Args::StringToBoolean(option_arg, false, &success); - if (!success) - error.SetErrorStringWithFormat("invalid value for stop-on-error: \"%s\"", option_arg); - } - break; - - case 'F': - m_use_one_liner = false; - m_use_script_language = true; - m_function_name.assign(option_arg); - break; - - default: - break; - } - return error; - } + void OptionParsingStarting(ExecutionContext *execution_context) override { + m_use_commands = true; + m_use_script_language = false; + m_script_language = eScriptLanguageNone; - void - OptionParsingStarting(ExecutionContext *execution_context) override - { - m_use_commands = true; - m_use_script_language = false; - m_script_language = eScriptLanguageNone; - - m_use_one_liner = false; - m_stop_on_error = true; - m_one_liner.clear(); - m_function_name.clear(); - } + m_use_one_liner = false; + m_stop_on_error = true; + m_one_liner.clear(); + m_function_name.clear(); + } - const OptionDefinition* - GetDefinitions () override - { - return g_option_table; - } + const OptionDefinition *GetDefinitions() override { return g_option_table; } - // Options table: Required for subclasses of Options. + // Options table: Required for subclasses of Options. - static OptionDefinition g_option_table[]; + static OptionDefinition g_option_table[]; - // Instance variables to hold the values for command options. + // Instance variables to hold the values for command options. - bool m_use_commands; - bool m_use_script_language; - lldb::ScriptLanguage m_script_language; + bool m_use_commands; + bool m_use_script_language; + lldb::ScriptLanguage m_script_language; - // Instance variables to hold the values for one_liner options. - bool m_use_one_liner; - std::string m_one_liner; - bool m_stop_on_error; - std::string m_function_name; - }; + // Instance variables to hold the values for one_liner options. + bool m_use_one_liner; + std::string m_one_liner; + bool m_stop_on_error; + std::string m_function_name; + }; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no watchpoints to which to add commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "watchpoints to which to add commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError ("No watchpoints exist to have commands added"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to have commands added"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (!m_options.m_use_script_language && !m_options.m_function_name.empty()) - { - result.AppendError ("need to enable scripting to have a function run as a watchpoint command"); - result.SetStatus (eReturnStatusFailed); - return false; - } - - std::vector valid_wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, valid_wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } + if (!m_options.m_use_script_language && + !m_options.m_function_name.empty()) { + result.AppendError("need to enable scripting to have a function run as a " + "watchpoint command"); + result.SetStatus(eReturnStatusFailed); + return false; + } - result.SetStatus(eReturnStatusSuccessFinishNoResult); - const size_t count = valid_wp_ids.size(); - for (size_t i = 0; i < count; ++i) - { - uint32_t cur_wp_id = valid_wp_ids.at (i); - if (cur_wp_id != LLDB_INVALID_WATCH_ID) - { - Watchpoint *wp = target->GetWatchpointList().FindByID (cur_wp_id).get(); - // Sanity check wp first. - if (wp == nullptr) continue; - - WatchpointOptions *wp_options = wp->GetOptions(); - // Skip this watchpoint if wp_options is not good. - if (wp_options == nullptr) continue; - - // If we are using script language, get the script interpreter - // in order to set or collect command callback. Otherwise, call - // the methods associated with this object. - if (m_options.m_use_script_language) - { - // Special handling for one-liner specified inline. - if (m_options.m_use_one_liner) - { - m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback (wp_options, - m_options.m_one_liner.c_str()); - } - // Special handling for using a Python function by name - // instead of extending the watchpoint callback data structures, we just automatize - // what the user would do manually: make their watchpoint command be a function call - else if (!m_options.m_function_name.empty()) - { - std::string oneliner(m_options.m_function_name); - oneliner += "(frame, wp, internal_dict)"; - m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback (wp_options, - oneliner.c_str()); - } - else - { - m_interpreter.GetScriptInterpreter()->CollectDataForWatchpointCommandCallback (wp_options, - result); - } - } - else - { - // Special handling for one-liner specified inline. - if (m_options.m_use_one_liner) - SetWatchpointCommandCallback (wp_options, - m_options.m_one_liner.c_str()); - else - CollectDataForWatchpointCommandCallback (wp_options, - result); - } - } - } + std::vector valid_wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, + valid_wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } - return result.Succeeded(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + const size_t count = valid_wp_ids.size(); + for (size_t i = 0; i < count; ++i) { + uint32_t cur_wp_id = valid_wp_ids.at(i); + if (cur_wp_id != LLDB_INVALID_WATCH_ID) { + Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); + // Sanity check wp first. + if (wp == nullptr) + continue; + + WatchpointOptions *wp_options = wp->GetOptions(); + // Skip this watchpoint if wp_options is not good. + if (wp_options == nullptr) + continue; + + // If we are using script language, get the script interpreter + // in order to set or collect command callback. Otherwise, call + // the methods associated with this object. + if (m_options.m_use_script_language) { + // Special handling for one-liner specified inline. + if (m_options.m_use_one_liner) { + m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback( + wp_options, m_options.m_one_liner.c_str()); + } + // Special handling for using a Python function by name + // instead of extending the watchpoint callback data structures, we + // just automatize + // what the user would do manually: make their watchpoint command be a + // function call + else if (!m_options.m_function_name.empty()) { + std::string oneliner(m_options.m_function_name); + oneliner += "(frame, wp, internal_dict)"; + m_interpreter.GetScriptInterpreter()->SetWatchpointCommandCallback( + wp_options, oneliner.c_str()); + } else { + m_interpreter.GetScriptInterpreter() + ->CollectDataForWatchpointCommandCallback(wp_options, result); + } + } else { + // Special handling for one-liner specified inline. + if (m_options.m_use_one_liner) + SetWatchpointCommandCallback(wp_options, + m_options.m_one_liner.c_str()); + else + CollectDataForWatchpointCommandCallback(wp_options, result); + } + } } + return result.Succeeded(); + } + private: - CommandOptions m_options; + CommandOptions m_options; }; -// FIXME: "script-type" needs to have its contents determined dynamically, so somebody can add a new scripting -// language to lldb and have it pickable here without having to change this enumeration by hand and rebuild lldb proper. +// FIXME: "script-type" needs to have its contents determined dynamically, so +// somebody can add a new scripting +// language to lldb and have it pickable here without having to change this +// enumeration by hand and rebuild lldb proper. -static OptionEnumValueElement -g_script_option_enumeration[4] = -{ - { eScriptLanguageNone, "command", "Commands are in the lldb command interpreter language"}, - { eScriptLanguagePython, "python", "Commands are in the Python language."}, - { eSortOrderByName, "default-script", "Commands are in the default scripting language."}, - { 0, nullptr, nullptr } -}; +static OptionEnumValueElement g_script_option_enumeration[4] = { + {eScriptLanguageNone, "command", + "Commands are in the lldb command interpreter language"}, + {eScriptLanguagePython, "python", "Commands are in the Python language."}, + {eSortOrderByName, "default-script", + "Commands are in the default scripting language."}, + {0, nullptr, nullptr}}; OptionDefinition -CommandObjectWatchpointCommandAdd::CommandOptions::g_option_table[] = -{ - // clang-format off + CommandObjectWatchpointCommandAdd::CommandOptions::g_option_table[] = { + // clang-format off {LLDB_OPT_SET_1, false, "one-liner", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner, "Specify a one-line watchpoint command inline. Be sure to surround it with quotes."}, {LLDB_OPT_SET_ALL, false, "stop-on-error", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Specify whether watchpoint command execution should terminate on error."}, {LLDB_OPT_SET_ALL, false, "script-type", 's', OptionParser::eRequiredArgument, nullptr, g_script_option_enumeration, 0, eArgTypeNone, "Specify the language for the commands - if none is specified, the lldb command interpreter will be used."}, {LLDB_OPT_SET_2, false, "python-function", 'F', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePythonFunction, "Give the name of a Python function to run as command for this watchpoint. Be sure to give a module name if appropriate."}, {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - // clang-format on + // clang-format on }; //------------------------------------------------------------------------- // CommandObjectWatchpointCommandDelete //------------------------------------------------------------------------- -class CommandObjectWatchpointCommandDelete : public CommandObjectParsed -{ +class CommandObjectWatchpointCommandDelete : public CommandObjectParsed { public: - CommandObjectWatchpointCommandDelete (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "delete", + CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "delete", "Delete the set of commands from a watchpoint.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData wp_id_arg; + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData wp_id_arg; - // Define the first (and only) variant of this arg. - wp_id_arg.arg_type = eArgTypeWatchpointID; - wp_id_arg.arg_repetition = eArgRepeatPlain; + // Define the first (and only) variant of this arg. + wp_id_arg.arg_type = eArgTypeWatchpointID; + wp_id_arg.arg_repetition = eArgRepeatPlain; - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (wp_id_arg); + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(wp_id_arg); - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } - ~CommandObjectWatchpointCommandDelete() override = default; + ~CommandObjectWatchpointCommandDelete() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no watchpoints from which to delete commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "watchpoints from which to delete commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError ("No watchpoints exist to have commands deleted"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist to have commands deleted"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - result.AppendError ("No watchpoint specified from which to delete the commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (command.GetArgumentCount() == 0) { + result.AppendError( + "No watchpoint specified from which to delete the commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::vector valid_wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, valid_wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } + std::vector valid_wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, + valid_wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } - result.SetStatus(eReturnStatusSuccessFinishNoResult); - const size_t count = valid_wp_ids.size(); - for (size_t i = 0; i < count; ++i) - { - uint32_t cur_wp_id = valid_wp_ids.at (i); - if (cur_wp_id != LLDB_INVALID_WATCH_ID) - { - Watchpoint *wp = target->GetWatchpointList().FindByID (cur_wp_id).get(); - if (wp) - wp->ClearCallback(); - } - else - { - result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", - cur_wp_id); - result.SetStatus (eReturnStatusFailed); - return false; - } - } - return result.Succeeded(); + result.SetStatus(eReturnStatusSuccessFinishNoResult); + const size_t count = valid_wp_ids.size(); + for (size_t i = 0; i < count; ++i) { + uint32_t cur_wp_id = valid_wp_ids.at(i); + if (cur_wp_id != LLDB_INVALID_WATCH_ID) { + Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); + if (wp) + wp->ClearCallback(); + } else { + result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id); + result.SetStatus(eReturnStatusFailed); + return false; + } } + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectWatchpointCommandList //------------------------------------------------------------------------- -class CommandObjectWatchpointCommandList : public CommandObjectParsed -{ +class CommandObjectWatchpointCommandList : public CommandObjectParsed { public: - CommandObjectWatchpointCommandList (CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, - "list", - "List the script or set of commands to be executed when the watchpoint is hit.", - nullptr) - { - CommandArgumentEntry arg; - CommandArgumentData wp_id_arg; - - // Define the first (and only) variant of this arg. - wp_id_arg.arg_type = eArgTypeWatchpointID; - wp_id_arg.arg_repetition = eArgRepeatPlain; - - // There is only one variant this argument could be; put it into the argument entry. - arg.push_back (wp_id_arg); - - // Push the data for the first argument into the m_arguments vector. - m_arguments.push_back (arg); - } + CommandObjectWatchpointCommandList(CommandInterpreter &interpreter) + : CommandObjectParsed(interpreter, "list", "List the script or set of " + "commands to be executed when " + "the watchpoint is hit.", + nullptr) { + CommandArgumentEntry arg; + CommandArgumentData wp_id_arg; + + // Define the first (and only) variant of this arg. + wp_id_arg.arg_type = eArgTypeWatchpointID; + wp_id_arg.arg_repetition = eArgRepeatPlain; + + // There is only one variant this argument could be; put it into the + // argument entry. + arg.push_back(wp_id_arg); - ~CommandObjectWatchpointCommandList() override = default; + // Push the data for the first argument into the m_arguments vector. + m_arguments.push_back(arg); + } + + ~CommandObjectWatchpointCommandList() override = default; protected: - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); - - if (target == nullptr) - { - result.AppendError ("There is not a current executable; there are no watchpoints for which to list commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + bool DoExecute(Args &command, CommandReturnObject &result) override { + Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); + + if (target == nullptr) { + result.AppendError("There is not a current executable; there are no " + "watchpoints for which to list commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - const WatchpointList &watchpoints = target->GetWatchpointList(); - size_t num_watchpoints = watchpoints.GetSize(); + const WatchpointList &watchpoints = target->GetWatchpointList(); + size_t num_watchpoints = watchpoints.GetSize(); - if (num_watchpoints == 0) - { - result.AppendError ("No watchpoints exist for which to list commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (num_watchpoints == 0) { + result.AppendError("No watchpoints exist for which to list commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - if (command.GetArgumentCount() == 0) - { - result.AppendError ("No watchpoint specified for which to list the commands"); - result.SetStatus (eReturnStatusFailed); - return false; - } + if (command.GetArgumentCount() == 0) { + result.AppendError( + "No watchpoint specified for which to list the commands"); + result.SetStatus(eReturnStatusFailed); + return false; + } - std::vector valid_wp_ids; - if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, valid_wp_ids)) - { - result.AppendError("Invalid watchpoints specification."); - result.SetStatus(eReturnStatusFailed); - return false; - } + std::vector valid_wp_ids; + if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, + valid_wp_ids)) { + result.AppendError("Invalid watchpoints specification."); + result.SetStatus(eReturnStatusFailed); + return false; + } - result.SetStatus(eReturnStatusSuccessFinishNoResult); - const size_t count = valid_wp_ids.size(); - for (size_t i = 0; i < count; ++i) - { - uint32_t cur_wp_id = valid_wp_ids.at (i); - if (cur_wp_id != LLDB_INVALID_WATCH_ID) - { - Watchpoint *wp = target->GetWatchpointList().FindByID (cur_wp_id).get(); - - if (wp) - { - const WatchpointOptions *wp_options = wp->GetOptions(); - if (wp_options) - { - // Get the callback baton associated with the current watchpoint. - const Baton *baton = wp_options->GetBaton(); - if (baton) - { - result.GetOutputStream().Printf ("Watchpoint %u:\n", cur_wp_id); - result.GetOutputStream().IndentMore (); - baton->GetDescription(&result.GetOutputStream(), eDescriptionLevelFull); - result.GetOutputStream().IndentLess (); - } - else - { - result.AppendMessageWithFormat ("Watchpoint %u does not have an associated command.\n", - cur_wp_id); - } - } - result.SetStatus (eReturnStatusSuccessFinishResult); - } - else - { - result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id); - result.SetStatus (eReturnStatusFailed); - } + result.SetStatus(eReturnStatusSuccessFinishNoResult); + const size_t count = valid_wp_ids.size(); + for (size_t i = 0; i < count; ++i) { + uint32_t cur_wp_id = valid_wp_ids.at(i); + if (cur_wp_id != LLDB_INVALID_WATCH_ID) { + Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); + + if (wp) { + const WatchpointOptions *wp_options = wp->GetOptions(); + if (wp_options) { + // Get the callback baton associated with the current watchpoint. + const Baton *baton = wp_options->GetBaton(); + if (baton) { + result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id); + result.GetOutputStream().IndentMore(); + baton->GetDescription(&result.GetOutputStream(), + eDescriptionLevelFull); + result.GetOutputStream().IndentLess(); + } else { + result.AppendMessageWithFormat( + "Watchpoint %u does not have an associated command.\n", + cur_wp_id); } + } + result.SetStatus(eReturnStatusSuccessFinishResult); + } else { + result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", + cur_wp_id); + result.SetStatus(eReturnStatusFailed); } - - return result.Succeeded(); + } } + + return result.Succeeded(); + } }; //------------------------------------------------------------------------- // CommandObjectWatchpointCommand //------------------------------------------------------------------------- -CommandObjectWatchpointCommand::CommandObjectWatchpointCommand(CommandInterpreter &interpreter) - : CommandObjectMultiword(interpreter, "command", "Commands for adding, removing and examining LLDB commands " - "executed when the watchpoint is hit (watchpoint 'commmands').", - "command [] ") -{ - CommandObjectSP add_command_object (new CommandObjectWatchpointCommandAdd (interpreter)); - CommandObjectSP delete_command_object (new CommandObjectWatchpointCommandDelete (interpreter)); - CommandObjectSP list_command_object (new CommandObjectWatchpointCommandList (interpreter)); - - add_command_object->SetCommandName ("watchpoint command add"); - delete_command_object->SetCommandName ("watchpoint command delete"); - list_command_object->SetCommandName ("watchpoint command list"); - - LoadSubCommand ("add", add_command_object); - LoadSubCommand ("delete", delete_command_object); - LoadSubCommand ("list", list_command_object); +CommandObjectWatchpointCommand::CommandObjectWatchpointCommand( + CommandInterpreter &interpreter) + : CommandObjectMultiword( + interpreter, "command", + "Commands for adding, removing and examining LLDB commands " + "executed when the watchpoint is hit (watchpoint 'commmands').", + "command [] ") { + CommandObjectSP add_command_object( + new CommandObjectWatchpointCommandAdd(interpreter)); + CommandObjectSP delete_command_object( + new CommandObjectWatchpointCommandDelete(interpreter)); + CommandObjectSP list_command_object( + new CommandObjectWatchpointCommandList(interpreter)); + + add_command_object->SetCommandName("watchpoint command add"); + delete_command_object->SetCommandName("watchpoint command delete"); + list_command_object->SetCommandName("watchpoint command list"); + + LoadSubCommand("add", add_command_object); + LoadSubCommand("delete", delete_command_object); + LoadSubCommand("list", list_command_object); } CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default; diff --git a/lldb/source/Commands/CommandObjectWatchpointCommand.h b/lldb/source/Commands/CommandObjectWatchpointCommand.h index d77b32a2fd4..63152f2f68a 100644 --- a/lldb/source/Commands/CommandObjectWatchpointCommand.h +++ b/lldb/source/Commands/CommandObjectWatchpointCommand.h @@ -16,10 +16,9 @@ // Other libraries and framework includes // Project includes -#include "lldb/lldb-types.h" -#include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/CommandObjectMultiword.h" - +#include "lldb/Interpreter/Options.h" +#include "lldb/lldb-types.h" namespace lldb_private { @@ -27,12 +26,11 @@ namespace lldb_private { // CommandObjectMultiwordWatchpoint //------------------------------------------------------------------------- -class CommandObjectWatchpointCommand : public CommandObjectMultiword -{ +class CommandObjectWatchpointCommand : public CommandObjectMultiword { public: - CommandObjectWatchpointCommand (CommandInterpreter &interpreter); + CommandObjectWatchpointCommand(CommandInterpreter &interpreter); - ~CommandObjectWatchpointCommand() override; + ~CommandObjectWatchpointCommand() override; }; } // namespace lldb_private diff --git a/lldb/source/Core/Address.cpp b/lldb/source/Core/Address.cpp index 2ef5bbee836..6933aba2d07 100644 --- a/lldb/source/Core/Address.cpp +++ b/lldb/source/Core/Address.cpp @@ -19,1108 +19,963 @@ #include "lldb/Core/Section.h" #include "lldb/Symbol/Block.h" #include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolVendor.h" #include "lldb/Symbol/Variable.h" #include "lldb/Symbol/VariableList.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/Target.h" -#include "lldb/Symbol/SymbolVendor.h" using namespace lldb; using namespace lldb_private; -static size_t -ReadBytes (ExecutionContextScope *exe_scope, const Address &address, void *dst, size_t dst_len) -{ - if (exe_scope == nullptr) - return 0; - - TargetSP target_sp (exe_scope->CalculateTarget()); - if (target_sp) - { - Error error; - bool prefer_file_cache = false; - return target_sp->ReadMemory (address, prefer_file_cache, dst, dst_len, error); - } +static size_t ReadBytes(ExecutionContextScope *exe_scope, + const Address &address, void *dst, size_t dst_len) { + if (exe_scope == nullptr) return 0; -} -static bool -GetByteOrderAndAddressSize (ExecutionContextScope *exe_scope, const Address &address, ByteOrder& byte_order, uint32_t& addr_size) -{ - byte_order = eByteOrderInvalid; - addr_size = 0; - if (exe_scope == nullptr) - return false; - - TargetSP target_sp (exe_scope->CalculateTarget()); - if (target_sp) - { - byte_order = target_sp->GetArchitecture().GetByteOrder(); - addr_size = target_sp->GetArchitecture().GetAddressByteSize(); - } + TargetSP target_sp(exe_scope->CalculateTarget()); + if (target_sp) { + Error error; + bool prefer_file_cache = false; + return target_sp->ReadMemory(address, prefer_file_cache, dst, dst_len, + error); + } + return 0; +} + +static bool GetByteOrderAndAddressSize(ExecutionContextScope *exe_scope, + const Address &address, + ByteOrder &byte_order, + uint32_t &addr_size) { + byte_order = eByteOrderInvalid; + addr_size = 0; + if (exe_scope == nullptr) + return false; - if (byte_order == eByteOrderInvalid || addr_size == 0) - { - ModuleSP module_sp (address.GetModule()); - if (module_sp) - { - byte_order = module_sp->GetArchitecture().GetByteOrder(); - addr_size = module_sp->GetArchitecture().GetAddressByteSize(); - } - } - return byte_order != eByteOrderInvalid && addr_size != 0; -} + TargetSP target_sp(exe_scope->CalculateTarget()); + if (target_sp) { + byte_order = target_sp->GetArchitecture().GetByteOrder(); + addr_size = target_sp->GetArchitecture().GetAddressByteSize(); + } -static uint64_t -ReadUIntMax64 (ExecutionContextScope *exe_scope, const Address &address, uint32_t byte_size, bool &success) -{ - uint64_t uval64 = 0; - if (exe_scope == nullptr || byte_size > sizeof(uint64_t)) - { - success = false; - return 0; + if (byte_order == eByteOrderInvalid || addr_size == 0) { + ModuleSP module_sp(address.GetModule()); + if (module_sp) { + byte_order = module_sp->GetArchitecture().GetByteOrder(); + addr_size = module_sp->GetArchitecture().GetAddressByteSize(); } - uint64_t buf = 0; - - success = ReadBytes (exe_scope, address, &buf, byte_size) == byte_size; - if (success) - { - ByteOrder byte_order = eByteOrderInvalid; - uint32_t addr_size = 0; - if (GetByteOrderAndAddressSize (exe_scope, address, byte_order, addr_size)) - { - DataExtractor data (&buf, sizeof(buf), byte_order, addr_size); - lldb::offset_t offset = 0; - uval64 = data.GetU64(&offset); - } - else - success = false; - } - return uval64; + } + return byte_order != eByteOrderInvalid && addr_size != 0; } -static bool -ReadAddress (ExecutionContextScope *exe_scope, const Address &address, uint32_t pointer_size, Address &deref_so_addr) -{ - if (exe_scope == nullptr) - return false; - - bool success = false; - addr_t deref_addr = ReadUIntMax64 (exe_scope, address, pointer_size, success); - if (success) - { - ExecutionContext exe_ctx; - exe_scope->CalculateExecutionContext(exe_ctx); - // If we have any sections that are loaded, try and resolve using the - // section load list - Target *target = exe_ctx.GetTargetPtr(); - if (target && !target->GetSectionLoadList().IsEmpty()) - { - if (target->GetSectionLoadList().ResolveLoadAddress (deref_addr, deref_so_addr)) - return true; - } - else - { - // If we were not running, yet able to read an integer, we must - // have a module - ModuleSP module_sp (address.GetModule()); - - assert (module_sp); - if (module_sp->ResolveFileAddress(deref_addr, deref_so_addr)) - return true; - } +static uint64_t ReadUIntMax64(ExecutionContextScope *exe_scope, + const Address &address, uint32_t byte_size, + bool &success) { + uint64_t uval64 = 0; + if (exe_scope == nullptr || byte_size > sizeof(uint64_t)) { + success = false; + return 0; + } + uint64_t buf = 0; + + success = ReadBytes(exe_scope, address, &buf, byte_size) == byte_size; + if (success) { + ByteOrder byte_order = eByteOrderInvalid; + uint32_t addr_size = 0; + if (GetByteOrderAndAddressSize(exe_scope, address, byte_order, addr_size)) { + DataExtractor data(&buf, sizeof(buf), byte_order, addr_size); + lldb::offset_t offset = 0; + uval64 = data.GetU64(&offset); + } else + success = false; + } + return uval64; +} + +static bool ReadAddress(ExecutionContextScope *exe_scope, + const Address &address, uint32_t pointer_size, + Address &deref_so_addr) { + if (exe_scope == nullptr) + return false; - // We couldn't make "deref_addr" into a section offset value, but we were - // able to read the address, so we return a section offset address with - // no section and "deref_addr" as the offset (address). - deref_so_addr.SetRawAddress(deref_addr); + bool success = false; + addr_t deref_addr = ReadUIntMax64(exe_scope, address, pointer_size, success); + if (success) { + ExecutionContext exe_ctx; + exe_scope->CalculateExecutionContext(exe_ctx); + // If we have any sections that are loaded, try and resolve using the + // section load list + Target *target = exe_ctx.GetTargetPtr(); + if (target && !target->GetSectionLoadList().IsEmpty()) { + if (target->GetSectionLoadList().ResolveLoadAddress(deref_addr, + deref_so_addr)) return true; - } - return false; -} + } else { + // If we were not running, yet able to read an integer, we must + // have a module + ModuleSP module_sp(address.GetModule()); -static bool -DumpUInt (ExecutionContextScope *exe_scope, const Address &address, uint32_t byte_size, Stream* strm) -{ - if (exe_scope == nullptr || byte_size == 0) - return 0; - std::vector buf(byte_size, 0); - - if (ReadBytes (exe_scope, address, &buf[0], buf.size()) == buf.size()) - { - ByteOrder byte_order = eByteOrderInvalid; - uint32_t addr_size = 0; - if (GetByteOrderAndAddressSize (exe_scope, address, byte_order, addr_size)) - { - DataExtractor data (&buf.front(), buf.size(), byte_order, addr_size); - - data.Dump (strm, - 0, // Start offset in "data" - eFormatHex, // Print as characters - buf.size(), // Size of item - 1, // Items count - UINT32_MAX, // num per line - LLDB_INVALID_ADDRESS,// base address - 0, // bitfield bit size - 0); // bitfield bit offset - - return true; - } + assert(module_sp); + if (module_sp->ResolveFileAddress(deref_addr, deref_so_addr)) + return true; } - return false; -} -static size_t -ReadCStringFromMemory (ExecutionContextScope *exe_scope, const Address &address, Stream *strm) -{ - if (exe_scope == nullptr) - return 0; - const size_t k_buf_len = 256; - char buf[k_buf_len+1]; - buf[k_buf_len] = '\0'; // NULL terminate - - // Byte order and address size don't matter for C string dumping.. - DataExtractor data (buf, sizeof(buf), endian::InlHostByteOrder(), 4); - size_t total_len = 0; - size_t bytes_read; - Address curr_address(address); - strm->PutChar ('"'); - while ((bytes_read = ReadBytes (exe_scope, curr_address, buf, k_buf_len)) > 0) - { - size_t len = strlen(buf); - if (len == 0) - break; - if (len > bytes_read) - len = bytes_read; - - data.Dump (strm, - 0, // Start offset in "data" - eFormatChar, // Print as characters - 1, // Size of item (1 byte for a char!) - len, // How many bytes to print? - UINT32_MAX, // num per line - LLDB_INVALID_ADDRESS,// base address - 0, // bitfield bit size - - 0); // bitfield bit offset - - total_len += bytes_read; - - if (len < k_buf_len) - break; - curr_address.SetOffset (curr_address.GetOffset() + bytes_read); - } - strm->PutChar ('"'); - return total_len; + // We couldn't make "deref_addr" into a section offset value, but we were + // able to read the address, so we return a section offset address with + // no section and "deref_addr" as the offset (address). + deref_so_addr.SetRawAddress(deref_addr); + return true; + } + return false; } -Address::Address (lldb::addr_t abs_addr) : - m_section_wp (), - m_offset (abs_addr) -{ -} +static bool DumpUInt(ExecutionContextScope *exe_scope, const Address &address, + uint32_t byte_size, Stream *strm) { + if (exe_scope == nullptr || byte_size == 0) + return 0; + std::vector buf(byte_size, 0); -Address::Address (addr_t address, const SectionList *section_list) : - m_section_wp (), - m_offset (LLDB_INVALID_ADDRESS) -{ - ResolveAddressUsingFileSections(address, section_list); -} + if (ReadBytes(exe_scope, address, &buf[0], buf.size()) == buf.size()) { + ByteOrder byte_order = eByteOrderInvalid; + uint32_t addr_size = 0; + if (GetByteOrderAndAddressSize(exe_scope, address, byte_order, addr_size)) { + DataExtractor data(&buf.front(), buf.size(), byte_order, addr_size); -const Address& -Address::operator= (const Address& rhs) -{ - if (this != &rhs) - { - m_section_wp = rhs.m_section_wp; - m_offset = rhs.m_offset; - } - return *this; -} + data.Dump(strm, + 0, // Start offset in "data" + eFormatHex, // Print as characters + buf.size(), // Size of item + 1, // Items count + UINT32_MAX, // num per line + LLDB_INVALID_ADDRESS, // base address + 0, // bitfield bit size + 0); // bitfield bit offset -bool -Address::ResolveAddressUsingFileSections (addr_t file_addr, const SectionList *section_list) -{ - if (section_list) - { - SectionSP section_sp (section_list->FindSectionContainingFileAddress(file_addr)); - m_section_wp = section_sp; - if (section_sp) - { - assert( section_sp->ContainsFileAddress(file_addr) ); - m_offset = file_addr - section_sp->GetFileAddress(); - return true; // Successfully transformed addr into a section offset address - } + return true; } - m_offset = file_addr; - return false; // Failed to resolve this address to a section offset value + } + return false; } -ModuleSP -Address::GetModule () const -{ - lldb::ModuleSP module_sp; - SectionSP section_sp (GetSection()); - if (section_sp) - module_sp = section_sp->GetModule(); - return module_sp; +static size_t ReadCStringFromMemory(ExecutionContextScope *exe_scope, + const Address &address, Stream *strm) { + if (exe_scope == nullptr) + return 0; + const size_t k_buf_len = 256; + char buf[k_buf_len + 1]; + buf[k_buf_len] = '\0'; // NULL terminate + + // Byte order and address size don't matter for C string dumping.. + DataExtractor data(buf, sizeof(buf), endian::InlHostByteOrder(), 4); + size_t total_len = 0; + size_t bytes_read; + Address curr_address(address); + strm->PutChar('"'); + while ((bytes_read = ReadBytes(exe_scope, curr_address, buf, k_buf_len)) > + 0) { + size_t len = strlen(buf); + if (len == 0) + break; + if (len > bytes_read) + len = bytes_read; + + data.Dump(strm, + 0, // Start offset in "data" + eFormatChar, // Print as characters + 1, // Size of item (1 byte for a char!) + len, // How many bytes to print? + UINT32_MAX, // num per line + LLDB_INVALID_ADDRESS, // base address + 0, // bitfield bit size + + 0); // bitfield bit offset + + total_len += bytes_read; + + if (len < k_buf_len) + break; + curr_address.SetOffset(curr_address.GetOffset() + bytes_read); + } + strm->PutChar('"'); + return total_len; +} + +Address::Address(lldb::addr_t abs_addr) : m_section_wp(), m_offset(abs_addr) {} + +Address::Address(addr_t address, const SectionList *section_list) + : m_section_wp(), m_offset(LLDB_INVALID_ADDRESS) { + ResolveAddressUsingFileSections(address, section_list); +} + +const Address &Address::operator=(const Address &rhs) { + if (this != &rhs) { + m_section_wp = rhs.m_section_wp; + m_offset = rhs.m_offset; + } + return *this; +} + +bool Address::ResolveAddressUsingFileSections(addr_t file_addr, + const SectionList *section_list) { + if (section_list) { + SectionSP section_sp( + section_list->FindSectionContainingFileAddress(file_addr)); + m_section_wp = section_sp; + if (section_sp) { + assert(section_sp->ContainsFileAddress(file_addr)); + m_offset = file_addr - section_sp->GetFileAddress(); + return true; // Successfully transformed addr into a section offset + // address + } + } + m_offset = file_addr; + return false; // Failed to resolve this address to a section offset value +} + +ModuleSP Address::GetModule() const { + lldb::ModuleSP module_sp; + SectionSP section_sp(GetSection()); + if (section_sp) + module_sp = section_sp->GetModule(); + return module_sp; +} + +addr_t Address::GetFileAddress() const { + SectionSP section_sp(GetSection()); + if (section_sp) { + addr_t sect_file_addr = section_sp->GetFileAddress(); + if (sect_file_addr == LLDB_INVALID_ADDRESS) { + // Section isn't resolved, we can't return a valid file address + return LLDB_INVALID_ADDRESS; + } + // We have a valid file range, so we can return the file based + // address by adding the file base address to our offset + return sect_file_addr + m_offset; + } else if (SectionWasDeletedPrivate()) { + // Used to have a valid section but it got deleted so the + // offset doesn't mean anything without the section + return LLDB_INVALID_ADDRESS; + } + // No section, we just return the offset since it is the value in this case + return m_offset; } -addr_t -Address::GetFileAddress () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - addr_t sect_file_addr = section_sp->GetFileAddress(); - if (sect_file_addr == LLDB_INVALID_ADDRESS) - { - // Section isn't resolved, we can't return a valid file address - return LLDB_INVALID_ADDRESS; - } +addr_t Address::GetLoadAddress(Target *target) const { + SectionSP section_sp(GetSection()); + if (section_sp) { + if (target) { + addr_t sect_load_addr = section_sp->GetLoadBaseAddress(target); + + if (sect_load_addr != LLDB_INVALID_ADDRESS) { // We have a valid file range, so we can return the file based // address by adding the file base address to our offset - return sect_file_addr + m_offset; - } - else if (SectionWasDeletedPrivate()) - { - // Used to have a valid section but it got deleted so the - // offset doesn't mean anything without the section - return LLDB_INVALID_ADDRESS; + return sect_load_addr + m_offset; + } } - // No section, we just return the offset since it is the value in this case + } else if (SectionWasDeletedPrivate()) { + // Used to have a valid section but it got deleted so the + // offset doesn't mean anything without the section + return LLDB_INVALID_ADDRESS; + } else { + // We don't have a section so the offset is the load address return m_offset; + } + // The section isn't resolved or an invalid target was passed in + // so we can't return a valid load address. + return LLDB_INVALID_ADDRESS; } -addr_t -Address::GetLoadAddress (Target *target) const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - if (target) - { - addr_t sect_load_addr = section_sp->GetLoadBaseAddress (target); - - if (sect_load_addr != LLDB_INVALID_ADDRESS) - { - // We have a valid file range, so we can return the file based - // address by adding the file base address to our offset - return sect_load_addr + m_offset; - } - } - } - else if (SectionWasDeletedPrivate()) - { - // Used to have a valid section but it got deleted so the - // offset doesn't mean anything without the section - return LLDB_INVALID_ADDRESS; - } - else - { - // We don't have a section so the offset is the load address - return m_offset; - } - // The section isn't resolved or an invalid target was passed in - // so we can't return a valid load address. - return LLDB_INVALID_ADDRESS; -} +addr_t Address::GetCallableLoadAddress(Target *target, bool is_indirect) const { + addr_t code_addr = LLDB_INVALID_ADDRESS; -addr_t -Address::GetCallableLoadAddress (Target *target, bool is_indirect) const -{ - addr_t code_addr = LLDB_INVALID_ADDRESS; - - if (is_indirect && target) - { - ProcessSP processSP = target->GetProcessSP(); - Error error; - if (processSP) - { - code_addr = processSP->ResolveIndirectFunction(this, error); - if (!error.Success()) - code_addr = LLDB_INVALID_ADDRESS; - } - } - else - { - code_addr = GetLoadAddress (target); + if (is_indirect && target) { + ProcessSP processSP = target->GetProcessSP(); + Error error; + if (processSP) { + code_addr = processSP->ResolveIndirectFunction(this, error); + if (!error.Success()) + code_addr = LLDB_INVALID_ADDRESS; } - - if (code_addr == LLDB_INVALID_ADDRESS) - return code_addr; - - if (target) - return target->GetCallableLoadAddress (code_addr, GetAddressClass()); + } else { + code_addr = GetLoadAddress(target); + } + + if (code_addr == LLDB_INVALID_ADDRESS) return code_addr; -} -bool -Address::SetCallableLoadAddress (lldb::addr_t load_addr, Target *target) -{ - if (SetLoadAddress (load_addr, target)) - { - if (target) - m_offset = target->GetCallableLoadAddress(m_offset, GetAddressClass()); - return true; - } - return false; + if (target) + return target->GetCallableLoadAddress(code_addr, GetAddressClass()); + return code_addr; } -addr_t -Address::GetOpcodeLoadAddress (Target *target, AddressClass addr_class) const -{ - addr_t code_addr = GetLoadAddress (target); - if (code_addr != LLDB_INVALID_ADDRESS) - { - if (addr_class == eAddressClassInvalid) - addr_class = GetAddressClass(); - code_addr = target->GetOpcodeLoadAddress (code_addr, addr_class); - } - return code_addr; +bool Address::SetCallableLoadAddress(lldb::addr_t load_addr, Target *target) { + if (SetLoadAddress(load_addr, target)) { + if (target) + m_offset = target->GetCallableLoadAddress(m_offset, GetAddressClass()); + return true; + } + return false; } -bool -Address::SetOpcodeLoadAddress (lldb::addr_t load_addr, Target *target, AddressClass addr_class) -{ - if (SetLoadAddress (load_addr, target)) - { - if (target) - { - if (addr_class == eAddressClassInvalid) - addr_class = GetAddressClass(); - m_offset = target->GetOpcodeLoadAddress (m_offset, addr_class); - } - return true; - } - return false; +addr_t Address::GetOpcodeLoadAddress(Target *target, + AddressClass addr_class) const { + addr_t code_addr = GetLoadAddress(target); + if (code_addr != LLDB_INVALID_ADDRESS) { + if (addr_class == eAddressClassInvalid) + addr_class = GetAddressClass(); + code_addr = target->GetOpcodeLoadAddress(code_addr, addr_class); + } + return code_addr; } -bool -Address::Dump (Stream *s, ExecutionContextScope *exe_scope, DumpStyle style, DumpStyle fallback_style, uint32_t addr_size) const -{ - // If the section was nullptr, only load address is going to work unless we are - // trying to deref a pointer - SectionSP section_sp (GetSection()); - if (!section_sp && style != DumpStyleResolvedPointerDescription) - style = DumpStyleLoadAddress; - - ExecutionContext exe_ctx (exe_scope); - Target *target = exe_ctx.GetTargetPtr(); - // If addr_byte_size is UINT32_MAX, then determine the correct address - // byte size for the process or default to the size of addr_t - if (addr_size == UINT32_MAX) - { - if (target) - addr_size = target->GetArchitecture().GetAddressByteSize (); - else - addr_size = sizeof(addr_t); +bool Address::SetOpcodeLoadAddress(lldb::addr_t load_addr, Target *target, + AddressClass addr_class) { + if (SetLoadAddress(load_addr, target)) { + if (target) { + if (addr_class == eAddressClassInvalid) + addr_class = GetAddressClass(); + m_offset = target->GetOpcodeLoadAddress(m_offset, addr_class); } + return true; + } + return false; +} + +bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style, + DumpStyle fallback_style, uint32_t addr_size) const { + // If the section was nullptr, only load address is going to work unless we + // are + // trying to deref a pointer + SectionSP section_sp(GetSection()); + if (!section_sp && style != DumpStyleResolvedPointerDescription) + style = DumpStyleLoadAddress; + + ExecutionContext exe_ctx(exe_scope); + Target *target = exe_ctx.GetTargetPtr(); + // If addr_byte_size is UINT32_MAX, then determine the correct address + // byte size for the process or default to the size of addr_t + if (addr_size == UINT32_MAX) { + if (target) + addr_size = target->GetArchitecture().GetAddressByteSize(); + else + addr_size = sizeof(addr_t); + } - Address so_addr; - switch (style) - { - case DumpStyleInvalid: - return false; - - case DumpStyleSectionNameOffset: - if (section_sp) - { - section_sp->DumpName(s); - s->Printf (" + %" PRIu64, m_offset); - } - else - { - s->Address(m_offset, addr_size); - } - break; - - case DumpStyleSectionPointerOffset: - s->Printf("(Section *)%p + ", static_cast(section_sp.get())); - s->Address(m_offset, addr_size); - break; - - case DumpStyleModuleWithFileAddress: - if (section_sp) - { - ModuleSP module_sp = section_sp->GetModule(); - if (module_sp) - s->Printf("%s[", module_sp->GetFileSpec().GetFilename().AsCString("")); - else - s->Printf("%s[",""); - } - LLVM_FALLTHROUGH; - case DumpStyleFileAddress: - { - addr_t file_addr = GetFileAddress(); - if (file_addr == LLDB_INVALID_ADDRESS) - { - if (fallback_style != DumpStyleInvalid) - return Dump (s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); - return false; - } - s->Address (file_addr, addr_size); - if (style == DumpStyleModuleWithFileAddress && section_sp) - s->PutChar(']'); - } - break; - - case DumpStyleLoadAddress: - { - addr_t load_addr = GetLoadAddress (target); - - /* - * MIPS: - * Display address in compressed form for MIPS16 or microMIPS - * if the address belongs to eAddressClassCodeAlternateISA. - */ - if (target) - { - const llvm::Triple::ArchType llvm_arch = target->GetArchitecture().GetMachine(); - if (llvm_arch == llvm::Triple::mips || llvm_arch == llvm::Triple::mipsel - || llvm_arch == llvm::Triple::mips64 || llvm_arch == llvm::Triple::mips64el) - load_addr = GetCallableLoadAddress (target); - } + Address so_addr; + switch (style) { + case DumpStyleInvalid: + return false; - if (load_addr == LLDB_INVALID_ADDRESS) - { - if (fallback_style != DumpStyleInvalid) - return Dump (s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); - return false; - } - s->Address (load_addr, addr_size); - } - break; - - case DumpStyleResolvedDescription: - case DumpStyleResolvedDescriptionNoModule: - case DumpStyleResolvedDescriptionNoFunctionArguments: - case DumpStyleNoFunctionName: - if (IsSectionOffset()) - { - uint32_t pointer_size = 4; - ModuleSP module_sp (GetModule()); - if (target) - pointer_size = target->GetArchitecture().GetAddressByteSize(); - else if (module_sp) - pointer_size = module_sp->GetArchitecture().GetAddressByteSize(); - - bool showed_info = false; - if (section_sp) - { - SectionType sect_type = section_sp->GetType(); - switch (sect_type) - { - case eSectionTypeData: - if (module_sp) - { - SymbolVendor *sym_vendor = module_sp->GetSymbolVendor(); - if (sym_vendor) - { - Symtab *symtab = sym_vendor->GetSymtab(); - if (symtab) - { - const addr_t file_Addr = GetFileAddress(); - Symbol *symbol = symtab->FindSymbolContainingFileAddress (file_Addr); - if (symbol) - { - const char *symbol_name = symbol->GetName().AsCString(); - if (symbol_name) - { - s->PutCString(symbol_name); - addr_t delta = file_Addr - symbol->GetAddressRef().GetFileAddress(); - if (delta) - s->Printf(" + %" PRIu64, delta); - showed_info = true; - } - } - } - } - } - break; - - case eSectionTypeDataCString: - // Read the C string from memory and display it + case DumpStyleSectionNameOffset: + if (section_sp) { + section_sp->DumpName(s); + s->Printf(" + %" PRIu64, m_offset); + } else { + s->Address(m_offset, addr_size); + } + break; + + case DumpStyleSectionPointerOffset: + s->Printf("(Section *)%p + ", static_cast(section_sp.get())); + s->Address(m_offset, addr_size); + break; + + case DumpStyleModuleWithFileAddress: + if (section_sp) { + ModuleSP module_sp = section_sp->GetModule(); + if (module_sp) + s->Printf("%s[", module_sp->GetFileSpec().GetFilename().AsCString( + "")); + else + s->Printf("%s[", ""); + } + LLVM_FALLTHROUGH; + case DumpStyleFileAddress: { + addr_t file_addr = GetFileAddress(); + if (file_addr == LLDB_INVALID_ADDRESS) { + if (fallback_style != DumpStyleInvalid) + return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); + return false; + } + s->Address(file_addr, addr_size); + if (style == DumpStyleModuleWithFileAddress && section_sp) + s->PutChar(']'); + } break; + + case DumpStyleLoadAddress: { + addr_t load_addr = GetLoadAddress(target); + + /* + * MIPS: + * Display address in compressed form for MIPS16 or microMIPS + * if the address belongs to eAddressClassCodeAlternateISA. + */ + if (target) { + const llvm::Triple::ArchType llvm_arch = + target->GetArchitecture().GetMachine(); + if (llvm_arch == llvm::Triple::mips || + llvm_arch == llvm::Triple::mipsel || + llvm_arch == llvm::Triple::mips64 || + llvm_arch == llvm::Triple::mips64el) + load_addr = GetCallableLoadAddress(target); + } + + if (load_addr == LLDB_INVALID_ADDRESS) { + if (fallback_style != DumpStyleInvalid) + return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); + return false; + } + s->Address(load_addr, addr_size); + } break; + + case DumpStyleResolvedDescription: + case DumpStyleResolvedDescriptionNoModule: + case DumpStyleResolvedDescriptionNoFunctionArguments: + case DumpStyleNoFunctionName: + if (IsSectionOffset()) { + uint32_t pointer_size = 4; + ModuleSP module_sp(GetModule()); + if (target) + pointer_size = target->GetArchitecture().GetAddressByteSize(); + else if (module_sp) + pointer_size = module_sp->GetArchitecture().GetAddressByteSize(); + + bool showed_info = false; + if (section_sp) { + SectionType sect_type = section_sp->GetType(); + switch (sect_type) { + case eSectionTypeData: + if (module_sp) { + SymbolVendor *sym_vendor = module_sp->GetSymbolVendor(); + if (sym_vendor) { + Symtab *symtab = sym_vendor->GetSymtab(); + if (symtab) { + const addr_t file_Addr = GetFileAddress(); + Symbol *symbol = + symtab->FindSymbolContainingFileAddress(file_Addr); + if (symbol) { + const char *symbol_name = symbol->GetName().AsCString(); + if (symbol_name) { + s->PutCString(symbol_name); + addr_t delta = + file_Addr - symbol->GetAddressRef().GetFileAddress(); + if (delta) + s->Printf(" + %" PRIu64, delta); showed_info = true; - ReadCStringFromMemory (exe_scope, *this, s); - break; + } + } + } + } + } + break; + + case eSectionTypeDataCString: + // Read the C string from memory and display it + showed_info = true; + ReadCStringFromMemory(exe_scope, *this, s); + break; - case eSectionTypeDataCStringPointers: - if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) - { + case eSectionTypeDataCStringPointers: + if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) { #if VERBOSE_OUTPUT - s->PutCString("(char *)"); - so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, DumpStyleFileAddress); - s->PutCString(": "); + s->PutCString("(char *)"); + so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, + DumpStyleFileAddress); + s->PutCString(": "); #endif - showed_info = true; - ReadCStringFromMemory(exe_scope, so_addr, s); - } - break; - - case eSectionTypeDataObjCMessageRefs: - if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) - { - if (target && so_addr.IsSectionOffset()) - { - SymbolContext func_sc; - target->GetImages().ResolveSymbolContextForAddress(so_addr, - eSymbolContextEverything, - func_sc); - if (func_sc.function != nullptr || func_sc.symbol != nullptr) - { - showed_info = true; + showed_info = true; + ReadCStringFromMemory(exe_scope, so_addr, s); + } + break; + + case eSectionTypeDataObjCMessageRefs: + if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) { + if (target && so_addr.IsSectionOffset()) { + SymbolContext func_sc; + target->GetImages().ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, func_sc); + if (func_sc.function != nullptr || func_sc.symbol != nullptr) { + showed_info = true; #if VERBOSE_OUTPUT - s->PutCString ("(objc_msgref *) -> { (func*)"); - so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, DumpStyleFileAddress); + s->PutCString("(objc_msgref *) -> { (func*)"); + so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, + DumpStyleFileAddress); #else - s->PutCString ("{ "); + s->PutCString("{ "); #endif - Address cstr_addr(*this); - cstr_addr.SetOffset(cstr_addr.GetOffset() + pointer_size); - func_sc.DumpStopContext(s, exe_scope, so_addr, true, true, false, true, true); - if (ReadAddress(exe_scope, cstr_addr, pointer_size, so_addr)) - { + Address cstr_addr(*this); + cstr_addr.SetOffset(cstr_addr.GetOffset() + pointer_size); + func_sc.DumpStopContext(s, exe_scope, so_addr, true, true, + false, true, true); + if (ReadAddress(exe_scope, cstr_addr, pointer_size, so_addr)) { #if VERBOSE_OUTPUT - s->PutCString("), (char *)"); - so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, DumpStyleFileAddress); - s->PutCString(" ("); + s->PutCString("), (char *)"); + so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, + DumpStyleFileAddress); + s->PutCString(" ("); #else - s->PutCString(", "); + s->PutCString(", "); #endif - ReadCStringFromMemory (exe_scope, so_addr, s); - } + ReadCStringFromMemory(exe_scope, so_addr, s); + } #if VERBOSE_OUTPUT - s->PutCString(") }"); + s->PutCString(") }"); #else - s->PutCString(" }"); + s->PutCString(" }"); #endif - } - } - } - break; - - case eSectionTypeDataObjCCFStrings: - { - Address cfstring_data_addr(*this); - cfstring_data_addr.SetOffset(cfstring_data_addr.GetOffset() + (2 * pointer_size)); - if (ReadAddress (exe_scope, cfstring_data_addr, pointer_size, so_addr)) - { + } + } + } + break; + + case eSectionTypeDataObjCCFStrings: { + Address cfstring_data_addr(*this); + cfstring_data_addr.SetOffset(cfstring_data_addr.GetOffset() + + (2 * pointer_size)); + if (ReadAddress(exe_scope, cfstring_data_addr, pointer_size, + so_addr)) { #if VERBOSE_OUTPUT - s->PutCString("(CFString *) "); - cfstring_data_addr.Dump(s, exe_scope, DumpStyleLoadAddress, DumpStyleFileAddress); - s->PutCString(" -> @"); + s->PutCString("(CFString *) "); + cfstring_data_addr.Dump(s, exe_scope, DumpStyleLoadAddress, + DumpStyleFileAddress); + s->PutCString(" -> @"); #else - s->PutChar('@'); + s->PutChar('@'); #endif - if (so_addr.Dump(s, exe_scope, DumpStyleResolvedDescription)) - showed_info = true; - } - } - break; - - case eSectionTypeData4: - // Read the 4 byte data and display it - showed_info = true; - s->PutCString("(uint32_t) "); - DumpUInt (exe_scope, *this, 4, s); - break; - - case eSectionTypeData8: - // Read the 8 byte data and display it - showed_info = true; - s->PutCString("(uint64_t) "); - DumpUInt (exe_scope, *this, 8, s); - break; - - case eSectionTypeData16: - // Read the 16 byte data and display it - showed_info = true; - s->PutCString("(uint128_t) "); - DumpUInt (exe_scope, *this, 16, s); - break; - - case eSectionTypeDataPointers: - // Read the pointer data and display it - if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) - { - s->PutCString ("(void *)"); - so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, DumpStyleFileAddress); - - showed_info = true; - if (so_addr.IsSectionOffset()) - { - SymbolContext pointer_sc; - if (target) - { - target->GetImages().ResolveSymbolContextForAddress(so_addr, - eSymbolContextEverything, - pointer_sc); - if (pointer_sc.function != nullptr || pointer_sc.symbol != nullptr) - { - s->PutCString(": "); - pointer_sc.DumpStopContext(s, exe_scope, so_addr, true, false, false, true, true); - } - } - } - } - break; - - default: - break; + if (so_addr.Dump(s, exe_scope, DumpStyleResolvedDescription)) + showed_info = true; + } + } break; + + case eSectionTypeData4: + // Read the 4 byte data and display it + showed_info = true; + s->PutCString("(uint32_t) "); + DumpUInt(exe_scope, *this, 4, s); + break; + + case eSectionTypeData8: + // Read the 8 byte data and display it + showed_info = true; + s->PutCString("(uint64_t) "); + DumpUInt(exe_scope, *this, 8, s); + break; + + case eSectionTypeData16: + // Read the 16 byte data and display it + showed_info = true; + s->PutCString("(uint128_t) "); + DumpUInt(exe_scope, *this, 16, s); + break; + + case eSectionTypeDataPointers: + // Read the pointer data and display it + if (ReadAddress(exe_scope, *this, pointer_size, so_addr)) { + s->PutCString("(void *)"); + so_addr.Dump(s, exe_scope, DumpStyleLoadAddress, + DumpStyleFileAddress); + + showed_info = true; + if (so_addr.IsSectionOffset()) { + SymbolContext pointer_sc; + if (target) { + target->GetImages().ResolveSymbolContextForAddress( + so_addr, eSymbolContextEverything, pointer_sc); + if (pointer_sc.function != nullptr || + pointer_sc.symbol != nullptr) { + s->PutCString(": "); + pointer_sc.DumpStopContext(s, exe_scope, so_addr, true, false, + false, true, true); } + } } + } + break; - if (!showed_info) - { - if (module_sp) - { - SymbolContext sc; - module_sp->ResolveSymbolContextForAddress(*this, eSymbolContextEverything, sc); - if (sc.function || sc.symbol) - { - bool show_stop_context = true; - const bool show_module = (style == DumpStyleResolvedDescription); - const bool show_fullpaths = false; - const bool show_inlined_frames = true; - const bool show_function_arguments = (style != DumpStyleResolvedDescriptionNoFunctionArguments); - const bool show_function_name = (style != DumpStyleNoFunctionName); - if (sc.function == nullptr && sc.symbol != nullptr) - { - // If we have just a symbol make sure it is in the right section - if (sc.symbol->ValueIsAddress()) - { - if (sc.symbol->GetAddressRef().GetSection() != GetSection()) - { - // don't show the module if the symbol is a trampoline symbol - show_stop_context = false; - } - } - } - if (show_stop_context) - { - // We have a function or a symbol from the same - // sections as this address. - sc.DumpStopContext (s, - exe_scope, - *this, - show_fullpaths, - show_module, - show_inlined_frames, - show_function_arguments, - show_function_name); - } - else - { - // We found a symbol but it was in a different - // section so it isn't the symbol we should be - // showing, just show the section name + offset - Dump (s, exe_scope, DumpStyleSectionNameOffset); - } - } - } - } - } - else - { - if (fallback_style != DumpStyleInvalid) - return Dump (s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); - return false; + default: + break; } - break; - - case DumpStyleDetailedSymbolContext: - if (IsSectionOffset()) - { - ModuleSP module_sp (GetModule()); - if (module_sp) - { - SymbolContext sc; - module_sp->ResolveSymbolContextForAddress(*this, eSymbolContextEverything | eSymbolContextVariable, sc); - if (sc.symbol) - { - // If we have just a symbol make sure it is in the same section - // as our address. If it isn't, then we might have just found - // the last symbol that came before the address that we are - // looking up that has nothing to do with our address lookup. - if (sc.symbol->ValueIsAddress() && sc.symbol->GetAddressRef().GetSection() != GetSection()) - sc.symbol = nullptr; - } - sc.GetDescription(s, eDescriptionLevelBrief, target); - - if (sc.block) - { - bool can_create = true; - bool get_parent_variables = true; - bool stop_if_block_is_inlined_function = false; - VariableList variable_list; - sc.block->AppendVariables (can_create, - get_parent_variables, - stop_if_block_is_inlined_function, - [](Variable*) { return true; }, - &variable_list); - - const size_t num_variables = variable_list.GetSize(); - for (size_t var_idx = 0; var_idx < num_variables; ++var_idx) - { - Variable *var = variable_list.GetVariableAtIndex (var_idx).get(); - if (var && var->LocationIsValidForAddress (*this)) - { - s->Indent(); - s->Printf (" Variable: id = {0x%8.8" PRIx64 "}, name = \"%s\"", - var->GetID(), - var->GetName().GetCString()); - Type *type = var->GetType(); - if (type) - s->Printf(", type = \"%s\"", type->GetName().GetCString()); - else - s->PutCString(", type = "); - s->PutCString(", location = "); - var->DumpLocationForAddress(s, *this); - s->PutCString(", decl = "); - var->GetDeclaration().DumpStopContext(s, false); - s->EOL(); - } - } + } + + if (!showed_info) { + if (module_sp) { + SymbolContext sc; + module_sp->ResolveSymbolContextForAddress( + *this, eSymbolContextEverything, sc); + if (sc.function || sc.symbol) { + bool show_stop_context = true; + const bool show_module = (style == DumpStyleResolvedDescription); + const bool show_fullpaths = false; + const bool show_inlined_frames = true; + const bool show_function_arguments = + (style != DumpStyleResolvedDescriptionNoFunctionArguments); + const bool show_function_name = (style != DumpStyleNoFunctionName); + if (sc.function == nullptr && sc.symbol != nullptr) { + // If we have just a symbol make sure it is in the right section + if (sc.symbol->ValueIsAddress()) { + if (sc.symbol->GetAddressRef().GetSection() != GetSection()) { + // don't show the module if the symbol is a trampoline symbol + show_stop_context = false; } + } } - } - else - { - if (fallback_style != DumpStyleInvalid) - return Dump (s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); - return false; - } - break; - - case DumpStyleResolvedPointerDescription: - { - Process *process = exe_ctx.GetProcessPtr(); - if (process) - { - addr_t load_addr = GetLoadAddress (target); - if (load_addr != LLDB_INVALID_ADDRESS) - { - Error memory_error; - addr_t dereferenced_load_addr = process->ReadPointerFromMemory(load_addr, memory_error); - if (dereferenced_load_addr != LLDB_INVALID_ADDRESS) - { - Address dereferenced_addr; - if (dereferenced_addr.SetLoadAddress(dereferenced_load_addr, target)) - { - StreamString strm; - if (dereferenced_addr.Dump (&strm, exe_scope, DumpStyleResolvedDescription, DumpStyleInvalid, addr_size)) - { - s->Address (dereferenced_load_addr, addr_size, " -> ", " "); - s->Write(strm.GetData(), strm.GetSize()); - return true; - } - } - } - } + if (show_stop_context) { + // We have a function or a symbol from the same + // sections as this address. + sc.DumpStopContext(s, exe_scope, *this, show_fullpaths, + show_module, show_inlined_frames, + show_function_arguments, show_function_name); + } else { + // We found a symbol but it was in a different + // section so it isn't the symbol we should be + // showing, just show the section name + offset + Dump(s, exe_scope, DumpStyleSectionNameOffset); } - if (fallback_style != DumpStyleInvalid) - return Dump (s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); - return false; - } - break; - } - - return true; -} - -bool -Address::SectionWasDeleted() const -{ - if (GetSection()) - return false; - return SectionWasDeletedPrivate(); -} - -bool -Address::SectionWasDeletedPrivate() const -{ - lldb::SectionWP empty_section_wp; - - // If either call to "std::weak_ptr::owner_before(...) value returns true, this - // indicates that m_section_wp once contained (possibly still does) a reference - // to a valid shared pointer. This helps us know if we had a valid reference to - // a section which is now invalid because the module it was in was unloaded/deleted, - // or if the address doesn't have a valid reference to a section. - return empty_section_wp.owner_before(m_section_wp) || m_section_wp.owner_before(empty_section_wp); -} - -uint32_t -Address::CalculateSymbolContext (SymbolContext *sc, uint32_t resolve_scope) const -{ - sc->Clear(false); - // Absolute addresses don't have enough information to reconstruct even their target. - - SectionSP section_sp (GetSection()); - if (section_sp) - { - ModuleSP module_sp (section_sp->GetModule()); - if (module_sp) - { - sc->module_sp = module_sp; - if (sc->module_sp) - return sc->module_sp->ResolveSymbolContextForAddress (*this, resolve_scope, *sc); + } } - } - return 0; -} - -ModuleSP -Address::CalculateSymbolContextModule () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - return section_sp->GetModule(); - return ModuleSP(); -} - -CompileUnit * -Address::CalculateSymbolContextCompileUnit () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - SymbolContext sc; - sc.module_sp = section_sp->GetModule(); - if (sc.module_sp) - { - sc.module_sp->ResolveSymbolContextForAddress (*this, eSymbolContextCompUnit, sc); - return sc.comp_unit; - } - } - return nullptr; -} - -Function * -Address::CalculateSymbolContextFunction () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { + } + } else { + if (fallback_style != DumpStyleInvalid) + return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); + return false; + } + break; + + case DumpStyleDetailedSymbolContext: + if (IsSectionOffset()) { + ModuleSP module_sp(GetModule()); + if (module_sp) { SymbolContext sc; - sc.module_sp = section_sp->GetModule(); - if (sc.module_sp) - { - sc.module_sp->ResolveSymbolContextForAddress (*this, eSymbolContextFunction, sc); - return sc.function; + module_sp->ResolveSymbolContextForAddress( + *this, eSymbolContextEverything | eSymbolContextVariable, sc); + if (sc.symbol) { + // If we have just a symbol make sure it is in the same section + // as our address. If it isn't, then we might have just found + // the last symbol that came before the address that we are + // looking up that has nothing to do with our address lookup. + if (sc.symbol->ValueIsAddress() && + sc.symbol->GetAddressRef().GetSection() != GetSection()) + sc.symbol = nullptr; } - } - return nullptr; -} - -Block * -Address::CalculateSymbolContextBlock () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - SymbolContext sc; - sc.module_sp = section_sp->GetModule(); - if (sc.module_sp) - { - sc.module_sp->ResolveSymbolContextForAddress (*this, eSymbolContextBlock, sc); - return sc.block; - } - } - return nullptr; -} - -Symbol * -Address::CalculateSymbolContextSymbol () const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - SymbolContext sc; - sc.module_sp = section_sp->GetModule(); - if (sc.module_sp) - { - sc.module_sp->ResolveSymbolContextForAddress (*this, eSymbolContextSymbol, sc); - return sc.symbol; + sc.GetDescription(s, eDescriptionLevelBrief, target); + + if (sc.block) { + bool can_create = true; + bool get_parent_variables = true; + bool stop_if_block_is_inlined_function = false; + VariableList variable_list; + sc.block->AppendVariables(can_create, get_parent_variables, + stop_if_block_is_inlined_function, + [](Variable *) { return true; }, + &variable_list); + + const size_t num_variables = variable_list.GetSize(); + for (size_t var_idx = 0; var_idx < num_variables; ++var_idx) { + Variable *var = variable_list.GetVariableAtIndex(var_idx).get(); + if (var && var->LocationIsValidForAddress(*this)) { + s->Indent(); + s->Printf(" Variable: id = {0x%8.8" PRIx64 "}, name = \"%s\"", + var->GetID(), var->GetName().GetCString()); + Type *type = var->GetType(); + if (type) + s->Printf(", type = \"%s\"", type->GetName().GetCString()); + else + s->PutCString(", type = "); + s->PutCString(", location = "); + var->DumpLocationForAddress(s, *this); + s->PutCString(", decl = "); + var->GetDeclaration().DumpStopContext(s, false); + s->EOL(); + } + } } - } - return nullptr; -} - -bool -Address::CalculateSymbolContextLineEntry (LineEntry &line_entry) const -{ - SectionSP section_sp (GetSection()); - if (section_sp) - { - SymbolContext sc; - sc.module_sp = section_sp->GetModule(); - if (sc.module_sp) - { - sc.module_sp->ResolveSymbolContextForAddress (*this, eSymbolContextLineEntry, sc); - if (sc.line_entry.IsValid()) - { - line_entry = sc.line_entry; - return true; + } + } else { + if (fallback_style != DumpStyleInvalid) + return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); + return false; + } + break; + + case DumpStyleResolvedPointerDescription: { + Process *process = exe_ctx.GetProcessPtr(); + if (process) { + addr_t load_addr = GetLoadAddress(target); + if (load_addr != LLDB_INVALID_ADDRESS) { + Error memory_error; + addr_t dereferenced_load_addr = + process->ReadPointerFromMemory(load_addr, memory_error); + if (dereferenced_load_addr != LLDB_INVALID_ADDRESS) { + Address dereferenced_addr; + if (dereferenced_addr.SetLoadAddress(dereferenced_load_addr, + target)) { + StreamString strm; + if (dereferenced_addr.Dump(&strm, exe_scope, + DumpStyleResolvedDescription, + DumpStyleInvalid, addr_size)) { + s->Address(dereferenced_load_addr, addr_size, " -> ", " "); + s->Write(strm.GetData(), strm.GetSize()); + return true; } + } } + } } - line_entry.Clear(); + if (fallback_style != DumpStyleInvalid) + return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size); return false; -} + } break; + } -int -Address::CompareFileAddress (const Address& a, const Address& b) -{ - addr_t a_file_addr = a.GetFileAddress(); - addr_t b_file_addr = b.GetFileAddress(); - if (a_file_addr < b_file_addr) - return -1; - if (a_file_addr > b_file_addr) - return +1; - return 0; -} - -int -Address::CompareLoadAddress (const Address& a, const Address& b, Target *target) -{ - assert(target != nullptr); - addr_t a_load_addr = a.GetLoadAddress (target); - addr_t b_load_addr = b.GetLoadAddress (target); - if (a_load_addr < b_load_addr) - return -1; - if (a_load_addr > b_load_addr) - return +1; - return 0; + return true; } -int -Address::CompareModulePointerAndOffset (const Address& a, const Address& b) -{ - ModuleSP a_module_sp (a.GetModule()); - ModuleSP b_module_sp (b.GetModule()); - Module *a_module = a_module_sp.get(); - Module *b_module = b_module_sp.get(); - if (a_module < b_module) - return -1; - if (a_module > b_module) - return +1; - // Modules are the same, just compare the file address since they should - // be unique - addr_t a_file_addr = a.GetFileAddress(); - addr_t b_file_addr = b.GetFileAddress(); - if (a_file_addr < b_file_addr) - return -1; - if (a_file_addr > b_file_addr) - return +1; - return 0; -} - -size_t -Address::MemorySize () const -{ - // Noting special for the memory size of a single Address object, - // it is just the size of itself. - return sizeof(Address); +bool Address::SectionWasDeleted() const { + if (GetSection()) + return false; + return SectionWasDeletedPrivate(); +} + +bool Address::SectionWasDeletedPrivate() const { + lldb::SectionWP empty_section_wp; + + // If either call to "std::weak_ptr::owner_before(...) value returns true, + // this + // indicates that m_section_wp once contained (possibly still does) a + // reference + // to a valid shared pointer. This helps us know if we had a valid reference + // to + // a section which is now invalid because the module it was in was + // unloaded/deleted, + // or if the address doesn't have a valid reference to a section. + return empty_section_wp.owner_before(m_section_wp) || + m_section_wp.owner_before(empty_section_wp); +} + +uint32_t Address::CalculateSymbolContext(SymbolContext *sc, + uint32_t resolve_scope) const { + sc->Clear(false); + // Absolute addresses don't have enough information to reconstruct even their + // target. + + SectionSP section_sp(GetSection()); + if (section_sp) { + ModuleSP module_sp(section_sp->GetModule()); + if (module_sp) { + sc->module_sp = module_sp; + if (sc->module_sp) + return sc->module_sp->ResolveSymbolContextForAddress( + *this, resolve_scope, *sc); + } + } + return 0; +} + +ModuleSP Address::CalculateSymbolContextModule() const { + SectionSP section_sp(GetSection()); + if (section_sp) + return section_sp->GetModule(); + return ModuleSP(); +} + +CompileUnit *Address::CalculateSymbolContextCompileUnit() const { + SectionSP section_sp(GetSection()); + if (section_sp) { + SymbolContext sc; + sc.module_sp = section_sp->GetModule(); + if (sc.module_sp) { + sc.module_sp->ResolveSymbolContextForAddress(*this, + eSymbolContextCompUnit, sc); + return sc.comp_unit; + } + } + return nullptr; +} + +Function *Address::CalculateSymbolContextFunction() const { + SectionSP section_sp(GetSection()); + if (section_sp) { + SymbolContext sc; + sc.module_sp = section_sp->GetModule(); + if (sc.module_sp) { + sc.module_sp->ResolveSymbolContextForAddress(*this, + eSymbolContextFunction, sc); + return sc.function; + } + } + return nullptr; +} + +Block *Address::CalculateSymbolContextBlock() const { + SectionSP section_sp(GetSection()); + if (section_sp) { + SymbolContext sc; + sc.module_sp = section_sp->GetModule(); + if (sc.module_sp) { + sc.module_sp->ResolveSymbolContextForAddress(*this, eSymbolContextBlock, + sc); + return sc.block; + } + } + return nullptr; +} + +Symbol *Address::CalculateSymbolContextSymbol() const { + SectionSP section_sp(GetSection()); + if (section_sp) { + SymbolContext sc; + sc.module_sp = section_sp->GetModule(); + if (sc.module_sp) { + sc.module_sp->ResolveSymbolContextForAddress(*this, eSymbolContextSymbol, + sc); + return sc.symbol; + } + } + return nullptr; +} + +bool Address::CalculateSymbolContextLineEntry(LineEntry &line_entry) const { + SectionSP section_sp(GetSection()); + if (section_sp) { + SymbolContext sc; + sc.module_sp = section_sp->GetModule(); + if (sc.module_sp) { + sc.module_sp->ResolveSymbolContextForAddress(*this, + eSymbolContextLineEntry, sc); + if (sc.line_entry.IsValid()) { + line_entry = sc.line_entry; + return true; + } + } + } + line_entry.Clear(); + return false; +} + +int Address::CompareFileAddress(const Address &a, const Address &b) { + addr_t a_file_addr = a.GetFileAddress(); + addr_t b_file_addr = b.GetFileAddress(); + if (a_file_addr < b_file_addr) + return -1; + if (a_file_addr > b_file_addr) + return +1; + return 0; +} + +int Address::CompareLoadAddress(const Address &a, const Address &b, + Target *target) { + assert(target != nullptr); + addr_t a_load_addr = a.GetLoadAddress(target); + addr_t b_load_addr = b.GetLoadAddress(target); + if (a_load_addr < b_load_addr) + return -1; + if (a_load_addr > b_load_addr) + return +1; + return 0; +} + +int Address::CompareModulePointerAndOffset(const Address &a, const Address &b) { + ModuleSP a_module_sp(a.GetModule()); + ModuleSP b_module_sp(b.GetModule()); + Module *a_module = a_module_sp.get(); + Module *b_module = b_module_sp.get(); + if (a_module < b_module) + return -1; + if (a_module > b_module) + return +1; + // Modules are the same, just compare the file address since they should + // be unique + addr_t a_file_addr = a.GetFileAddress(); + addr_t b_file_addr = b.GetFileAddress(); + if (a_file_addr < b_file_addr) + return -1; + if (a_file_addr > b_file_addr) + return +1; + return 0; +} + +size_t Address::MemorySize() const { + // Noting special for the memory size of a single Address object, + // it is just the size of itself. + return sizeof(Address); } //---------------------------------------------------------------------- -// NOTE: Be careful using this operator. It can correctly compare two -// addresses from the same Module correctly. It can't compare two +// NOTE: Be careful using this operator. It can correctly compare two +// addresses from the same Module correctly. It can't compare two // addresses from different modules in any meaningful way, but it will // compare the module pointers. -// +// // To sum things up: // - works great for addresses within the same module // - it works for addresses across multiple modules, but don't expect the // address results to make much sense // -// This basically lets Address objects be used in ordered collection +// This basically lets Address objects be used in ordered collection // classes. //---------------------------------------------------------------------- -bool -lldb_private::operator< (const Address& lhs, const Address& rhs) -{ - ModuleSP lhs_module_sp (lhs.GetModule()); - ModuleSP rhs_module_sp (rhs.GetModule()); - Module *lhs_module = lhs_module_sp.get(); - Module *rhs_module = rhs_module_sp.get(); - if (lhs_module == rhs_module) - { - // Addresses are in the same module, just compare the file addresses - return lhs.GetFileAddress() < rhs.GetFileAddress(); - } - else - { - // The addresses are from different modules, just use the module - // pointer value to get consistent ordering - return lhs_module < rhs_module; - } -} - -bool -lldb_private::operator> (const Address& lhs, const Address& rhs) -{ - ModuleSP lhs_module_sp (lhs.GetModule()); - ModuleSP rhs_module_sp (rhs.GetModule()); - Module *lhs_module = lhs_module_sp.get(); - Module *rhs_module = rhs_module_sp.get(); - if (lhs_module == rhs_module) - { - // Addresses are in the same module, just compare the file addresses - return lhs.GetFileAddress() > rhs.GetFileAddress(); - } - else - { - // The addresses are from different modules, just use the module - // pointer value to get consistent ordering - return lhs_module > rhs_module; - } +bool lldb_private::operator<(const Address &lhs, const Address &rhs) { + ModuleSP lhs_module_sp(lhs.GetModule()); + ModuleSP rhs_module_sp(rhs.GetModule()); + Module *lhs_module = lhs_module_sp.get(); + Module *rhs_module = rhs_module_sp.get(); + if (lhs_module == rhs_module) { + // Addresses are in the same module, just compare the file addresses + return lhs.GetFileAddress() < rhs.GetFileAddress(); + } else { + // The addresses are from different modules, just use the module + // pointer value to get consistent ordering + return lhs_module < rhs_module; + } +} + +bool lldb_private::operator>(const Address &lhs, const Address &rhs) { + ModuleSP lhs_module_sp(lhs.GetModule()); + ModuleSP rhs_module_sp(rhs.GetModule()); + Module *lhs_module = lhs_module_sp.get(); + Module *rhs_module = rhs_module_sp.get(); + if (lhs_module == rhs_module) { + // Addresses are in the same module, just compare the file addresses + return lhs.GetFileAddress() > rhs.GetFileAddress(); + } else { + // The addresses are from different modules, just use the module + // pointer value to get consistent ordering + return lhs_module > rhs_module; + } } // The operator == checks for exact equality only (same section, same offset) -bool -lldb_private::operator== (const Address& a, const Address& rhs) -{ - return a.GetOffset() == rhs.GetOffset() && - a.GetSection() == rhs.GetSection(); +bool lldb_private::operator==(const Address &a, const Address &rhs) { + return a.GetOffset() == rhs.GetOffset() && a.GetSection() == rhs.GetSection(); } // The operator != checks for exact inequality only (differing section, or // different offset) -bool -lldb_private::operator!= (const Address& a, const Address& rhs) -{ - return a.GetOffset() != rhs.GetOffset() || - a.GetSection() != rhs.GetSection(); +bool lldb_private::operator!=(const Address &a, const Address &rhs) { + return a.GetOffset() != rhs.GetOffset() || a.GetSection() != rhs.GetSection(); } -AddressClass -Address::GetAddressClass () const -{ - ModuleSP module_sp (GetModule()); - if (module_sp) - { - ObjectFile *obj_file = module_sp->GetObjectFile(); - if (obj_file) - { - // Give the symbol vendor a chance to add to the unified section list. - module_sp->GetSymbolVendor(); - return obj_file->GetAddressClass (GetFileAddress()); - } +AddressClass Address::GetAddressClass() const { + ModuleSP module_sp(GetModule()); + if (module_sp) { + ObjectFile *obj_file = module_sp->GetObjectFile(); + if (obj_file) { + // Give the symbol vendor a chance to add to the unified section list. + module_sp->GetSymbolVendor(); + return obj_file->GetAddressClass(GetFileAddress()); } - return eAddressClassUnknown; + } + return eAddressClassUnknown; } -bool -Address::SetLoadAddress (lldb::addr_t load_addr, Target *target) -{ - if (target && target->GetSectionLoadList().ResolveLoadAddress(load_addr, *this)) - return true; - m_section_wp.reset(); - m_offset = load_addr; - return false; +bool Address::SetLoadAddress(lldb::addr_t load_addr, Target *target) { + if (target && + target->GetSectionLoadList().ResolveLoadAddress(load_addr, *this)) + return true; + m_section_wp.reset(); + m_offset = load_addr; + return false; } diff --git a/lldb/source/Core/AddressRange.cpp b/lldb/source/Core/AddressRange.cpp index 072c2450836..e03d721b566 100644 --- a/lldb/source/Core/AddressRange.cpp +++ b/lldb/source/Core/AddressRange.cpp @@ -16,194 +16,165 @@ using namespace lldb; using namespace lldb_private; -AddressRange::AddressRange () : - m_base_addr(), - m_byte_size(0) -{ -} +AddressRange::AddressRange() : m_base_addr(), m_byte_size(0) {} -AddressRange::AddressRange (addr_t file_addr, addr_t byte_size, const SectionList *section_list) : - m_base_addr(file_addr, section_list), - m_byte_size(byte_size) -{ -} +AddressRange::AddressRange(addr_t file_addr, addr_t byte_size, + const SectionList *section_list) + : m_base_addr(file_addr, section_list), m_byte_size(byte_size) {} -AddressRange::AddressRange (const lldb::SectionSP §ion, addr_t offset, addr_t byte_size) : - m_base_addr(section, offset), - m_byte_size(byte_size) -{ -} +AddressRange::AddressRange(const lldb::SectionSP §ion, addr_t offset, + addr_t byte_size) + : m_base_addr(section, offset), m_byte_size(byte_size) {} -AddressRange::AddressRange (const Address& so_addr, addr_t byte_size) : - m_base_addr(so_addr), - m_byte_size(byte_size) -{ -} +AddressRange::AddressRange(const Address &so_addr, addr_t byte_size) + : m_base_addr(so_addr), m_byte_size(byte_size) {} -AddressRange::~AddressRange () -{ -} +AddressRange::~AddressRange() {} -//bool -//AddressRange::Contains (const Address &addr) const +// bool +// AddressRange::Contains (const Address &addr) const //{ // const addr_t byte_size = GetByteSize(); // if (byte_size) -// return addr.GetSection() == m_base_addr.GetSection() && (addr.GetOffset() - m_base_addr.GetOffset()) < byte_size; +// return addr.GetSection() == m_base_addr.GetSection() && +// (addr.GetOffset() - m_base_addr.GetOffset()) < byte_size; //} // -//bool -//AddressRange::Contains (const Address *addr) const +// bool +// AddressRange::Contains (const Address *addr) const //{ // if (addr) // return Contains (*addr); // return false; //} -bool -AddressRange::ContainsFileAddress (const Address &addr) const -{ - if (addr.GetSection() == m_base_addr.GetSection()) - return (addr.GetOffset() - m_base_addr.GetOffset()) < GetByteSize(); - addr_t file_base_addr = GetBaseAddress().GetFileAddress(); - if (file_base_addr == LLDB_INVALID_ADDRESS) - return false; +bool AddressRange::ContainsFileAddress(const Address &addr) const { + if (addr.GetSection() == m_base_addr.GetSection()) + return (addr.GetOffset() - m_base_addr.GetOffset()) < GetByteSize(); + addr_t file_base_addr = GetBaseAddress().GetFileAddress(); + if (file_base_addr == LLDB_INVALID_ADDRESS) + return false; - addr_t file_addr = addr.GetFileAddress(); - if (file_addr == LLDB_INVALID_ADDRESS) - return false; + addr_t file_addr = addr.GetFileAddress(); + if (file_addr == LLDB_INVALID_ADDRESS) + return false; - if (file_base_addr <= file_addr) - return (file_addr - file_base_addr) < GetByteSize(); + if (file_base_addr <= file_addr) + return (file_addr - file_base_addr) < GetByteSize(); - return false; + return false; } -bool -AddressRange::ContainsFileAddress (addr_t file_addr) const -{ - if (file_addr == LLDB_INVALID_ADDRESS) - return false; +bool AddressRange::ContainsFileAddress(addr_t file_addr) const { + if (file_addr == LLDB_INVALID_ADDRESS) + return false; - addr_t file_base_addr = GetBaseAddress().GetFileAddress(); - if (file_base_addr == LLDB_INVALID_ADDRESS) - return false; + addr_t file_base_addr = GetBaseAddress().GetFileAddress(); + if (file_base_addr == LLDB_INVALID_ADDRESS) + return false; - if (file_base_addr <= file_addr) - return (file_addr - file_base_addr) < GetByteSize(); + if (file_base_addr <= file_addr) + return (file_addr - file_base_addr) < GetByteSize(); - return false; + return false; } +bool AddressRange::ContainsLoadAddress(const Address &addr, + Target *target) const { + if (addr.GetSection() == m_base_addr.GetSection()) + return (addr.GetOffset() - m_base_addr.GetOffset()) < GetByteSize(); + addr_t load_base_addr = GetBaseAddress().GetLoadAddress(target); + if (load_base_addr == LLDB_INVALID_ADDRESS) + return false; -bool -AddressRange::ContainsLoadAddress (const Address &addr, Target *target) const -{ - if (addr.GetSection() == m_base_addr.GetSection()) - return (addr.GetOffset() - m_base_addr.GetOffset()) < GetByteSize(); - addr_t load_base_addr = GetBaseAddress().GetLoadAddress(target); - if (load_base_addr == LLDB_INVALID_ADDRESS) - return false; - - addr_t load_addr = addr.GetLoadAddress(target); - if (load_addr == LLDB_INVALID_ADDRESS) - return false; + addr_t load_addr = addr.GetLoadAddress(target); + if (load_addr == LLDB_INVALID_ADDRESS) + return false; - if (load_base_addr <= load_addr) - return (load_addr - load_base_addr) < GetByteSize(); + if (load_base_addr <= load_addr) + return (load_addr - load_base_addr) < GetByteSize(); - return false; + return false; } -bool -AddressRange::ContainsLoadAddress (addr_t load_addr, Target *target) const -{ - if (load_addr == LLDB_INVALID_ADDRESS) - return false; +bool AddressRange::ContainsLoadAddress(addr_t load_addr, Target *target) const { + if (load_addr == LLDB_INVALID_ADDRESS) + return false; - addr_t load_base_addr = GetBaseAddress().GetLoadAddress(target); - if (load_base_addr == LLDB_INVALID_ADDRESS) - return false; + addr_t load_base_addr = GetBaseAddress().GetLoadAddress(target); + if (load_base_addr == LLDB_INVALID_ADDRESS) + return false; - if (load_base_addr <= load_addr) - return (load_addr - load_base_addr) < GetByteSize(); + if (load_base_addr <= load_addr) + return (load_addr - load_base_addr) < GetByteSize(); - return false; + return false; } -void -AddressRange::Clear() -{ - m_base_addr.Clear(); - m_byte_size = 0; +void AddressRange::Clear() { + m_base_addr.Clear(); + m_byte_size = 0; } -bool -AddressRange::Dump(Stream *s, Target *target, Address::DumpStyle style, Address::DumpStyle fallback_style) const -{ - addr_t vmaddr = LLDB_INVALID_ADDRESS; - int addr_size = sizeof (addr_t); - if (target) - addr_size = target->GetArchitecture().GetAddressByteSize (); - - bool show_module = false; - switch (style) - { - default: - break; - case Address::DumpStyleSectionNameOffset: - case Address::DumpStyleSectionPointerOffset: - s->PutChar ('['); - m_base_addr.Dump(s, target, style, fallback_style); - s->PutChar ('-'); - s->Address (m_base_addr.GetOffset() + GetByteSize(), addr_size); - s->PutChar (')'); - return true; - break; - - case Address::DumpStyleModuleWithFileAddress: - show_module = true; - LLVM_FALLTHROUGH; - case Address::DumpStyleFileAddress: - vmaddr = m_base_addr.GetFileAddress(); - break; - - case Address::DumpStyleLoadAddress: - vmaddr = m_base_addr.GetLoadAddress(target); - break; +bool AddressRange::Dump(Stream *s, Target *target, Address::DumpStyle style, + Address::DumpStyle fallback_style) const { + addr_t vmaddr = LLDB_INVALID_ADDRESS; + int addr_size = sizeof(addr_t); + if (target) + addr_size = target->GetArchitecture().GetAddressByteSize(); + + bool show_module = false; + switch (style) { + default: + break; + case Address::DumpStyleSectionNameOffset: + case Address::DumpStyleSectionPointerOffset: + s->PutChar('['); + m_base_addr.Dump(s, target, style, fallback_style); + s->PutChar('-'); + s->Address(m_base_addr.GetOffset() + GetByteSize(), addr_size); + s->PutChar(')'); + return true; + break; + + case Address::DumpStyleModuleWithFileAddress: + show_module = true; + LLVM_FALLTHROUGH; + case Address::DumpStyleFileAddress: + vmaddr = m_base_addr.GetFileAddress(); + break; + + case Address::DumpStyleLoadAddress: + vmaddr = m_base_addr.GetLoadAddress(target); + break; + } + + if (vmaddr != LLDB_INVALID_ADDRESS) { + if (show_module) { + ModuleSP module_sp(GetBaseAddress().GetModule()); + if (module_sp) + s->Printf("%s", module_sp->GetFileSpec().GetFilename().AsCString( + "")); } + s->AddressRange(vmaddr, vmaddr + GetByteSize(), addr_size); + return true; + } else if (fallback_style != Address::DumpStyleInvalid) { + return Dump(s, target, fallback_style, Address::DumpStyleInvalid); + } - if (vmaddr != LLDB_INVALID_ADDRESS) - { - if (show_module) - { - ModuleSP module_sp (GetBaseAddress().GetModule()); - if (module_sp) - s->Printf("%s", module_sp->GetFileSpec().GetFilename().AsCString("")); - } - s->AddressRange(vmaddr, vmaddr + GetByteSize(), addr_size); - return true; - } - else if (fallback_style != Address::DumpStyleInvalid) - { - return Dump(s, target, fallback_style, Address::DumpStyleInvalid); - } - - return false; + return false; } - -void -AddressRange::DumpDebug (Stream *s) const -{ - s->Printf("%p: AddressRange section = %p, offset = 0x%16.16" PRIx64 ", byte_size = 0x%16.16" PRIx64 "\n", - static_cast(this), - static_cast(m_base_addr.GetSection().get()), - m_base_addr.GetOffset(), GetByteSize()); +void AddressRange::DumpDebug(Stream *s) const { + s->Printf("%p: AddressRange section = %p, offset = 0x%16.16" PRIx64 + ", byte_size = 0x%16.16" PRIx64 "\n", + static_cast(this), + static_cast(m_base_addr.GetSection().get()), + m_base_addr.GetOffset(), GetByteSize()); } // -//bool -//lldb::operator== (const AddressRange& lhs, const AddressRange& rhs) +// bool +// lldb::operator== (const AddressRange& lhs, const AddressRange& rhs) //{ // if (lhs.GetBaseAddress() == rhs.GetBaseAddress()) // return lhs.GetByteSize() == rhs.GetByteSize(); diff --git a/lldb/source/Core/AddressResolver.cpp b/lldb/source/Core/AddressResolver.cpp index aa457015b4f..40f4d55340e 100644 --- a/lldb/source/Core/AddressResolver.cpp +++ b/lldb/source/Core/AddressResolver.cpp @@ -9,7 +9,6 @@ #include "lldb/Core/AddressResolver.h" - // Project includes #include "lldb/Core/Address.h" @@ -26,41 +25,27 @@ using namespace lldb_private; //---------------------------------------------------------------------- // AddressResolver: //---------------------------------------------------------------------- -AddressResolver::AddressResolver () -{ -} +AddressResolver::AddressResolver() {} -AddressResolver::~AddressResolver () -{ - -} +AddressResolver::~AddressResolver() {} -void -AddressResolver::ResolveAddressInModules (SearchFilter &filter, ModuleList &modules) -{ - filter.SearchInModuleList(*this, modules); +void AddressResolver::ResolveAddressInModules(SearchFilter &filter, + ModuleList &modules) { + filter.SearchInModuleList(*this, modules); } -void -AddressResolver::ResolveAddress (SearchFilter &filter) -{ - filter.Search (*this); +void AddressResolver::ResolveAddress(SearchFilter &filter) { + filter.Search(*this); } -std::vector & -AddressResolver::GetAddressRanges () -{ - return m_address_ranges; +std::vector &AddressResolver::GetAddressRanges() { + return m_address_ranges; } -size_t -AddressResolver::GetNumberOfAddresses () -{ - return m_address_ranges.size(); +size_t AddressResolver::GetNumberOfAddresses() { + return m_address_ranges.size(); } -AddressRange & -AddressResolver::GetAddressRangeAtIndex (size_t idx) -{ +AddressRange &AddressResolver::GetAddressRangeAtIndex(size_t idx) { return m_address_ranges[idx]; } diff --git a/lldb/source/Core/AddressResolverFileLine.cpp b/lldb/source/Core/AddressResolverFileLine.cpp index e45076e9bfc..939cf45f3e8 100644 --- a/lldb/source/Core/AddressResolverFileLine.cpp +++ b/lldb/source/Core/AddressResolverFileLine.cpp @@ -21,81 +21,58 @@ using namespace lldb_private; //---------------------------------------------------------------------- // AddressResolverFileLine: //---------------------------------------------------------------------- -AddressResolverFileLine::AddressResolverFileLine -( - const FileSpec &file_spec, - uint32_t line_no, - bool check_inlines -) : - AddressResolver (), - m_file_spec (file_spec), - m_line_number (line_no), - m_inlines (check_inlines) -{ -} +AddressResolverFileLine::AddressResolverFileLine(const FileSpec &file_spec, + uint32_t line_no, + bool check_inlines) + : AddressResolver(), m_file_spec(file_spec), m_line_number(line_no), + m_inlines(check_inlines) {} -AddressResolverFileLine::~AddressResolverFileLine () -{ -} +AddressResolverFileLine::~AddressResolverFileLine() {} Searcher::CallbackReturn -AddressResolverFileLine::SearchCallback -( - SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing -) -{ - SymbolContextList sc_list; - uint32_t sc_list_size; - CompileUnit *cu = context.comp_unit; +AddressResolverFileLine::SearchCallback(SearchFilter &filter, + SymbolContext &context, Address *addr, + bool containing) { + SymbolContextList sc_list; + uint32_t sc_list_size; + CompileUnit *cu = context.comp_unit; - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); - sc_list_size = cu->ResolveSymbolContext (m_file_spec, m_line_number, m_inlines, false, eSymbolContextEverything, - sc_list); - for (uint32_t i = 0; i < sc_list_size; i++) - { - SymbolContext sc; - if (sc_list.GetContextAtIndex(i, sc)) - { - Address line_start = sc.line_entry.range.GetBaseAddress(); - addr_t byte_size = sc.line_entry.range.GetByteSize(); - if (line_start.IsValid()) - { - AddressRange new_range (line_start, byte_size); - m_address_ranges.push_back (new_range); - if (log) - { - StreamString s; - //new_bp_loc->GetDescription (&s, lldb::eDescriptionLevelVerbose); - //log->Printf ("Added address: %s\n", s.GetData()); - } - } - else - { - if (log) - log->Printf ("error: Unable to resolve address at file address 0x%" PRIx64 " for %s:%d\n", - line_start.GetFileAddress(), - m_file_spec.GetFilename().AsCString(""), - m_line_number); - } + sc_list_size = + cu->ResolveSymbolContext(m_file_spec, m_line_number, m_inlines, false, + eSymbolContextEverything, sc_list); + for (uint32_t i = 0; i < sc_list_size; i++) { + SymbolContext sc; + if (sc_list.GetContextAtIndex(i, sc)) { + Address line_start = sc.line_entry.range.GetBaseAddress(); + addr_t byte_size = sc.line_entry.range.GetByteSize(); + if (line_start.IsValid()) { + AddressRange new_range(line_start, byte_size); + m_address_ranges.push_back(new_range); + if (log) { + StreamString s; + // new_bp_loc->GetDescription (&s, lldb::eDescriptionLevelVerbose); + // log->Printf ("Added address: %s\n", s.GetData()); } + } else { + if (log) + log->Printf( + "error: Unable to resolve address at file address 0x%" PRIx64 + " for %s:%d\n", + line_start.GetFileAddress(), + m_file_spec.GetFilename().AsCString(""), m_line_number); + } } - return Searcher::eCallbackReturnContinue; + } + return Searcher::eCallbackReturnContinue; } -Searcher::Depth -AddressResolverFileLine::GetDepth() -{ - return Searcher::eDepthCompUnit; +Searcher::Depth AddressResolverFileLine::GetDepth() { + return Searcher::eDepthCompUnit; } -void -AddressResolverFileLine::GetDescription (Stream *s) -{ - s->Printf ("File and line address - file: \"%s\" line: %u", m_file_spec.GetFilename().AsCString(""), m_line_number); +void AddressResolverFileLine::GetDescription(Stream *s) { + s->Printf("File and line address - file: \"%s\" line: %u", + m_file_spec.GetFilename().AsCString(""), m_line_number); } - - diff --git a/lldb/source/Core/AddressResolverName.cpp b/lldb/source/Core/AddressResolverName.cpp index dacc7d777f8..a2a45e6cd4f 100644 --- a/lldb/source/Core/AddressResolverName.cpp +++ b/lldb/source/Core/AddressResolverName.cpp @@ -17,223 +17,176 @@ #include "lldb/Core/Module.h" #include "lldb/Core/StreamString.h" #include "lldb/Symbol/Function.h" -#include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/Symbol.h" +#include "lldb/Symbol/SymbolContext.h" using namespace lldb; using namespace lldb_private; AddressResolverName::AddressResolverName(const char *func_name, - AddressResolver::MatchType type) : - AddressResolver(), - m_func_name(func_name), - m_class_name(nullptr), - m_regex(), - m_match_type(type) -{ - if (m_match_type == AddressResolver::Regexp) - { - if (!m_regex.Compile (m_func_name.AsCString())) - { - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - - if (log) - log->Warning ("function name regexp: \"%s\" did not compile.", m_func_name.AsCString()); - } + AddressResolver::MatchType type) + : AddressResolver(), m_func_name(func_name), m_class_name(nullptr), + m_regex(), m_match_type(type) { + if (m_match_type == AddressResolver::Regexp) { + if (!m_regex.Compile(m_func_name.AsCString())) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + + if (log) + log->Warning("function name regexp: \"%s\" did not compile.", + m_func_name.AsCString()); } + } } -AddressResolverName::AddressResolverName(RegularExpression &func_regex) : - AddressResolver(), - m_func_name(nullptr), - m_class_name(nullptr), - m_regex(func_regex), - m_match_type(AddressResolver::Regexp) -{ -} +AddressResolverName::AddressResolverName(RegularExpression &func_regex) + : AddressResolver(), m_func_name(nullptr), m_class_name(nullptr), + m_regex(func_regex), m_match_type(AddressResolver::Regexp) {} AddressResolverName::AddressResolverName(const char *class_name, const char *method, - AddressResolver::MatchType type) : - AddressResolver (), - m_func_name (method), - m_class_name (class_name), - m_regex (), - m_match_type (type) -{ -} + AddressResolver::MatchType type) + : AddressResolver(), m_func_name(method), m_class_name(class_name), + m_regex(), m_match_type(type) {} AddressResolverName::~AddressResolverName() = default; -// FIXME: Right now we look at the module level, and call the module's "FindFunctions". -// Greg says he will add function tables, maybe at the CompileUnit level to accelerate function -// lookup. At that point, we should switch the depth to CompileUnit, and look in these tables. +// FIXME: Right now we look at the module level, and call the module's +// "FindFunctions". +// Greg says he will add function tables, maybe at the CompileUnit level to +// accelerate function +// lookup. At that point, we should switch the depth to CompileUnit, and look +// in these tables. Searcher::CallbackReturn AddressResolverName::SearchCallback(SearchFilter &filter, - SymbolContext &context, - Address *addr, - bool containing) -{ - SymbolContextList func_list; - SymbolContextList sym_list; - - bool skip_prologue = true; - uint32_t i; - SymbolContext sc; - Address func_addr; - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); - - if (m_class_name) - { - if (log) - log->Warning ("Class/method function specification not supported yet.\n"); - return Searcher::eCallbackReturnStop; + SymbolContext &context, Address *addr, + bool containing) { + SymbolContextList func_list; + SymbolContextList sym_list; + + bool skip_prologue = true; + uint32_t i; + SymbolContext sc; + Address func_addr; + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); + + if (m_class_name) { + if (log) + log->Warning("Class/method function specification not supported yet.\n"); + return Searcher::eCallbackReturnStop; + } + + const bool include_symbols = false; + const bool include_inlines = true; + const bool append = false; + switch (m_match_type) { + case AddressResolver::Exact: + if (context.module_sp) { + context.module_sp->FindSymbolsWithNameAndType(m_func_name, + eSymbolTypeCode, sym_list); + context.module_sp->FindFunctions(m_func_name, nullptr, + eFunctionNameTypeAuto, include_symbols, + include_inlines, append, func_list); } - - const bool include_symbols = false; - const bool include_inlines = true; - const bool append = false; - switch (m_match_type) - { - case AddressResolver::Exact: - if (context.module_sp) - { - context.module_sp->FindSymbolsWithNameAndType (m_func_name, - eSymbolTypeCode, - sym_list); - context.module_sp->FindFunctions(m_func_name, - nullptr, - eFunctionNameTypeAuto, - include_symbols, - include_inlines, - append, - func_list); - } - break; - - case AddressResolver::Regexp: - if (context.module_sp) - { - context.module_sp->FindSymbolsMatchingRegExAndType (m_regex, - eSymbolTypeCode, - sym_list); - context.module_sp->FindFunctions (m_regex, - include_symbols, - include_inlines, - append, - func_list); + break; + + case AddressResolver::Regexp: + if (context.module_sp) { + context.module_sp->FindSymbolsMatchingRegExAndType( + m_regex, eSymbolTypeCode, sym_list); + context.module_sp->FindFunctions(m_regex, include_symbols, + include_inlines, append, func_list); + } + break; + + case AddressResolver::Glob: + if (log) + log->Warning("glob is not supported yet."); + break; + } + + // Remove any duplicates between the function list and the symbol list + if (func_list.GetSize()) { + for (i = 0; i < func_list.GetSize(); i++) { + if (!func_list.GetContextAtIndex(i, sc)) + continue; + + if (sc.function == nullptr) + continue; + uint32_t j = 0; + while (j < sym_list.GetSize()) { + SymbolContext symbol_sc; + if (sym_list.GetContextAtIndex(j, symbol_sc)) { + if (symbol_sc.symbol && symbol_sc.symbol->ValueIsAddress()) { + if (sc.function->GetAddressRange().GetBaseAddress() == + symbol_sc.symbol->GetAddressRef()) { + sym_list.RemoveContextAtIndex(j); + continue; // Don't increment j + } + } } - break; - case AddressResolver::Glob: - if (log) - log->Warning ("glob is not supported yet."); - break; + j++; + } } - // Remove any duplicates between the function list and the symbol list - if (func_list.GetSize()) - { - for (i = 0; i < func_list.GetSize(); i++) - { - if (!func_list.GetContextAtIndex(i, sc)) - continue; - - if (sc.function == nullptr) - continue; - uint32_t j = 0; - while (j < sym_list.GetSize()) - { - SymbolContext symbol_sc; - if (sym_list.GetContextAtIndex(j, symbol_sc)) - { - if (symbol_sc.symbol && symbol_sc.symbol->ValueIsAddress()) - { - if (sc.function->GetAddressRange().GetBaseAddress() == symbol_sc.symbol->GetAddressRef()) - { - sym_list.RemoveContextAtIndex(j); - continue; // Don't increment j - } - } - } - - j++; + for (i = 0; i < func_list.GetSize(); i++) { + if (func_list.GetContextAtIndex(i, sc)) { + if (sc.function) { + func_addr = sc.function->GetAddressRange().GetBaseAddress(); + addr_t byte_size = sc.function->GetAddressRange().GetByteSize(); + if (skip_prologue) { + const uint32_t prologue_byte_size = + sc.function->GetPrologueByteSize(); + if (prologue_byte_size) { + func_addr.SetOffset(func_addr.GetOffset() + prologue_byte_size); + byte_size -= prologue_byte_size; } - } + } - for (i = 0; i < func_list.GetSize(); i++) - { - if (func_list.GetContextAtIndex(i, sc)) - { - if (sc.function) - { - func_addr = sc.function->GetAddressRange().GetBaseAddress(); - addr_t byte_size = sc.function->GetAddressRange().GetByteSize(); - if (skip_prologue) - { - const uint32_t prologue_byte_size = sc.function->GetPrologueByteSize(); - if (prologue_byte_size) - { - func_addr.SetOffset (func_addr.GetOffset() + prologue_byte_size); - byte_size -= prologue_byte_size; - } - } - - if (filter.AddressPasses (func_addr)) - { - AddressRange new_range (func_addr, byte_size); - m_address_ranges.push_back (new_range); - } - } - } + if (filter.AddressPasses(func_addr)) { + AddressRange new_range(func_addr, byte_size); + m_address_ranges.push_back(new_range); + } } + } } + } + + for (i = 0; i < sym_list.GetSize(); i++) { + if (sym_list.GetContextAtIndex(i, sc)) { + if (sc.symbol && sc.symbol->ValueIsAddress()) { + func_addr = sc.symbol->GetAddressRef(); + addr_t byte_size = sc.symbol->GetByteSize(); + + if (skip_prologue) { + const uint32_t prologue_byte_size = sc.symbol->GetPrologueByteSize(); + if (prologue_byte_size) { + func_addr.SetOffset(func_addr.GetOffset() + prologue_byte_size); + byte_size -= prologue_byte_size; + } + } - for (i = 0; i < sym_list.GetSize(); i++) - { - if (sym_list.GetContextAtIndex(i, sc)) - { - if (sc.symbol && sc.symbol->ValueIsAddress()) - { - func_addr = sc.symbol->GetAddressRef(); - addr_t byte_size = sc.symbol->GetByteSize(); - - if (skip_prologue) - { - const uint32_t prologue_byte_size = sc.symbol->GetPrologueByteSize(); - if (prologue_byte_size) - { - func_addr.SetOffset (func_addr.GetOffset() + prologue_byte_size); - byte_size -= prologue_byte_size; - } - } - - if (filter.AddressPasses (func_addr)) - { - AddressRange new_range (func_addr, byte_size); - m_address_ranges.push_back (new_range); - } - } + if (filter.AddressPasses(func_addr)) { + AddressRange new_range(func_addr, byte_size); + m_address_ranges.push_back(new_range); } + } } - return Searcher::eCallbackReturnContinue; + } + return Searcher::eCallbackReturnContinue; } -Searcher::Depth -AddressResolverName::GetDepth() -{ - return Searcher::eDepthModule; +Searcher::Depth AddressResolverName::GetDepth() { + return Searcher::eDepthModule; } -void -AddressResolverName::GetDescription (Stream *s) -{ - s->PutCString("Address by function name: "); +void AddressResolverName::GetDescription(Stream *s) { + s->PutCString("Address by function name: "); - if (m_match_type == AddressResolver::Regexp) - s->Printf("'%s' (regular expression)", m_regex.GetText()); - else - s->Printf("'%s'", m_func_name.AsCString()); + if (m_match_type == AddressResolver::Regexp) + s->Printf("'%s' (regular expression)", m_regex.GetText()); + else + s->Printf("'%s'", m_func_name.AsCString()); } diff --git a/lldb/source/Core/ArchSpec.cpp b/lldb/source/Core/ArchSpec.cpp index 24aba81350a..285e30e3594 100644 --- a/lldb/source/Core/ArchSpec.cpp +++ b/lldb/source/Core/ArchSpec.cpp @@ -11,8 +11,8 @@ // C Includes // C++ Includes -#include #include +#include #include // Other libraries and framework includes @@ -22,6 +22,8 @@ #include "llvm/Support/Host.h" // Project includes +#include "Plugins/Process/Utility/ARMDefines.h" +#include "Plugins/Process/Utility/InstructionUtils.h" #include "lldb/Core/RegularExpression.h" #include "lldb/Core/StringList.h" #include "lldb/Host/Endian.h" @@ -32,166 +34,239 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/NameMatches.h" #include "lldb/Utility/SafeMachO.h" -#include "Plugins/Process/Utility/ARMDefines.h" -#include "Plugins/Process/Utility/InstructionUtils.h" using namespace lldb; using namespace lldb_private; -static bool cores_match (const ArchSpec::Core core1, const ArchSpec::Core core2, bool try_inverse, bool enforce_exact_match); +static bool cores_match(const ArchSpec::Core core1, const ArchSpec::Core core2, + bool try_inverse, bool enforce_exact_match); namespace lldb_private { - struct CoreDefinition - { - ByteOrder default_byte_order; - uint32_t addr_byte_size; - uint32_t min_opcode_byte_size; - uint32_t max_opcode_byte_size; - llvm::Triple::ArchType machine; - ArchSpec::Core core; - const char * const name; - }; +struct CoreDefinition { + ByteOrder default_byte_order; + uint32_t addr_byte_size; + uint32_t min_opcode_byte_size; + uint32_t max_opcode_byte_size; + llvm::Triple::ArchType machine; + ArchSpec::Core core; + const char *const name; +}; } // namespace lldb_private // This core information can be looked using the ArchSpec::Core as the index -static const CoreDefinition g_core_definitions[] = -{ - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_generic , "arm" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv4 , "armv4" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv4t , "armv4t" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5 , "armv5" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5e , "armv5e" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5t , "armv5t" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv6 , "armv6" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv6m , "armv6m" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7 , "armv7" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7f , "armv7f" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7s , "armv7s" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7k , "armv7k" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7m , "armv7m" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7em , "armv7em" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_xscale , "xscale" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumb , "thumb" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv4t , "thumbv4t" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv5 , "thumbv5" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv5e , "thumbv5e" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv6 , "thumbv6" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv6m , "thumbv6m" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7 , "thumbv7" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7f , "thumbv7f" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7s , "thumbv7s" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7k , "thumbv7k" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7m , "thumbv7m" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7em , "thumbv7em" }, - { eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_arm64 , "arm64" }, - { eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_armv8 , "armv8" }, - { eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_aarch64 , "aarch64" }, +static const CoreDefinition g_core_definitions[] = { + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_generic, + "arm"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv4, + "armv4"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv4t, + "armv4t"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv5, + "armv5"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv5e, + "armv5e"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv5t, + "armv5t"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv6, + "armv6"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv6m, + "armv6m"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7, + "armv7"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7f, + "armv7f"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7s, + "armv7s"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7k, + "armv7k"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7m, + "armv7m"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_armv7em, + "armv7em"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::arm, ArchSpec::eCore_arm_xscale, + "xscale"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumb, + "thumb"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv4t, + "thumbv4t"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv5, + "thumbv5"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv5e, + "thumbv5e"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv6, + "thumbv6"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv6m, + "thumbv6m"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7, + "thumbv7"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7f, + "thumbv7f"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7s, + "thumbv7s"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7k, + "thumbv7k"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7m, + "thumbv7m"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb, ArchSpec::eCore_thumbv7em, + "thumbv7em"}, + {eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, + ArchSpec::eCore_arm_arm64, "arm64"}, + {eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, + ArchSpec::eCore_arm_armv8, "armv8"}, + {eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, + ArchSpec::eCore_arm_aarch64, "aarch64"}, // mips32, mips32r2, mips32r3, mips32r5, mips32r6 - { eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32 , "mips" }, - { eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r2 , "mipsr2" }, - { eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r3 , "mipsr3" }, - { eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r5 , "mipsr5" }, - { eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r6 , "mipsr6" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32el , "mipsel" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r2el , "mipsr2el" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r3el , "mipsr3el" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r5el , "mipsr5el" }, - { eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r6el , "mipsr6el" }, - - // mips64, mips64r2, mips64r3, mips64r5, mips64r6 - { eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64 , "mips64" }, - { eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r2 , "mips64r2" }, - { eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r3 , "mips64r3" }, - { eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r5 , "mips64r5" }, - { eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r6 , "mips64r6" }, - { eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64el , "mips64el" }, - { eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r2el , "mips64r2el" }, - { eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r3el , "mips64r3el" }, - { eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r5el , "mips64r5el" }, - { eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r6el , "mips64r6el" }, - - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_generic , "powerpc" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc601 , "ppc601" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc602 , "ppc602" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603 , "ppc603" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603e , "ppc603e" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603ev , "ppc603ev" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc604 , "ppc604" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc604e , "ppc604e" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc620 , "ppc620" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc750 , "ppc750" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc7400 , "ppc7400" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc7450 , "ppc7450" }, - { eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc970 , "ppc970" }, - - { eByteOrderBig , 8, 4, 4, llvm::Triple::ppc64 , ArchSpec::eCore_ppc64_generic , "powerpc64" }, - { eByteOrderBig , 8, 4, 4, llvm::Triple::ppc64 , ArchSpec::eCore_ppc64_ppc970_64 , "ppc970-64" }, - - { eByteOrderBig , 8, 2, 6, llvm::Triple::systemz, ArchSpec::eCore_s390x_generic , "s390x" }, - - { eByteOrderLittle, 4, 4, 4, llvm::Triple::sparc , ArchSpec::eCore_sparc_generic , "sparc" }, - { eByteOrderLittle, 8, 4, 4, llvm::Triple::sparcv9, ArchSpec::eCore_sparc9_generic , "sparcv9" }, - - { eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i386 , "i386" }, - { eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i486 , "i486" }, - { eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i486sx , "i486sx" }, - { eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i686 , "i686" }, - - { eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64 , ArchSpec::eCore_x86_64_x86_64 , "x86_64" }, - { eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64 , ArchSpec::eCore_x86_64_x86_64h , "x86_64h" }, - { eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_generic, "hexagon" }, - { eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_hexagonv4, "hexagonv4" }, - { eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_hexagonv5, "hexagonv5" }, - - { eByteOrderLittle, 4, 4, 4 , llvm::Triple::UnknownArch , ArchSpec::eCore_uknownMach32 , "unknown-mach-32" }, - { eByteOrderLittle, 8, 4, 4 , llvm::Triple::UnknownArch , ArchSpec::eCore_uknownMach64 , "unknown-mach-64" }, - - { eByteOrderBig , 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba3 , "kalimba3" }, - { eByteOrderLittle, 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba4 , "kalimba4" }, - { eByteOrderLittle, 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba5 , "kalimba5" } -}; + {eByteOrderBig, 4, 2, 4, llvm::Triple::mips, ArchSpec::eCore_mips32, + "mips"}, + {eByteOrderBig, 4, 2, 4, llvm::Triple::mips, ArchSpec::eCore_mips32r2, + "mipsr2"}, + {eByteOrderBig, 4, 2, 4, llvm::Triple::mips, ArchSpec::eCore_mips32r3, + "mipsr3"}, + {eByteOrderBig, 4, 2, 4, llvm::Triple::mips, ArchSpec::eCore_mips32r5, + "mipsr5"}, + {eByteOrderBig, 4, 2, 4, llvm::Triple::mips, ArchSpec::eCore_mips32r6, + "mipsr6"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32el, + "mipsel"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, + ArchSpec::eCore_mips32r2el, "mipsr2el"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, + ArchSpec::eCore_mips32r3el, "mipsr3el"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, + ArchSpec::eCore_mips32r5el, "mipsr5el"}, + {eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, + ArchSpec::eCore_mips32r6el, "mipsr6el"}, -// Ensure that we have an entry in the g_core_definitions for each core. If you comment out an entry above, + // mips64, mips64r2, mips64r3, mips64r5, mips64r6 + {eByteOrderBig, 8, 2, 4, llvm::Triple::mips64, ArchSpec::eCore_mips64, + "mips64"}, + {eByteOrderBig, 8, 2, 4, llvm::Triple::mips64, ArchSpec::eCore_mips64r2, + "mips64r2"}, + {eByteOrderBig, 8, 2, 4, llvm::Triple::mips64, ArchSpec::eCore_mips64r3, + "mips64r3"}, + {eByteOrderBig, 8, 2, 4, llvm::Triple::mips64, ArchSpec::eCore_mips64r5, + "mips64r5"}, + {eByteOrderBig, 8, 2, 4, llvm::Triple::mips64, ArchSpec::eCore_mips64r6, + "mips64r6"}, + {eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, + ArchSpec::eCore_mips64el, "mips64el"}, + {eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, + ArchSpec::eCore_mips64r2el, "mips64r2el"}, + {eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, + ArchSpec::eCore_mips64r3el, "mips64r3el"}, + {eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, + ArchSpec::eCore_mips64r5el, "mips64r5el"}, + {eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, + ArchSpec::eCore_mips64r6el, "mips64r6el"}, + + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_generic, + "powerpc"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc601, + "ppc601"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc602, + "ppc602"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc603, + "ppc603"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc603e, + "ppc603e"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc603ev, + "ppc603ev"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc604, + "ppc604"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc604e, + "ppc604e"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc620, + "ppc620"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc750, + "ppc750"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc7400, + "ppc7400"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc7450, + "ppc7450"}, + {eByteOrderBig, 4, 4, 4, llvm::Triple::ppc, ArchSpec::eCore_ppc_ppc970, + "ppc970"}, + + {eByteOrderBig, 8, 4, 4, llvm::Triple::ppc64, ArchSpec::eCore_ppc64_generic, + "powerpc64"}, + {eByteOrderBig, 8, 4, 4, llvm::Triple::ppc64, + ArchSpec::eCore_ppc64_ppc970_64, "ppc970-64"}, + + {eByteOrderBig, 8, 2, 6, llvm::Triple::systemz, + ArchSpec::eCore_s390x_generic, "s390x"}, + + {eByteOrderLittle, 4, 4, 4, llvm::Triple::sparc, + ArchSpec::eCore_sparc_generic, "sparc"}, + {eByteOrderLittle, 8, 4, 4, llvm::Triple::sparcv9, + ArchSpec::eCore_sparc9_generic, "sparcv9"}, + + {eByteOrderLittle, 4, 1, 15, llvm::Triple::x86, ArchSpec::eCore_x86_32_i386, + "i386"}, + {eByteOrderLittle, 4, 1, 15, llvm::Triple::x86, ArchSpec::eCore_x86_32_i486, + "i486"}, + {eByteOrderLittle, 4, 1, 15, llvm::Triple::x86, + ArchSpec::eCore_x86_32_i486sx, "i486sx"}, + {eByteOrderLittle, 4, 1, 15, llvm::Triple::x86, ArchSpec::eCore_x86_32_i686, + "i686"}, + + {eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64, + ArchSpec::eCore_x86_64_x86_64, "x86_64"}, + {eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64, + ArchSpec::eCore_x86_64_x86_64h, "x86_64h"}, + {eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon, + ArchSpec::eCore_hexagon_generic, "hexagon"}, + {eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon, + ArchSpec::eCore_hexagon_hexagonv4, "hexagonv4"}, + {eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon, + ArchSpec::eCore_hexagon_hexagonv5, "hexagonv5"}, + + {eByteOrderLittle, 4, 4, 4, llvm::Triple::UnknownArch, + ArchSpec::eCore_uknownMach32, "unknown-mach-32"}, + {eByteOrderLittle, 8, 4, 4, llvm::Triple::UnknownArch, + ArchSpec::eCore_uknownMach64, "unknown-mach-64"}, + + {eByteOrderBig, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba3, + "kalimba3"}, + {eByteOrderLittle, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba4, + "kalimba4"}, + {eByteOrderLittle, 4, 1, 1, llvm::Triple::kalimba, ArchSpec::eCore_kalimba5, + "kalimba5"}}; + +// Ensure that we have an entry in the g_core_definitions for each core. If you +// comment out an entry above, // you will need to comment out the corresponding ArchSpec::Core enumeration. -static_assert(sizeof(g_core_definitions) / sizeof(CoreDefinition) == ArchSpec::kNumCores, "make sure we have one core definition for each core"); - -struct ArchDefinitionEntry -{ - ArchSpec::Core core; - uint32_t cpu; - uint32_t sub; - uint32_t cpu_mask; - uint32_t sub_mask; +static_assert(sizeof(g_core_definitions) / sizeof(CoreDefinition) == + ArchSpec::kNumCores, + "make sure we have one core definition for each core"); + +struct ArchDefinitionEntry { + ArchSpec::Core core; + uint32_t cpu; + uint32_t sub; + uint32_t cpu_mask; + uint32_t sub_mask; }; -struct ArchDefinition -{ - ArchitectureType type; - size_t num_entries; - const ArchDefinitionEntry *entries; - const char *name; +struct ArchDefinition { + ArchitectureType type; + size_t num_entries; + const ArchDefinitionEntry *entries; + const char *name; }; -size_t -ArchSpec::AutoComplete (const char *name, StringList &matches) -{ - if (name && name[0]) - { - for (uint32_t i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) - { - if (NameMatches(g_core_definitions[i].name, eNameMatchStartsWith, name)) - matches.AppendString (g_core_definitions[i].name); - } +size_t ArchSpec::AutoComplete(const char *name, StringList &matches) { + if (name && name[0]) { + for (uint32_t i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) { + if (NameMatches(g_core_definitions[i].name, eNameMatchStartsWith, name)) + matches.AppendString(g_core_definitions[i].name); } - else - { - for (uint32_t i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) - matches.AppendString (g_core_definitions[i].name); - } - return matches.GetSize(); + } else { + for (uint32_t i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) + matches.AppendString(g_core_definitions[i].name); + } + return matches.GetSize(); } #define CPU_ANY (UINT32_MAX) @@ -203,267 +278,311 @@ ArchSpec::AutoComplete (const char *name, StringList &matches) // allows the precedence to be set when the table is built. #define SUBTYPE_MASK 0x00FFFFFFu -static const ArchDefinitionEntry g_macho_arch_entries[] = -{ - { ArchSpec::eCore_arm_generic , llvm::MachO::CPU_TYPE_ARM , CPU_ANY, UINT32_MAX , UINT32_MAX }, - { ArchSpec::eCore_arm_generic , llvm::MachO::CPU_TYPE_ARM , 0 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv4 , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv4t , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv6 , llvm::MachO::CPU_TYPE_ARM , 6 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv6m , llvm::MachO::CPU_TYPE_ARM , 14 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv5 , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv5e , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv5t , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_xscale , llvm::MachO::CPU_TYPE_ARM , 8 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7 , llvm::MachO::CPU_TYPE_ARM , 9 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7f , llvm::MachO::CPU_TYPE_ARM , 10 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7s , llvm::MachO::CPU_TYPE_ARM , 11 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7k , llvm::MachO::CPU_TYPE_ARM , 12 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7m , llvm::MachO::CPU_TYPE_ARM , 15 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_armv7em , llvm::MachO::CPU_TYPE_ARM , 16 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 1 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 0 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 13 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , CPU_ANY, UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumb , llvm::MachO::CPU_TYPE_ARM , 0 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv4t , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv5 , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv5e , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv6 , llvm::MachO::CPU_TYPE_ARM , 6 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv6m , llvm::MachO::CPU_TYPE_ARM , 14 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7 , llvm::MachO::CPU_TYPE_ARM , 9 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7f , llvm::MachO::CPU_TYPE_ARM , 10 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7s , llvm::MachO::CPU_TYPE_ARM , 11 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7k , llvm::MachO::CPU_TYPE_ARM , 12 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7m , llvm::MachO::CPU_TYPE_ARM , 15 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_thumbv7em , llvm::MachO::CPU_TYPE_ARM , 16 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_generic , llvm::MachO::CPU_TYPE_POWERPC , CPU_ANY, UINT32_MAX , UINT32_MAX }, - { ArchSpec::eCore_ppc_generic , llvm::MachO::CPU_TYPE_POWERPC , 0 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc601 , llvm::MachO::CPU_TYPE_POWERPC , 1 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc602 , llvm::MachO::CPU_TYPE_POWERPC , 2 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc603 , llvm::MachO::CPU_TYPE_POWERPC , 3 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc603e , llvm::MachO::CPU_TYPE_POWERPC , 4 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc603ev , llvm::MachO::CPU_TYPE_POWERPC , 5 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc604 , llvm::MachO::CPU_TYPE_POWERPC , 6 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc604e , llvm::MachO::CPU_TYPE_POWERPC , 7 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc620 , llvm::MachO::CPU_TYPE_POWERPC , 8 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc750 , llvm::MachO::CPU_TYPE_POWERPC , 9 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc7400 , llvm::MachO::CPU_TYPE_POWERPC , 10 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc7450 , llvm::MachO::CPU_TYPE_POWERPC , 11 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc_ppc970 , llvm::MachO::CPU_TYPE_POWERPC , 100 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc64_generic , llvm::MachO::CPU_TYPE_POWERPC64 , 0 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_ppc64_ppc970_64 , llvm::MachO::CPU_TYPE_POWERPC64 , 100 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_32_i386 , llvm::MachO::CPU_TYPE_I386 , 3 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_32_i486 , llvm::MachO::CPU_TYPE_I386 , 4 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_32_i486sx , llvm::MachO::CPU_TYPE_I386 , 0x84 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_32_i386 , llvm::MachO::CPU_TYPE_I386 , CPU_ANY, UINT32_MAX , UINT32_MAX }, - { ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , 3 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , 4 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_64_x86_64h , llvm::MachO::CPU_TYPE_X86_64 , 8 , UINT32_MAX , SUBTYPE_MASK }, - { ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , CPU_ANY, UINT32_MAX , UINT32_MAX }, - // Catch any unknown mach architectures so we can always use the object and symbol mach-o files - { ArchSpec::eCore_uknownMach32 , 0 , 0 , 0xFF000000u, 0x00000000u }, - { ArchSpec::eCore_uknownMach64 , llvm::MachO::CPU_ARCH_ABI64 , 0 , 0xFF000000u, 0x00000000u } -}; +static const ArchDefinitionEntry g_macho_arch_entries[] = { + {ArchSpec::eCore_arm_generic, llvm::MachO::CPU_TYPE_ARM, CPU_ANY, + UINT32_MAX, UINT32_MAX}, + {ArchSpec::eCore_arm_generic, llvm::MachO::CPU_TYPE_ARM, 0, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv4, llvm::MachO::CPU_TYPE_ARM, 5, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv4t, llvm::MachO::CPU_TYPE_ARM, 5, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv6, llvm::MachO::CPU_TYPE_ARM, 6, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv6m, llvm::MachO::CPU_TYPE_ARM, 14, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv5, llvm::MachO::CPU_TYPE_ARM, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv5e, llvm::MachO::CPU_TYPE_ARM, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv5t, llvm::MachO::CPU_TYPE_ARM, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_xscale, llvm::MachO::CPU_TYPE_ARM, 8, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7, llvm::MachO::CPU_TYPE_ARM, 9, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7f, llvm::MachO::CPU_TYPE_ARM, 10, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7s, llvm::MachO::CPU_TYPE_ARM, 11, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7k, llvm::MachO::CPU_TYPE_ARM, 12, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7m, llvm::MachO::CPU_TYPE_ARM, 15, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_armv7em, llvm::MachO::CPU_TYPE_ARM, 16, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_arm64, llvm::MachO::CPU_TYPE_ARM64, 1, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_arm64, llvm::MachO::CPU_TYPE_ARM64, 0, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_arm64, llvm::MachO::CPU_TYPE_ARM64, 13, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_arm_arm64, llvm::MachO::CPU_TYPE_ARM64, CPU_ANY, + UINT32_MAX, SUBTYPE_MASK}, + {ArchSpec::eCore_thumb, llvm::MachO::CPU_TYPE_ARM, 0, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv4t, llvm::MachO::CPU_TYPE_ARM, 5, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv5, llvm::MachO::CPU_TYPE_ARM, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv5e, llvm::MachO::CPU_TYPE_ARM, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv6, llvm::MachO::CPU_TYPE_ARM, 6, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv6m, llvm::MachO::CPU_TYPE_ARM, 14, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7, llvm::MachO::CPU_TYPE_ARM, 9, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7f, llvm::MachO::CPU_TYPE_ARM, 10, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7s, llvm::MachO::CPU_TYPE_ARM, 11, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7k, llvm::MachO::CPU_TYPE_ARM, 12, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7m, llvm::MachO::CPU_TYPE_ARM, 15, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_thumbv7em, llvm::MachO::CPU_TYPE_ARM, 16, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_generic, llvm::MachO::CPU_TYPE_POWERPC, CPU_ANY, + UINT32_MAX, UINT32_MAX}, + {ArchSpec::eCore_ppc_generic, llvm::MachO::CPU_TYPE_POWERPC, 0, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc601, llvm::MachO::CPU_TYPE_POWERPC, 1, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc602, llvm::MachO::CPU_TYPE_POWERPC, 2, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc603, llvm::MachO::CPU_TYPE_POWERPC, 3, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc603e, llvm::MachO::CPU_TYPE_POWERPC, 4, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc603ev, llvm::MachO::CPU_TYPE_POWERPC, 5, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc604, llvm::MachO::CPU_TYPE_POWERPC, 6, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc604e, llvm::MachO::CPU_TYPE_POWERPC, 7, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc620, llvm::MachO::CPU_TYPE_POWERPC, 8, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc750, llvm::MachO::CPU_TYPE_POWERPC, 9, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc7400, llvm::MachO::CPU_TYPE_POWERPC, 10, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc7450, llvm::MachO::CPU_TYPE_POWERPC, 11, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc_ppc970, llvm::MachO::CPU_TYPE_POWERPC, 100, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_ppc64_generic, llvm::MachO::CPU_TYPE_POWERPC64, 0, + UINT32_MAX, SUBTYPE_MASK}, + {ArchSpec::eCore_ppc64_ppc970_64, llvm::MachO::CPU_TYPE_POWERPC64, 100, + UINT32_MAX, SUBTYPE_MASK}, + {ArchSpec::eCore_x86_32_i386, llvm::MachO::CPU_TYPE_I386, 3, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_x86_32_i486, llvm::MachO::CPU_TYPE_I386, 4, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_x86_32_i486sx, llvm::MachO::CPU_TYPE_I386, 0x84, + UINT32_MAX, SUBTYPE_MASK}, + {ArchSpec::eCore_x86_32_i386, llvm::MachO::CPU_TYPE_I386, CPU_ANY, + UINT32_MAX, UINT32_MAX}, + {ArchSpec::eCore_x86_64_x86_64, llvm::MachO::CPU_TYPE_X86_64, 3, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_x86_64_x86_64, llvm::MachO::CPU_TYPE_X86_64, 4, UINT32_MAX, + SUBTYPE_MASK}, + {ArchSpec::eCore_x86_64_x86_64h, llvm::MachO::CPU_TYPE_X86_64, 8, + UINT32_MAX, SUBTYPE_MASK}, + {ArchSpec::eCore_x86_64_x86_64, llvm::MachO::CPU_TYPE_X86_64, CPU_ANY, + UINT32_MAX, UINT32_MAX}, + // Catch any unknown mach architectures so we can always use the object and + // symbol mach-o files + {ArchSpec::eCore_uknownMach32, 0, 0, 0xFF000000u, 0x00000000u}, + {ArchSpec::eCore_uknownMach64, llvm::MachO::CPU_ARCH_ABI64, 0, 0xFF000000u, + 0x00000000u}}; static const ArchDefinition g_macho_arch_def = { - eArchTypeMachO, - llvm::array_lengthof(g_macho_arch_entries), - g_macho_arch_entries, - "mach-o" -}; + eArchTypeMachO, llvm::array_lengthof(g_macho_arch_entries), + g_macho_arch_entries, "mach-o"}; //===----------------------------------------------------------------------===// // A table that gets searched linearly for matches. This table is used to // convert cpu type and subtypes to architecture names, and to convert // architecture names to cpu types and subtypes. The ordering is important and // allows the precedence to be set when the table is built. -static const ArchDefinitionEntry g_elf_arch_entries[] = -{ - { ArchSpec::eCore_sparc_generic , llvm::ELF::EM_SPARC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Sparc - { ArchSpec::eCore_x86_32_i386 , llvm::ELF::EM_386 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel 80386 - { ArchSpec::eCore_x86_32_i486 , llvm::ELF::EM_IAMCU , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel MCU // FIXME: is this correct? - { ArchSpec::eCore_ppc_generic , llvm::ELF::EM_PPC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC - { ArchSpec::eCore_ppc64_generic , llvm::ELF::EM_PPC64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC64 - { ArchSpec::eCore_arm_generic , llvm::ELF::EM_ARM , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM - { ArchSpec::eCore_arm_aarch64 , llvm::ELF::EM_AARCH64, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM64 - { ArchSpec::eCore_s390x_generic , llvm::ELF::EM_S390 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // SystemZ - { ArchSpec::eCore_sparc9_generic , llvm::ELF::EM_SPARCV9, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // SPARC V9 - { ArchSpec::eCore_x86_64_x86_64 , llvm::ELF::EM_X86_64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // AMD64 - { ArchSpec::eCore_mips32 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32 - { ArchSpec::eCore_mips32r2 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r2, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r2 - { ArchSpec::eCore_mips32r6 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r6, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r6 - { ArchSpec::eCore_mips32el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32el - { ArchSpec::eCore_mips32r2el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r2el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r2el - { ArchSpec::eCore_mips32r6el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r6el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r6el - { ArchSpec::eCore_mips64 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64 - { ArchSpec::eCore_mips64r2 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r2, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r2 - { ArchSpec::eCore_mips64r6 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r6, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r6 - { ArchSpec::eCore_mips64el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64el - { ArchSpec::eCore_mips64r2el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r2el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r2el - { ArchSpec::eCore_mips64r6el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r6el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r6el - { ArchSpec::eCore_hexagon_generic , llvm::ELF::EM_HEXAGON, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // HEXAGON - { ArchSpec::eCore_kalimba3 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v3, 0xFFFFFFFFu, 0xFFFFFFFFu }, // KALIMBA - { ArchSpec::eCore_kalimba4 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v4, 0xFFFFFFFFu, 0xFFFFFFFFu }, // KALIMBA - { ArchSpec::eCore_kalimba5 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v5, 0xFFFFFFFFu, 0xFFFFFFFFu } // KALIMBA +static const ArchDefinitionEntry g_elf_arch_entries[] = { + {ArchSpec::eCore_sparc_generic, llvm::ELF::EM_SPARC, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // Sparc + {ArchSpec::eCore_x86_32_i386, llvm::ELF::EM_386, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // Intel 80386 + {ArchSpec::eCore_x86_32_i486, llvm::ELF::EM_IAMCU, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // Intel MCU // FIXME: is this correct? + {ArchSpec::eCore_ppc_generic, llvm::ELF::EM_PPC, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // PowerPC + {ArchSpec::eCore_ppc64_generic, llvm::ELF::EM_PPC64, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // PowerPC64 + {ArchSpec::eCore_arm_generic, llvm::ELF::EM_ARM, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // ARM + {ArchSpec::eCore_arm_aarch64, llvm::ELF::EM_AARCH64, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // ARM64 + {ArchSpec::eCore_s390x_generic, llvm::ELF::EM_S390, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // SystemZ + {ArchSpec::eCore_sparc9_generic, llvm::ELF::EM_SPARCV9, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // SPARC V9 + {ArchSpec::eCore_x86_64_x86_64, llvm::ELF::EM_X86_64, LLDB_INVALID_CPUTYPE, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // AMD64 + {ArchSpec::eCore_mips32, llvm::ELF::EM_MIPS, ArchSpec::eMIPSSubType_mips32, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32 + {ArchSpec::eCore_mips32r2, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips32r2, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32r2 + {ArchSpec::eCore_mips32r6, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips32r6, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32r6 + {ArchSpec::eCore_mips32el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips32el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32el + {ArchSpec::eCore_mips32r2el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips32r2el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32r2el + {ArchSpec::eCore_mips32r6el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips32r6el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips32r6el + {ArchSpec::eCore_mips64, llvm::ELF::EM_MIPS, ArchSpec::eMIPSSubType_mips64, + 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64 + {ArchSpec::eCore_mips64r2, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips64r2, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64r2 + {ArchSpec::eCore_mips64r6, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips64r6, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64r6 + {ArchSpec::eCore_mips64el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips64el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64el + {ArchSpec::eCore_mips64r2el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips64r2el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64r2el + {ArchSpec::eCore_mips64r6el, llvm::ELF::EM_MIPS, + ArchSpec::eMIPSSubType_mips64r6el, 0xFFFFFFFFu, 0xFFFFFFFFu}, // mips64r6el + {ArchSpec::eCore_hexagon_generic, llvm::ELF::EM_HEXAGON, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // HEXAGON + {ArchSpec::eCore_kalimba3, llvm::ELF::EM_CSR_KALIMBA, + llvm::Triple::KalimbaSubArch_v3, 0xFFFFFFFFu, 0xFFFFFFFFu}, // KALIMBA + {ArchSpec::eCore_kalimba4, llvm::ELF::EM_CSR_KALIMBA, + llvm::Triple::KalimbaSubArch_v4, 0xFFFFFFFFu, 0xFFFFFFFFu}, // KALIMBA + {ArchSpec::eCore_kalimba5, llvm::ELF::EM_CSR_KALIMBA, + llvm::Triple::KalimbaSubArch_v5, 0xFFFFFFFFu, 0xFFFFFFFFu} // KALIMBA }; static const ArchDefinition g_elf_arch_def = { - eArchTypeELF, - llvm::array_lengthof(g_elf_arch_entries), - g_elf_arch_entries, + eArchTypeELF, llvm::array_lengthof(g_elf_arch_entries), g_elf_arch_entries, "elf", }; -static const ArchDefinitionEntry g_coff_arch_entries[] = -{ - { ArchSpec::eCore_x86_32_i386 , llvm::COFF::IMAGE_FILE_MACHINE_I386 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel 80x86 - { ArchSpec::eCore_ppc_generic , llvm::COFF::IMAGE_FILE_MACHINE_POWERPC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC - { ArchSpec::eCore_ppc_generic , llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC (with FPU) - { ArchSpec::eCore_arm_generic , llvm::COFF::IMAGE_FILE_MACHINE_ARM , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM - { ArchSpec::eCore_arm_armv7 , llvm::COFF::IMAGE_FILE_MACHINE_ARMNT , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARMv7 - { ArchSpec::eCore_thumb , llvm::COFF::IMAGE_FILE_MACHINE_THUMB , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARMv7 - { ArchSpec::eCore_x86_64_x86_64, llvm::COFF::IMAGE_FILE_MACHINE_AMD64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu } // AMD64 +static const ArchDefinitionEntry g_coff_arch_entries[] = { + {ArchSpec::eCore_x86_32_i386, llvm::COFF::IMAGE_FILE_MACHINE_I386, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // Intel 80x86 + {ArchSpec::eCore_ppc_generic, llvm::COFF::IMAGE_FILE_MACHINE_POWERPC, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // PowerPC + {ArchSpec::eCore_ppc_generic, llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // PowerPC (with FPU) + {ArchSpec::eCore_arm_generic, llvm::COFF::IMAGE_FILE_MACHINE_ARM, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // ARM + {ArchSpec::eCore_arm_armv7, llvm::COFF::IMAGE_FILE_MACHINE_ARMNT, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // ARMv7 + {ArchSpec::eCore_thumb, llvm::COFF::IMAGE_FILE_MACHINE_THUMB, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu}, // ARMv7 + {ArchSpec::eCore_x86_64_x86_64, llvm::COFF::IMAGE_FILE_MACHINE_AMD64, + LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu} // AMD64 }; static const ArchDefinition g_coff_arch_def = { - eArchTypeCOFF, - llvm::array_lengthof(g_coff_arch_entries), - g_coff_arch_entries, - "pe-coff", + eArchTypeCOFF, llvm::array_lengthof(g_coff_arch_entries), + g_coff_arch_entries, "pe-coff", }; //===----------------------------------------------------------------------===// // Table of all ArchDefinitions static const ArchDefinition *g_arch_definitions[] = { - &g_macho_arch_def, - &g_elf_arch_def, - &g_coff_arch_def -}; + &g_macho_arch_def, &g_elf_arch_def, &g_coff_arch_def}; -static const size_t k_num_arch_definitions = llvm::array_lengthof(g_arch_definitions); +static const size_t k_num_arch_definitions = + llvm::array_lengthof(g_arch_definitions); //===----------------------------------------------------------------------===// // Static helper functions. // Get the architecture definition for a given object type. -static const ArchDefinition * -FindArchDefinition (ArchitectureType arch_type) -{ - for (unsigned int i = 0; i < k_num_arch_definitions; ++i) - { - const ArchDefinition *def = g_arch_definitions[i]; - if (def->type == arch_type) - return def; - } - return nullptr; +static const ArchDefinition *FindArchDefinition(ArchitectureType arch_type) { + for (unsigned int i = 0; i < k_num_arch_definitions; ++i) { + const ArchDefinition *def = g_arch_definitions[i]; + if (def->type == arch_type) + return def; + } + return nullptr; } // Get an architecture definition by name. -static const CoreDefinition * -FindCoreDefinition (llvm::StringRef name) -{ - for (unsigned int i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) - { - if (name.equals_lower(g_core_definitions[i].name)) - return &g_core_definitions[i]; - } - return nullptr; +static const CoreDefinition *FindCoreDefinition(llvm::StringRef name) { + for (unsigned int i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) { + if (name.equals_lower(g_core_definitions[i].name)) + return &g_core_definitions[i]; + } + return nullptr; } -static inline const CoreDefinition * -FindCoreDefinition (ArchSpec::Core core) -{ - if (core >= 0 && core < llvm::array_lengthof(g_core_definitions)) - return &g_core_definitions[core]; - return nullptr; +static inline const CoreDefinition *FindCoreDefinition(ArchSpec::Core core) { + if (core >= 0 && core < llvm::array_lengthof(g_core_definitions)) + return &g_core_definitions[core]; + return nullptr; } // Get a definition entry by cpu type and subtype. static const ArchDefinitionEntry * -FindArchDefinitionEntry (const ArchDefinition *def, uint32_t cpu, uint32_t sub) -{ - if (def == nullptr) - return nullptr; - - const ArchDefinitionEntry *entries = def->entries; - for (size_t i = 0; i < def->num_entries; ++i) - { - if (entries[i].cpu == (cpu & entries[i].cpu_mask)) - if (entries[i].sub == (sub & entries[i].sub_mask)) - return &entries[i]; - } +FindArchDefinitionEntry(const ArchDefinition *def, uint32_t cpu, uint32_t sub) { + if (def == nullptr) return nullptr; + + const ArchDefinitionEntry *entries = def->entries; + for (size_t i = 0; i < def->num_entries; ++i) { + if (entries[i].cpu == (cpu & entries[i].cpu_mask)) + if (entries[i].sub == (sub & entries[i].sub_mask)) + return &entries[i]; + } + return nullptr; } static const ArchDefinitionEntry * -FindArchDefinitionEntry (const ArchDefinition *def, ArchSpec::Core core) -{ - if (def == nullptr) - return nullptr; - - const ArchDefinitionEntry *entries = def->entries; - for (size_t i = 0; i < def->num_entries; ++i) - { - if (entries[i].core == core) - return &entries[i]; - } +FindArchDefinitionEntry(const ArchDefinition *def, ArchSpec::Core core) { + if (def == nullptr) return nullptr; + + const ArchDefinitionEntry *entries = def->entries; + for (size_t i = 0; i < def->num_entries; ++i) { + if (entries[i].core == core) + return &entries[i]; + } + return nullptr; } //===----------------------------------------------------------------------===// // Constructors and destructors. -ArchSpec::ArchSpec() : - m_triple (), - m_core (kCore_invalid), - m_byte_order (eByteOrderInvalid), - m_flags (0), - m_distribution_id () -{ -} +ArchSpec::ArchSpec() + : m_triple(), m_core(kCore_invalid), m_byte_order(eByteOrderInvalid), + m_flags(0), m_distribution_id() {} -ArchSpec::ArchSpec (const char *triple_cstr, Platform *platform) : - m_triple (), - m_core (kCore_invalid), - m_byte_order (eByteOrderInvalid), - m_flags (0), - m_distribution_id () -{ - if (triple_cstr) - SetTriple(triple_cstr, platform); +ArchSpec::ArchSpec(const char *triple_cstr, Platform *platform) + : m_triple(), m_core(kCore_invalid), m_byte_order(eByteOrderInvalid), + m_flags(0), m_distribution_id() { + if (triple_cstr) + SetTriple(triple_cstr, platform); } - -ArchSpec::ArchSpec (const char *triple_cstr) : - m_triple (), - m_core (kCore_invalid), - m_byte_order (eByteOrderInvalid), - m_flags (0), - m_distribution_id () -{ - if (triple_cstr) - SetTriple(triple_cstr); +ArchSpec::ArchSpec(const char *triple_cstr) + : m_triple(), m_core(kCore_invalid), m_byte_order(eByteOrderInvalid), + m_flags(0), m_distribution_id() { + if (triple_cstr) + SetTriple(triple_cstr); } -ArchSpec::ArchSpec(const llvm::Triple &triple) : - m_triple (), - m_core (kCore_invalid), - m_byte_order (eByteOrderInvalid), - m_flags (0), - m_distribution_id () -{ - SetTriple(triple); +ArchSpec::ArchSpec(const llvm::Triple &triple) + : m_triple(), m_core(kCore_invalid), m_byte_order(eByteOrderInvalid), + m_flags(0), m_distribution_id() { + SetTriple(triple); } -ArchSpec::ArchSpec (ArchitectureType arch_type, uint32_t cpu, uint32_t subtype) : - m_triple (), - m_core (kCore_invalid), - m_byte_order (eByteOrderInvalid), - m_flags (0), - m_distribution_id () -{ - SetArchitecture (arch_type, cpu, subtype); +ArchSpec::ArchSpec(ArchitectureType arch_type, uint32_t cpu, uint32_t subtype) + : m_triple(), m_core(kCore_invalid), m_byte_order(eByteOrderInvalid), + m_flags(0), m_distribution_id() { + SetArchitecture(arch_type, cpu, subtype); } ArchSpec::~ArchSpec() = default; @@ -471,1007 +590,929 @@ ArchSpec::~ArchSpec() = default; //===----------------------------------------------------------------------===// // Assignment and initialization. -const ArchSpec& -ArchSpec::operator= (const ArchSpec& rhs) -{ - if (this != &rhs) - { - m_triple = rhs.m_triple; - m_core = rhs.m_core; - m_byte_order = rhs.m_byte_order; - m_distribution_id = rhs.m_distribution_id; - m_flags = rhs.m_flags; - } - return *this; +const ArchSpec &ArchSpec::operator=(const ArchSpec &rhs) { + if (this != &rhs) { + m_triple = rhs.m_triple; + m_core = rhs.m_core; + m_byte_order = rhs.m_byte_order; + m_distribution_id = rhs.m_distribution_id; + m_flags = rhs.m_flags; + } + return *this; } -void -ArchSpec::Clear() -{ - m_triple = llvm::Triple(); - m_core = kCore_invalid; - m_byte_order = eByteOrderInvalid; - m_distribution_id.Clear (); - m_flags = 0; +void ArchSpec::Clear() { + m_triple = llvm::Triple(); + m_core = kCore_invalid; + m_byte_order = eByteOrderInvalid; + m_distribution_id.Clear(); + m_flags = 0; } //===----------------------------------------------------------------------===// // Predicates. -const char * -ArchSpec::GetArchitectureName () const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - return core_def->name; - return "unknown"; +const char *ArchSpec::GetArchitectureName() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) + return core_def->name; + return "unknown"; } -bool -ArchSpec::IsMIPS() const -{ - const llvm::Triple::ArchType machine = GetMachine(); - if(machine == llvm::Triple::mips || - machine == llvm::Triple::mipsel || - machine == llvm::Triple::mips64 || - machine == llvm::Triple::mips64el) - return true; - return false; +bool ArchSpec::IsMIPS() const { + const llvm::Triple::ArchType machine = GetMachine(); + if (machine == llvm::Triple::mips || machine == llvm::Triple::mipsel || + machine == llvm::Triple::mips64 || machine == llvm::Triple::mips64el) + return true; + return false; } -std::string -ArchSpec::GetClangTargetCPU () -{ - std::string cpu; - const llvm::Triple::ArchType machine = GetMachine(); - - if (machine == llvm::Triple::mips || - machine == llvm::Triple::mipsel || - machine == llvm::Triple::mips64 || - machine == llvm::Triple::mips64el) - { - switch (m_core) - { - case ArchSpec::eCore_mips32: - case ArchSpec::eCore_mips32el: - cpu = "mips32"; break; - case ArchSpec::eCore_mips32r2: - case ArchSpec::eCore_mips32r2el: - cpu = "mips32r2"; break; - case ArchSpec::eCore_mips32r3: - case ArchSpec::eCore_mips32r3el: - cpu = "mips32r3"; break; - case ArchSpec::eCore_mips32r5: - case ArchSpec::eCore_mips32r5el: - cpu = "mips32r5"; break; - case ArchSpec::eCore_mips32r6: - case ArchSpec::eCore_mips32r6el: - cpu = "mips32r6"; break; - case ArchSpec::eCore_mips64: - case ArchSpec::eCore_mips64el: - cpu = "mips64"; break; - case ArchSpec::eCore_mips64r2: - case ArchSpec::eCore_mips64r2el: - cpu = "mips64r2"; break; - case ArchSpec::eCore_mips64r3: - case ArchSpec::eCore_mips64r3el: - cpu = "mips64r3"; break; - case ArchSpec::eCore_mips64r5: - case ArchSpec::eCore_mips64r5el: - cpu = "mips64r5"; break; - case ArchSpec::eCore_mips64r6: - case ArchSpec::eCore_mips64r6el: - cpu = "mips64r6"; break; - default: - break; - } +std::string ArchSpec::GetClangTargetCPU() { + std::string cpu; + const llvm::Triple::ArchType machine = GetMachine(); + + if (machine == llvm::Triple::mips || machine == llvm::Triple::mipsel || + machine == llvm::Triple::mips64 || machine == llvm::Triple::mips64el) { + switch (m_core) { + case ArchSpec::eCore_mips32: + case ArchSpec::eCore_mips32el: + cpu = "mips32"; + break; + case ArchSpec::eCore_mips32r2: + case ArchSpec::eCore_mips32r2el: + cpu = "mips32r2"; + break; + case ArchSpec::eCore_mips32r3: + case ArchSpec::eCore_mips32r3el: + cpu = "mips32r3"; + break; + case ArchSpec::eCore_mips32r5: + case ArchSpec::eCore_mips32r5el: + cpu = "mips32r5"; + break; + case ArchSpec::eCore_mips32r6: + case ArchSpec::eCore_mips32r6el: + cpu = "mips32r6"; + break; + case ArchSpec::eCore_mips64: + case ArchSpec::eCore_mips64el: + cpu = "mips64"; + break; + case ArchSpec::eCore_mips64r2: + case ArchSpec::eCore_mips64r2el: + cpu = "mips64r2"; + break; + case ArchSpec::eCore_mips64r3: + case ArchSpec::eCore_mips64r3el: + cpu = "mips64r3"; + break; + case ArchSpec::eCore_mips64r5: + case ArchSpec::eCore_mips64r5el: + cpu = "mips64r5"; + break; + case ArchSpec::eCore_mips64r6: + case ArchSpec::eCore_mips64r6el: + cpu = "mips64r6"; + break; + default: + break; } - return cpu; + } + return cpu; } -uint32_t -ArchSpec::GetMachOCPUType () const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - { - const ArchDefinitionEntry *arch_def = FindArchDefinitionEntry (&g_macho_arch_def, core_def->core); - if (arch_def) - { - return arch_def->cpu; - } +uint32_t ArchSpec::GetMachOCPUType() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) { + const ArchDefinitionEntry *arch_def = + FindArchDefinitionEntry(&g_macho_arch_def, core_def->core); + if (arch_def) { + return arch_def->cpu; } - return LLDB_INVALID_CPUTYPE; + } + return LLDB_INVALID_CPUTYPE; } -uint32_t -ArchSpec::GetMachOCPUSubType () const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - { - const ArchDefinitionEntry *arch_def = FindArchDefinitionEntry (&g_macho_arch_def, core_def->core); - if (arch_def) - { - return arch_def->sub; - } +uint32_t ArchSpec::GetMachOCPUSubType() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) { + const ArchDefinitionEntry *arch_def = + FindArchDefinitionEntry(&g_macho_arch_def, core_def->core); + if (arch_def) { + return arch_def->sub; } - return LLDB_INVALID_CPUTYPE; + } + return LLDB_INVALID_CPUTYPE; } -uint32_t -ArchSpec::GetDataByteSize () const -{ - switch (m_core) - { - case eCore_kalimba3: - return 4; - case eCore_kalimba4: - return 1; - case eCore_kalimba5: - return 4; - default: - return 1; - } +uint32_t ArchSpec::GetDataByteSize() const { + switch (m_core) { + case eCore_kalimba3: + return 4; + case eCore_kalimba4: return 1; + case eCore_kalimba5: + return 4; + default: + return 1; + } + return 1; } -uint32_t -ArchSpec::GetCodeByteSize () const -{ - switch (m_core) - { - case eCore_kalimba3: - return 4; - case eCore_kalimba4: - return 1; - case eCore_kalimba5: - return 1; - default: - return 1; - } +uint32_t ArchSpec::GetCodeByteSize() const { + switch (m_core) { + case eCore_kalimba3: + return 4; + case eCore_kalimba4: + return 1; + case eCore_kalimba5: + return 1; + default: return 1; + } + return 1; } -llvm::Triple::ArchType -ArchSpec::GetMachine () const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - return core_def->machine; +llvm::Triple::ArchType ArchSpec::GetMachine() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) + return core_def->machine; - return llvm::Triple::UnknownArch; + return llvm::Triple::UnknownArch; } -const ConstString& -ArchSpec::GetDistributionId () const -{ - return m_distribution_id; +const ConstString &ArchSpec::GetDistributionId() const { + return m_distribution_id; } -void -ArchSpec::SetDistributionId (const char* distribution_id) -{ - m_distribution_id.SetCString (distribution_id); +void ArchSpec::SetDistributionId(const char *distribution_id) { + m_distribution_id.SetCString(distribution_id); } -uint32_t -ArchSpec::GetAddressByteSize() const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - { - if (core_def->machine == llvm::Triple::mips64 || core_def->machine == llvm::Triple::mips64el) - { - // For N32/O32 applications Address size is 4 bytes. - if (m_flags & (eMIPSABI_N32 | eMIPSABI_O32)) - return 4; - } - return core_def->addr_byte_size; +uint32_t ArchSpec::GetAddressByteSize() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) { + if (core_def->machine == llvm::Triple::mips64 || + core_def->machine == llvm::Triple::mips64el) { + // For N32/O32 applications Address size is 4 bytes. + if (m_flags & (eMIPSABI_N32 | eMIPSABI_O32)) + return 4; } - return 0; + return core_def->addr_byte_size; + } + return 0; } -ByteOrder -ArchSpec::GetDefaultEndian () const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - return core_def->default_byte_order; - return eByteOrderInvalid; +ByteOrder ArchSpec::GetDefaultEndian() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) + return core_def->default_byte_order; + return eByteOrderInvalid; } -bool -ArchSpec::CharIsSignedByDefault () const -{ - switch (m_triple.getArch()) { - default: - return true; - - case llvm::Triple::aarch64: - case llvm::Triple::aarch64_be: - case llvm::Triple::arm: - case llvm::Triple::armeb: - case llvm::Triple::thumb: - case llvm::Triple::thumbeb: - return m_triple.isOSDarwin() || m_triple.isOSWindows(); - - case llvm::Triple::ppc: - case llvm::Triple::ppc64: - return m_triple.isOSDarwin(); - - case llvm::Triple::ppc64le: - case llvm::Triple::systemz: - case llvm::Triple::xcore: - return false; - } +bool ArchSpec::CharIsSignedByDefault() const { + switch (m_triple.getArch()) { + default: + return true; + + case llvm::Triple::aarch64: + case llvm::Triple::aarch64_be: + case llvm::Triple::arm: + case llvm::Triple::armeb: + case llvm::Triple::thumb: + case llvm::Triple::thumbeb: + return m_triple.isOSDarwin() || m_triple.isOSWindows(); + + case llvm::Triple::ppc: + case llvm::Triple::ppc64: + return m_triple.isOSDarwin(); + + case llvm::Triple::ppc64le: + case llvm::Triple::systemz: + case llvm::Triple::xcore: + return false; + } } -lldb::ByteOrder -ArchSpec::GetByteOrder () const -{ - if (m_byte_order == eByteOrderInvalid) - return GetDefaultEndian(); - return m_byte_order; +lldb::ByteOrder ArchSpec::GetByteOrder() const { + if (m_byte_order == eByteOrderInvalid) + return GetDefaultEndian(); + return m_byte_order; } //===----------------------------------------------------------------------===// // Mutators. -bool -ArchSpec::SetTriple (const llvm::Triple &triple) -{ - m_triple = triple; - - llvm::StringRef arch_name (m_triple.getArchName()); - const CoreDefinition *core_def = FindCoreDefinition (arch_name); - if (core_def) - { - m_core = core_def->core; - // Set the byte order to the default byte order for an architecture. - // This can be modified if needed for cases when cores handle both - // big and little endian - m_byte_order = core_def->default_byte_order; - } - else - { - Clear(); - } - - return IsValid(); +bool ArchSpec::SetTriple(const llvm::Triple &triple) { + m_triple = triple; + + llvm::StringRef arch_name(m_triple.getArchName()); + const CoreDefinition *core_def = FindCoreDefinition(arch_name); + if (core_def) { + m_core = core_def->core; + // Set the byte order to the default byte order for an architecture. + // This can be modified if needed for cases when cores handle both + // big and little endian + m_byte_order = core_def->default_byte_order; + } else { + Clear(); + } + + return IsValid(); } -static bool -ParseMachCPUDashSubtypeTriple (const char *triple_cstr, ArchSpec &arch) -{ - // Accept "12-10" or "12.10" as cpu type/subtype - if (isdigit(triple_cstr[0])) - { - char *end = nullptr; - errno = 0; - uint32_t cpu = (uint32_t)::strtoul (triple_cstr, &end, 0); - if (errno == 0 && cpu != 0 && end && ((*end == '-') || (*end == '.'))) - { - errno = 0; - uint32_t sub = (uint32_t)::strtoul (end + 1, &end, 0); - if (errno == 0 && end && ((*end == '-') || (*end == '.') || (*end == '\0'))) - { - if (arch.SetArchitecture (eArchTypeMachO, cpu, sub)) - { - if (*end == '-') - { - llvm::StringRef vendor_os (end + 1); - size_t dash_pos = vendor_os.find('-'); - if (dash_pos != llvm::StringRef::npos) - { - llvm::StringRef vendor_str(vendor_os.substr(0, dash_pos)); - arch.GetTriple().setVendorName(vendor_str); - const size_t vendor_start_pos = dash_pos+1; - dash_pos = vendor_os.find('-', vendor_start_pos); - if (dash_pos == llvm::StringRef::npos) - { - if (vendor_start_pos < vendor_os.size()) - arch.GetTriple().setOSName(vendor_os.substr(vendor_start_pos)); - } - else - { - arch.GetTriple().setOSName(vendor_os.substr(vendor_start_pos, dash_pos - vendor_start_pos)); - } - } - } - return true; - } +static bool ParseMachCPUDashSubtypeTriple(const char *triple_cstr, + ArchSpec &arch) { + // Accept "12-10" or "12.10" as cpu type/subtype + if (isdigit(triple_cstr[0])) { + char *end = nullptr; + errno = 0; + uint32_t cpu = (uint32_t)::strtoul(triple_cstr, &end, 0); + if (errno == 0 && cpu != 0 && end && ((*end == '-') || (*end == '.'))) { + errno = 0; + uint32_t sub = (uint32_t)::strtoul(end + 1, &end, 0); + if (errno == 0 && end && + ((*end == '-') || (*end == '.') || (*end == '\0'))) { + if (arch.SetArchitecture(eArchTypeMachO, cpu, sub)) { + if (*end == '-') { + llvm::StringRef vendor_os(end + 1); + size_t dash_pos = vendor_os.find('-'); + if (dash_pos != llvm::StringRef::npos) { + llvm::StringRef vendor_str(vendor_os.substr(0, dash_pos)); + arch.GetTriple().setVendorName(vendor_str); + const size_t vendor_start_pos = dash_pos + 1; + dash_pos = vendor_os.find('-', vendor_start_pos); + if (dash_pos == llvm::StringRef::npos) { + if (vendor_start_pos < vendor_os.size()) + arch.GetTriple().setOSName( + vendor_os.substr(vendor_start_pos)); + } else { + arch.GetTriple().setOSName(vendor_os.substr( + vendor_start_pos, dash_pos - vendor_start_pos)); + } } + } + return true; } + } } - return false; + } + return false; } -bool -ArchSpec::SetTriple (const char *triple_cstr) -{ - if (triple_cstr && triple_cstr[0]) - { - if (ParseMachCPUDashSubtypeTriple (triple_cstr, *this)) - return true; - - llvm::StringRef triple_stref (triple_cstr); - if (triple_stref.startswith (LLDB_ARCH_DEFAULT)) - { - // Special case for the current host default architectures... - if (triple_stref.equals (LLDB_ARCH_DEFAULT_32BIT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKind32); - else if (triple_stref.equals (LLDB_ARCH_DEFAULT_64BIT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKind64); - else if (triple_stref.equals (LLDB_ARCH_DEFAULT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); - } - else - { - std::string normalized_triple_sstr (llvm::Triple::normalize(triple_stref)); - triple_stref = normalized_triple_sstr; - SetTriple (llvm::Triple (triple_stref)); - } +bool ArchSpec::SetTriple(const char *triple_cstr) { + if (triple_cstr && triple_cstr[0]) { + if (ParseMachCPUDashSubtypeTriple(triple_cstr, *this)) + return true; + + llvm::StringRef triple_stref(triple_cstr); + if (triple_stref.startswith(LLDB_ARCH_DEFAULT)) { + // Special case for the current host default architectures... + if (triple_stref.equals(LLDB_ARCH_DEFAULT_32BIT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKind32); + else if (triple_stref.equals(LLDB_ARCH_DEFAULT_64BIT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKind64); + else if (triple_stref.equals(LLDB_ARCH_DEFAULT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); + } else { + std::string normalized_triple_sstr(llvm::Triple::normalize(triple_stref)); + triple_stref = normalized_triple_sstr; + SetTriple(llvm::Triple(triple_stref)); } - else - Clear(); - return IsValid(); + } else + Clear(); + return IsValid(); } -bool -ArchSpec::SetTriple (const char *triple_cstr, Platform *platform) -{ - if (triple_cstr && triple_cstr[0]) - { - if (ParseMachCPUDashSubtypeTriple (triple_cstr, *this)) - return true; - - llvm::StringRef triple_stref (triple_cstr); - if (triple_stref.startswith (LLDB_ARCH_DEFAULT)) - { - // Special case for the current host default architectures... - if (triple_stref.equals (LLDB_ARCH_DEFAULT_32BIT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKind32); - else if (triple_stref.equals (LLDB_ARCH_DEFAULT_64BIT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKind64); - else if (triple_stref.equals (LLDB_ARCH_DEFAULT)) - *this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); - } - else - { - ArchSpec raw_arch (triple_cstr); - - std::string normalized_triple_sstr (llvm::Triple::normalize(triple_stref)); - triple_stref = normalized_triple_sstr; - llvm::Triple normalized_triple (triple_stref); - - const bool os_specified = normalized_triple.getOSName().size() > 0; - const bool vendor_specified = normalized_triple.getVendorName().size() > 0; - const bool env_specified = normalized_triple.getEnvironmentName().size() > 0; - - // If we got an arch only, then default the vendor, os, environment - // to match the platform if one is supplied - if (!(os_specified || vendor_specified || env_specified)) - { - if (platform) - { - // If we were given a platform, use the platform's system - // architecture. If this is not available (might not be - // connected) use the first supported architecture. - ArchSpec compatible_arch; - if (platform->IsCompatibleArchitecture (raw_arch, false, &compatible_arch)) - { - if (compatible_arch.IsValid()) - { - const llvm::Triple &compatible_triple = compatible_arch.GetTriple(); - if (!vendor_specified) - normalized_triple.setVendor(compatible_triple.getVendor()); - if (!os_specified) - normalized_triple.setOS(compatible_triple.getOS()); - if (!env_specified && compatible_triple.getEnvironmentName().size()) - normalized_triple.setEnvironment(compatible_triple.getEnvironment()); - } - } - else - { - *this = raw_arch; - return IsValid(); - } - } - else - { - // No platform specified, fall back to the host system for - // the default vendor, os, and environment. - llvm::Triple host_triple(llvm::sys::getDefaultTargetTriple()); - if (!vendor_specified) - normalized_triple.setVendor(host_triple.getVendor()); - if (!vendor_specified) - normalized_triple.setOS(host_triple.getOS()); - if (!env_specified && host_triple.getEnvironmentName().size()) - normalized_triple.setEnvironment(host_triple.getEnvironment()); - } +bool ArchSpec::SetTriple(const char *triple_cstr, Platform *platform) { + if (triple_cstr && triple_cstr[0]) { + if (ParseMachCPUDashSubtypeTriple(triple_cstr, *this)) + return true; + + llvm::StringRef triple_stref(triple_cstr); + if (triple_stref.startswith(LLDB_ARCH_DEFAULT)) { + // Special case for the current host default architectures... + if (triple_stref.equals(LLDB_ARCH_DEFAULT_32BIT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKind32); + else if (triple_stref.equals(LLDB_ARCH_DEFAULT_64BIT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKind64); + else if (triple_stref.equals(LLDB_ARCH_DEFAULT)) + *this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); + } else { + ArchSpec raw_arch(triple_cstr); + + std::string normalized_triple_sstr(llvm::Triple::normalize(triple_stref)); + triple_stref = normalized_triple_sstr; + llvm::Triple normalized_triple(triple_stref); + + const bool os_specified = normalized_triple.getOSName().size() > 0; + const bool vendor_specified = + normalized_triple.getVendorName().size() > 0; + const bool env_specified = + normalized_triple.getEnvironmentName().size() > 0; + + // If we got an arch only, then default the vendor, os, environment + // to match the platform if one is supplied + if (!(os_specified || vendor_specified || env_specified)) { + if (platform) { + // If we were given a platform, use the platform's system + // architecture. If this is not available (might not be + // connected) use the first supported architecture. + ArchSpec compatible_arch; + if (platform->IsCompatibleArchitecture(raw_arch, false, + &compatible_arch)) { + if (compatible_arch.IsValid()) { + const llvm::Triple &compatible_triple = + compatible_arch.GetTriple(); + if (!vendor_specified) + normalized_triple.setVendor(compatible_triple.getVendor()); + if (!os_specified) + normalized_triple.setOS(compatible_triple.getOS()); + if (!env_specified && + compatible_triple.getEnvironmentName().size()) + normalized_triple.setEnvironment( + compatible_triple.getEnvironment()); } - SetTriple (normalized_triple); + } else { + *this = raw_arch; + return IsValid(); + } + } else { + // No platform specified, fall back to the host system for + // the default vendor, os, and environment. + llvm::Triple host_triple(llvm::sys::getDefaultTargetTriple()); + if (!vendor_specified) + normalized_triple.setVendor(host_triple.getVendor()); + if (!vendor_specified) + normalized_triple.setOS(host_triple.getOS()); + if (!env_specified && host_triple.getEnvironmentName().size()) + normalized_triple.setEnvironment(host_triple.getEnvironment()); } + } + SetTriple(normalized_triple); } - else - Clear(); - return IsValid(); + } else + Clear(); + return IsValid(); } -void -ArchSpec::MergeFrom(const ArchSpec &other) -{ - if (TripleVendorIsUnspecifiedUnknown() && !other.TripleVendorIsUnspecifiedUnknown()) - GetTriple().setVendor(other.GetTriple().getVendor()); - if (TripleOSIsUnspecifiedUnknown() && !other.TripleOSIsUnspecifiedUnknown()) - GetTriple().setOS(other.GetTriple().getOS()); - if (GetTriple().getArch() == llvm::Triple::UnknownArch) - GetTriple().setArch(other.GetTriple().getArch()); - if (GetTriple().getEnvironment() == llvm::Triple::UnknownEnvironment && !TripleVendorWasSpecified()) - { - if (other.TripleVendorWasSpecified()) - GetTriple().setEnvironment(other.GetTriple().getEnvironment()); - } - // If this and other are both arm ArchSpecs and this ArchSpec is a generic "some kind of arm" - // spec but the other ArchSpec is a specific arm core, adopt the specific arm core. - if (GetTriple().getArch() == llvm::Triple::arm - && other.GetTriple().getArch() == llvm::Triple::arm - && IsCompatibleMatch (other) - && GetCore() == ArchSpec::eCore_arm_generic - && other.GetCore() != ArchSpec::eCore_arm_generic) - { - m_core = other.GetCore(); - CoreUpdated (true); - } +void ArchSpec::MergeFrom(const ArchSpec &other) { + if (TripleVendorIsUnspecifiedUnknown() && + !other.TripleVendorIsUnspecifiedUnknown()) + GetTriple().setVendor(other.GetTriple().getVendor()); + if (TripleOSIsUnspecifiedUnknown() && !other.TripleOSIsUnspecifiedUnknown()) + GetTriple().setOS(other.GetTriple().getOS()); + if (GetTriple().getArch() == llvm::Triple::UnknownArch) + GetTriple().setArch(other.GetTriple().getArch()); + if (GetTriple().getEnvironment() == llvm::Triple::UnknownEnvironment && + !TripleVendorWasSpecified()) { + if (other.TripleVendorWasSpecified()) + GetTriple().setEnvironment(other.GetTriple().getEnvironment()); + } + // If this and other are both arm ArchSpecs and this ArchSpec is a generic + // "some kind of arm" + // spec but the other ArchSpec is a specific arm core, adopt the specific arm + // core. + if (GetTriple().getArch() == llvm::Triple::arm && + other.GetTriple().getArch() == llvm::Triple::arm && + IsCompatibleMatch(other) && GetCore() == ArchSpec::eCore_arm_generic && + other.GetCore() != ArchSpec::eCore_arm_generic) { + m_core = other.GetCore(); + CoreUpdated(true); + } } -bool -ArchSpec::SetArchitecture (ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os) -{ - m_core = kCore_invalid; - bool update_triple = true; - const ArchDefinition *arch_def = FindArchDefinition(arch_type); - if (arch_def) - { - const ArchDefinitionEntry *arch_def_entry = FindArchDefinitionEntry (arch_def, cpu, sub); - if (arch_def_entry) - { - const CoreDefinition *core_def = FindCoreDefinition (arch_def_entry->core); - if (core_def) - { - m_core = core_def->core; - update_triple = false; - // Always use the architecture name because it might be more descriptive - // than the architecture enum ("armv7" -> llvm::Triple::arm). - m_triple.setArchName(llvm::StringRef(core_def->name)); - if (arch_type == eArchTypeMachO) - { - m_triple.setVendor (llvm::Triple::Apple); - - // Don't set the OS. It could be simulator, macosx, ios, watchos, tvos. We could - // get close with the cpu type - but we can't get it right all of the time. Better - // to leave this unset so other sections of code will set it when they have more - // information. - // NB: don't call m_triple.setOS (llvm::Triple::UnknownOS). That sets the OSName to - // "unknown" and the ArchSpec::TripleVendorWasSpecified() method says that any - // OSName setting means it was specified. - } - else if (arch_type == eArchTypeELF) - { - switch (os) - { - case llvm::ELF::ELFOSABI_AIX: m_triple.setOS (llvm::Triple::OSType::AIX); break; - case llvm::ELF::ELFOSABI_FREEBSD: m_triple.setOS (llvm::Triple::OSType::FreeBSD); break; - case llvm::ELF::ELFOSABI_GNU: m_triple.setOS (llvm::Triple::OSType::Linux); break; - case llvm::ELF::ELFOSABI_NETBSD: m_triple.setOS (llvm::Triple::OSType::NetBSD); break; - case llvm::ELF::ELFOSABI_OPENBSD: m_triple.setOS (llvm::Triple::OSType::OpenBSD); break; - case llvm::ELF::ELFOSABI_SOLARIS: m_triple.setOS (llvm::Triple::OSType::Solaris); break; - } - } - else - { - m_triple.setVendor (llvm::Triple::UnknownVendor); - m_triple.setOS (llvm::Triple::UnknownOS); - } - // Fall back onto setting the machine type if the arch by name failed... - if (m_triple.getArch () == llvm::Triple::UnknownArch) - m_triple.setArch (core_def->machine); - } +bool ArchSpec::SetArchitecture(ArchitectureType arch_type, uint32_t cpu, + uint32_t sub, uint32_t os) { + m_core = kCore_invalid; + bool update_triple = true; + const ArchDefinition *arch_def = FindArchDefinition(arch_type); + if (arch_def) { + const ArchDefinitionEntry *arch_def_entry = + FindArchDefinitionEntry(arch_def, cpu, sub); + if (arch_def_entry) { + const CoreDefinition *core_def = FindCoreDefinition(arch_def_entry->core); + if (core_def) { + m_core = core_def->core; + update_triple = false; + // Always use the architecture name because it might be more descriptive + // than the architecture enum ("armv7" -> llvm::Triple::arm). + m_triple.setArchName(llvm::StringRef(core_def->name)); + if (arch_type == eArchTypeMachO) { + m_triple.setVendor(llvm::Triple::Apple); + + // Don't set the OS. It could be simulator, macosx, ios, watchos, + // tvos. We could + // get close with the cpu type - but we can't get it right all of the + // time. Better + // to leave this unset so other sections of code will set it when they + // have more + // information. + // NB: don't call m_triple.setOS (llvm::Triple::UnknownOS). That sets + // the OSName to + // "unknown" and the ArchSpec::TripleVendorWasSpecified() method says + // that any + // OSName setting means it was specified. + } else if (arch_type == eArchTypeELF) { + switch (os) { + case llvm::ELF::ELFOSABI_AIX: + m_triple.setOS(llvm::Triple::OSType::AIX); + break; + case llvm::ELF::ELFOSABI_FREEBSD: + m_triple.setOS(llvm::Triple::OSType::FreeBSD); + break; + case llvm::ELF::ELFOSABI_GNU: + m_triple.setOS(llvm::Triple::OSType::Linux); + break; + case llvm::ELF::ELFOSABI_NETBSD: + m_triple.setOS(llvm::Triple::OSType::NetBSD); + break; + case llvm::ELF::ELFOSABI_OPENBSD: + m_triple.setOS(llvm::Triple::OSType::OpenBSD); + break; + case llvm::ELF::ELFOSABI_SOLARIS: + m_triple.setOS(llvm::Triple::OSType::Solaris); + break; + } + } else { + m_triple.setVendor(llvm::Triple::UnknownVendor); + m_triple.setOS(llvm::Triple::UnknownOS); } + // Fall back onto setting the machine type if the arch by name failed... + if (m_triple.getArch() == llvm::Triple::UnknownArch) + m_triple.setArch(core_def->machine); + } } - CoreUpdated(update_triple); - return IsValid(); + } + CoreUpdated(update_triple); + return IsValid(); } -uint32_t -ArchSpec::GetMinimumOpcodeByteSize() const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - return core_def->min_opcode_byte_size; - return 0; +uint32_t ArchSpec::GetMinimumOpcodeByteSize() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) + return core_def->min_opcode_byte_size; + return 0; } -uint32_t -ArchSpec::GetMaximumOpcodeByteSize() const -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - return core_def->max_opcode_byte_size; - return 0; +uint32_t ArchSpec::GetMaximumOpcodeByteSize() const { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) + return core_def->max_opcode_byte_size; + return 0; } -bool -ArchSpec::IsExactMatch (const ArchSpec& rhs) const -{ - return IsEqualTo (rhs, true); +bool ArchSpec::IsExactMatch(const ArchSpec &rhs) const { + return IsEqualTo(rhs, true); } -bool -ArchSpec::IsCompatibleMatch (const ArchSpec& rhs) const -{ - return IsEqualTo (rhs, false); +bool ArchSpec::IsCompatibleMatch(const ArchSpec &rhs) const { + return IsEqualTo(rhs, false); } -static bool -isCompatibleEnvironment(llvm::Triple::EnvironmentType lhs, llvm::Triple::EnvironmentType rhs) -{ - if (lhs == rhs) - return true; - - // If any of the environment is unknown then they are compatible - if (lhs == llvm::Triple::UnknownEnvironment || rhs == llvm::Triple::UnknownEnvironment) - return true; +static bool isCompatibleEnvironment(llvm::Triple::EnvironmentType lhs, + llvm::Triple::EnvironmentType rhs) { + if (lhs == rhs) + return true; + + // If any of the environment is unknown then they are compatible + if (lhs == llvm::Triple::UnknownEnvironment || + rhs == llvm::Triple::UnknownEnvironment) + return true; + + // If one of the environment is Android and the other one is EABI then they + // are considered to + // be compatible. This is required as a workaround for shared libraries + // compiled for Android + // without the NOTE section indicating that they are using the Android ABI. + if ((lhs == llvm::Triple::Android && rhs == llvm::Triple::EABI) || + (rhs == llvm::Triple::Android && lhs == llvm::Triple::EABI) || + (lhs == llvm::Triple::GNUEABI && rhs == llvm::Triple::EABI) || + (rhs == llvm::Triple::GNUEABI && lhs == llvm::Triple::EABI) || + (lhs == llvm::Triple::GNUEABIHF && rhs == llvm::Triple::EABIHF) || + (rhs == llvm::Triple::GNUEABIHF && lhs == llvm::Triple::EABIHF)) + return true; + + return false; +} - // If one of the environment is Android and the other one is EABI then they are considered to - // be compatible. This is required as a workaround for shared libraries compiled for Android - // without the NOTE section indicating that they are using the Android ABI. - if ((lhs == llvm::Triple::Android && rhs == llvm::Triple::EABI) || - (rhs == llvm::Triple::Android && lhs == llvm::Triple::EABI) || - (lhs == llvm::Triple::GNUEABI && rhs == llvm::Triple::EABI) || - (rhs == llvm::Triple::GNUEABI && lhs == llvm::Triple::EABI) || - (lhs == llvm::Triple::GNUEABIHF && rhs == llvm::Triple::EABIHF) || - (rhs == llvm::Triple::GNUEABIHF && lhs == llvm::Triple::EABIHF)) - return true; +bool ArchSpec::IsEqualTo(const ArchSpec &rhs, bool exact_match) const { + // explicitly ignoring m_distribution_id in this method. + if (GetByteOrder() != rhs.GetByteOrder()) return false; -} -bool -ArchSpec::IsEqualTo (const ArchSpec& rhs, bool exact_match) const -{ - // explicitly ignoring m_distribution_id in this method. + const ArchSpec::Core lhs_core = GetCore(); + const ArchSpec::Core rhs_core = rhs.GetCore(); + + const bool core_match = cores_match(lhs_core, rhs_core, true, exact_match); - if (GetByteOrder() != rhs.GetByteOrder()) + if (core_match) { + const llvm::Triple &lhs_triple = GetTriple(); + const llvm::Triple &rhs_triple = rhs.GetTriple(); + + const llvm::Triple::VendorType lhs_triple_vendor = lhs_triple.getVendor(); + const llvm::Triple::VendorType rhs_triple_vendor = rhs_triple.getVendor(); + if (lhs_triple_vendor != rhs_triple_vendor) { + const bool rhs_vendor_specified = rhs.TripleVendorWasSpecified(); + const bool lhs_vendor_specified = TripleVendorWasSpecified(); + // Both architectures had the vendor specified, so if they aren't + // equal then we return false + if (rhs_vendor_specified && lhs_vendor_specified) return false; - - const ArchSpec::Core lhs_core = GetCore (); - const ArchSpec::Core rhs_core = rhs.GetCore (); - - const bool core_match = cores_match (lhs_core, rhs_core, true, exact_match); - - if (core_match) - { - const llvm::Triple &lhs_triple = GetTriple(); - const llvm::Triple &rhs_triple = rhs.GetTriple(); - - const llvm::Triple::VendorType lhs_triple_vendor = lhs_triple.getVendor(); - const llvm::Triple::VendorType rhs_triple_vendor = rhs_triple.getVendor(); - if (lhs_triple_vendor != rhs_triple_vendor) - { - const bool rhs_vendor_specified = rhs.TripleVendorWasSpecified(); - const bool lhs_vendor_specified = TripleVendorWasSpecified(); - // Both architectures had the vendor specified, so if they aren't - // equal then we return false - if (rhs_vendor_specified && lhs_vendor_specified) - return false; - - // Only fail if both vendor types are not unknown - if (lhs_triple_vendor != llvm::Triple::UnknownVendor && - rhs_triple_vendor != llvm::Triple::UnknownVendor) - return false; - } - - const llvm::Triple::OSType lhs_triple_os = lhs_triple.getOS(); - const llvm::Triple::OSType rhs_triple_os = rhs_triple.getOS(); - if (lhs_triple_os != rhs_triple_os) - { - const bool rhs_os_specified = rhs.TripleOSWasSpecified(); - const bool lhs_os_specified = TripleOSWasSpecified(); - // Both architectures had the OS specified, so if they aren't - // equal then we return false - if (rhs_os_specified && lhs_os_specified) - return false; - - // Only fail if both os types are not unknown - if (lhs_triple_os != llvm::Triple::UnknownOS && - rhs_triple_os != llvm::Triple::UnknownOS) - return false; - } - const llvm::Triple::EnvironmentType lhs_triple_env = lhs_triple.getEnvironment(); - const llvm::Triple::EnvironmentType rhs_triple_env = rhs_triple.getEnvironment(); - - if (!isCompatibleEnvironment(lhs_triple_env, rhs_triple_env)) - return false; - return true; + // Only fail if both vendor types are not unknown + if (lhs_triple_vendor != llvm::Triple::UnknownVendor && + rhs_triple_vendor != llvm::Triple::UnknownVendor) + return false; } - return false; + + const llvm::Triple::OSType lhs_triple_os = lhs_triple.getOS(); + const llvm::Triple::OSType rhs_triple_os = rhs_triple.getOS(); + if (lhs_triple_os != rhs_triple_os) { + const bool rhs_os_specified = rhs.TripleOSWasSpecified(); + const bool lhs_os_specified = TripleOSWasSpecified(); + // Both architectures had the OS specified, so if they aren't + // equal then we return false + if (rhs_os_specified && lhs_os_specified) + return false; + + // Only fail if both os types are not unknown + if (lhs_triple_os != llvm::Triple::UnknownOS && + rhs_triple_os != llvm::Triple::UnknownOS) + return false; + } + + const llvm::Triple::EnvironmentType lhs_triple_env = + lhs_triple.getEnvironment(); + const llvm::Triple::EnvironmentType rhs_triple_env = + rhs_triple.getEnvironment(); + + if (!isCompatibleEnvironment(lhs_triple_env, rhs_triple_env)) + return false; + return true; + } + return false; } //===----------------------------------------------------------------------===// // Helper methods. -void -ArchSpec::CoreUpdated (bool update_triple) -{ - const CoreDefinition *core_def = FindCoreDefinition (m_core); - if (core_def) - { - if (update_triple) - m_triple = llvm::Triple(core_def->name, "unknown", "unknown"); - m_byte_order = core_def->default_byte_order; - } - else - { - if (update_triple) - m_triple = llvm::Triple(); - m_byte_order = eByteOrderInvalid; - } +void ArchSpec::CoreUpdated(bool update_triple) { + const CoreDefinition *core_def = FindCoreDefinition(m_core); + if (core_def) { + if (update_triple) + m_triple = llvm::Triple(core_def->name, "unknown", "unknown"); + m_byte_order = core_def->default_byte_order; + } else { + if (update_triple) + m_triple = llvm::Triple(); + m_byte_order = eByteOrderInvalid; + } } //===----------------------------------------------------------------------===// // Operators. -static bool -cores_match (const ArchSpec::Core core1, const ArchSpec::Core core2, bool try_inverse, bool enforce_exact_match) -{ - if (core1 == core2) +static bool cores_match(const ArchSpec::Core core1, const ArchSpec::Core core2, + bool try_inverse, bool enforce_exact_match) { + if (core1 == core2) + return true; + + switch (core1) { + case ArchSpec::kCore_any: + return true; + + case ArchSpec::eCore_arm_generic: + if (enforce_exact_match) + break; + LLVM_FALLTHROUGH; + case ArchSpec::kCore_arm_any: + if (core2 >= ArchSpec::kCore_arm_first && core2 <= ArchSpec::kCore_arm_last) + return true; + if (core2 >= ArchSpec::kCore_thumb_first && + core2 <= ArchSpec::kCore_thumb_last) + return true; + if (core2 == ArchSpec::kCore_arm_any) + return true; + break; + + case ArchSpec::kCore_x86_32_any: + if ((core2 >= ArchSpec::kCore_x86_32_first && + core2 <= ArchSpec::kCore_x86_32_last) || + (core2 == ArchSpec::kCore_x86_32_any)) + return true; + break; + + case ArchSpec::kCore_x86_64_any: + if ((core2 >= ArchSpec::kCore_x86_64_first && + core2 <= ArchSpec::kCore_x86_64_last) || + (core2 == ArchSpec::kCore_x86_64_any)) + return true; + break; + + case ArchSpec::kCore_ppc_any: + if ((core2 >= ArchSpec::kCore_ppc_first && + core2 <= ArchSpec::kCore_ppc_last) || + (core2 == ArchSpec::kCore_ppc_any)) + return true; + break; + + case ArchSpec::kCore_ppc64_any: + if ((core2 >= ArchSpec::kCore_ppc64_first && + core2 <= ArchSpec::kCore_ppc64_last) || + (core2 == ArchSpec::kCore_ppc64_any)) + return true; + break; + + case ArchSpec::eCore_arm_armv6m: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_generic) return true; + try_inverse = false; + if (core2 == ArchSpec::eCore_arm_armv7) + return true; + if (core2 == ArchSpec::eCore_arm_armv6m) + return true; + } + break; + + case ArchSpec::kCore_hexagon_any: + if ((core2 >= ArchSpec::kCore_hexagon_first && + core2 <= ArchSpec::kCore_hexagon_last) || + (core2 == ArchSpec::kCore_hexagon_any)) + return true; + break; + + // v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization + // Cortex-M0 - ARMv6-M - armv6m + // Cortex-M3 - ARMv7-M - armv7m + // Cortex-M4 - ARMv7E-M - armv7em + case ArchSpec::eCore_arm_armv7em: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_generic) + return true; + if (core2 == ArchSpec::eCore_arm_armv7m) + return true; + if (core2 == ArchSpec::eCore_arm_armv6m) + return true; + if (core2 == ArchSpec::eCore_arm_armv7) + return true; + try_inverse = true; + } + break; + + // v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization + // Cortex-M0 - ARMv6-M - armv6m + // Cortex-M3 - ARMv7-M - armv7m + // Cortex-M4 - ARMv7E-M - armv7em + case ArchSpec::eCore_arm_armv7m: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_generic) + return true; + if (core2 == ArchSpec::eCore_arm_armv6m) + return true; + if (core2 == ArchSpec::eCore_arm_armv7) + return true; + if (core2 == ArchSpec::eCore_arm_armv7em) + return true; + try_inverse = true; + } + break; - switch (core1) - { - case ArchSpec::kCore_any: + case ArchSpec::eCore_arm_armv7f: + case ArchSpec::eCore_arm_armv7k: + case ArchSpec::eCore_arm_armv7s: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_generic) return true; + if (core2 == ArchSpec::eCore_arm_armv7) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_arm_generic: - if (enforce_exact_match) - break; - LLVM_FALLTHROUGH; - case ArchSpec::kCore_arm_any: - if (core2 >= ArchSpec::kCore_arm_first && core2 <= ArchSpec::kCore_arm_last) - return true; - if (core2 >= ArchSpec::kCore_thumb_first && core2 <= ArchSpec::kCore_thumb_last) - return true; - if (core2 == ArchSpec::kCore_arm_any) - return true; - break; - - case ArchSpec::kCore_x86_32_any: - if ((core2 >= ArchSpec::kCore_x86_32_first && core2 <= ArchSpec::kCore_x86_32_last) || (core2 == ArchSpec::kCore_x86_32_any)) - return true; - break; - - case ArchSpec::kCore_x86_64_any: - if ((core2 >= ArchSpec::kCore_x86_64_first && core2 <= ArchSpec::kCore_x86_64_last) || (core2 == ArchSpec::kCore_x86_64_any)) - return true; - break; - - case ArchSpec::kCore_ppc_any: - if ((core2 >= ArchSpec::kCore_ppc_first && core2 <= ArchSpec::kCore_ppc_last) || (core2 == ArchSpec::kCore_ppc_any)) - return true; - break; - - case ArchSpec::kCore_ppc64_any: - if ((core2 >= ArchSpec::kCore_ppc64_first && core2 <= ArchSpec::kCore_ppc64_last) || (core2 == ArchSpec::kCore_ppc64_any)) - return true; - break; - - case ArchSpec::eCore_arm_armv6m: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_generic) - return true; - try_inverse = false; - if (core2 == ArchSpec::eCore_arm_armv7) - return true; - if (core2 == ArchSpec::eCore_arm_armv6m) - return true; - } - break; - - case ArchSpec::kCore_hexagon_any: - if ((core2 >= ArchSpec::kCore_hexagon_first && core2 <= ArchSpec::kCore_hexagon_last) || (core2 == ArchSpec::kCore_hexagon_any)) - return true; - break; - - // v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization - // Cortex-M0 - ARMv6-M - armv6m - // Cortex-M3 - ARMv7-M - armv7m - // Cortex-M4 - ARMv7E-M - armv7em - case ArchSpec::eCore_arm_armv7em: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_generic) - return true; - if (core2 == ArchSpec::eCore_arm_armv7m) - return true; - if (core2 == ArchSpec::eCore_arm_armv6m) - return true; - if (core2 == ArchSpec::eCore_arm_armv7) - return true; - try_inverse = true; - } - break; - - // v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization - // Cortex-M0 - ARMv6-M - armv6m - // Cortex-M3 - ARMv7-M - armv7m - // Cortex-M4 - ARMv7E-M - armv7em - case ArchSpec::eCore_arm_armv7m: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_generic) - return true; - if (core2 == ArchSpec::eCore_arm_armv6m) - return true; - if (core2 == ArchSpec::eCore_arm_armv7) - return true; - if (core2 == ArchSpec::eCore_arm_armv7em) - return true; - try_inverse = true; - } - break; - - case ArchSpec::eCore_arm_armv7f: - case ArchSpec::eCore_arm_armv7k: - case ArchSpec::eCore_arm_armv7s: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_generic) - return true; - if (core2 == ArchSpec::eCore_arm_armv7) - return true; - try_inverse = false; - } - break; - - case ArchSpec::eCore_x86_64_x86_64h: - if (!enforce_exact_match) - { - try_inverse = false; - if (core2 == ArchSpec::eCore_x86_64_x86_64) - return true; - } - break; - - case ArchSpec::eCore_arm_armv8: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_arm64) - return true; - if (core2 == ArchSpec::eCore_arm_aarch64) - return true; - try_inverse = false; - } - break; - - case ArchSpec::eCore_arm_aarch64: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_arm64) - return true; - if (core2 == ArchSpec::eCore_arm_armv8) - return true; - try_inverse = false; - } - break; - - case ArchSpec::eCore_arm_arm64: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_arm_aarch64) - return true; - if (core2 == ArchSpec::eCore_arm_armv8) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_x86_64_x86_64h: + if (!enforce_exact_match) { + try_inverse = false; + if (core2 == ArchSpec::eCore_x86_64_x86_64) + return true; + } + break; - case ArchSpec::eCore_mips32: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32_first && core2 <= ArchSpec::kCore_mips32_last) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_arm_armv8: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_arm64) + return true; + if (core2 == ArchSpec::eCore_arm_aarch64) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips32el: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= ArchSpec::kCore_mips32el_last) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_arm_aarch64: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_arm64) + return true; + if (core2 == ArchSpec::eCore_arm_armv8) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips64: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32_first && core2 <= ArchSpec::kCore_mips32_last) - return true; - if (core2 >= ArchSpec::kCore_mips64_first && core2 <= ArchSpec::kCore_mips64_last) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_arm_arm64: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_arm_aarch64) + return true; + if (core2 == ArchSpec::eCore_arm_armv8) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips64el: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= ArchSpec::kCore_mips32el_last) - return true; - if (core2 >= ArchSpec::kCore_mips64el_first && core2 <= ArchSpec::kCore_mips64el_last) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_mips32: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32_first && + core2 <= ArchSpec::kCore_mips32_last) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips64r2: - case ArchSpec::eCore_mips64r3: - case ArchSpec::eCore_mips64r5: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32_first && core2 <= (core1 - 10)) - return true; - if (core2 >= ArchSpec::kCore_mips64_first && core2 <= (core1 - 1)) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_mips32el: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32el_first && + core2 <= ArchSpec::kCore_mips32el_last) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips64r2el: - case ArchSpec::eCore_mips64r3el: - case ArchSpec::eCore_mips64r5el: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= (core1 - 10)) - return true; - if (core2 >= ArchSpec::kCore_mips64el_first && core2 <= (core1 - 1)) - return true; - try_inverse = false; - } - break; + case ArchSpec::eCore_mips64: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32_first && + core2 <= ArchSpec::kCore_mips32_last) + return true; + if (core2 >= ArchSpec::kCore_mips64_first && + core2 <= ArchSpec::kCore_mips64_last) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips32r2: - case ArchSpec::eCore_mips32r3: - case ArchSpec::eCore_mips32r5: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32_first && core2 <= core1) - return true; - } - break; + case ArchSpec::eCore_mips64el: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32el_first && + core2 <= ArchSpec::kCore_mips32el_last) + return true; + if (core2 >= ArchSpec::kCore_mips64el_first && + core2 <= ArchSpec::kCore_mips64el_last) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips32r2el: - case ArchSpec::eCore_mips32r3el: - case ArchSpec::eCore_mips32r5el: - if (!enforce_exact_match) - { - if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= core1) - return true; - } - break; + case ArchSpec::eCore_mips64r2: + case ArchSpec::eCore_mips64r3: + case ArchSpec::eCore_mips64r5: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32_first && core2 <= (core1 - 10)) + return true; + if (core2 >= ArchSpec::kCore_mips64_first && core2 <= (core1 - 1)) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips32r6: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6) - return true; - } - break; + case ArchSpec::eCore_mips64r2el: + case ArchSpec::eCore_mips64r3el: + case ArchSpec::eCore_mips64r5el: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= (core1 - 10)) + return true; + if (core2 >= ArchSpec::kCore_mips64el_first && core2 <= (core1 - 1)) + return true; + try_inverse = false; + } + break; - case ArchSpec::eCore_mips32r6el: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_mips32el || core2 == ArchSpec::eCore_mips32r6el) - return true; - } - break; + case ArchSpec::eCore_mips32r2: + case ArchSpec::eCore_mips32r3: + case ArchSpec::eCore_mips32r5: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32_first && core2 <= core1) + return true; + } + break; - case ArchSpec::eCore_mips64r6: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6) - return true; - if (core2 == ArchSpec::eCore_mips64 || core2 == ArchSpec::eCore_mips64r6) - return true; - } - break; + case ArchSpec::eCore_mips32r2el: + case ArchSpec::eCore_mips32r3el: + case ArchSpec::eCore_mips32r5el: + if (!enforce_exact_match) { + if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= core1) + return true; + } + break; - case ArchSpec::eCore_mips64r6el: - if (!enforce_exact_match) - { - if (core2 == ArchSpec::eCore_mips32el || core2 == ArchSpec::eCore_mips32r6el) - return true; - if (core2 == ArchSpec::eCore_mips64el || core2 == ArchSpec::eCore_mips64r6el) - return true; - } - break; + case ArchSpec::eCore_mips32r6: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6) + return true; + } + break; - default: - break; + case ArchSpec::eCore_mips32r6el: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_mips32el || + core2 == ArchSpec::eCore_mips32r6el) + return true; } - if (try_inverse) - return cores_match (core2, core1, false, enforce_exact_match); - return false; + break; + + case ArchSpec::eCore_mips64r6: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6) + return true; + if (core2 == ArchSpec::eCore_mips64 || core2 == ArchSpec::eCore_mips64r6) + return true; + } + break; + + case ArchSpec::eCore_mips64r6el: + if (!enforce_exact_match) { + if (core2 == ArchSpec::eCore_mips32el || + core2 == ArchSpec::eCore_mips32r6el) + return true; + if (core2 == ArchSpec::eCore_mips64el || + core2 == ArchSpec::eCore_mips64r6el) + return true; + } + break; + + default: + break; + } + if (try_inverse) + return cores_match(core2, core1, false, enforce_exact_match); + return false; } -bool -lldb_private::operator<(const ArchSpec& lhs, const ArchSpec& rhs) -{ - const ArchSpec::Core lhs_core = lhs.GetCore (); - const ArchSpec::Core rhs_core = rhs.GetCore (); - return lhs_core < rhs_core; +bool lldb_private::operator<(const ArchSpec &lhs, const ArchSpec &rhs) { + const ArchSpec::Core lhs_core = lhs.GetCore(); + const ArchSpec::Core rhs_core = rhs.GetCore(); + return lhs_core < rhs_core; } -static void -StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread) -{ - // We need to check if we are stopped in Thumb mode in a IT instruction - // and detect if the condition doesn't pass. If this is the case it means - // we won't actually execute this instruction. If this happens we need to - // clear the stop reason to no thread plans think we are stopped for a - // reason and the plans should keep going. - // - // We do this because when single stepping many ARM processes, debuggers - // often use the BVR/BCR registers that says "stop when the PC is not - // equal to its current value". This method of stepping means we can end - // up stopping on instructions inside an if/then block that wouldn't get - // executed. By fixing this we can stop the debugger from seeming like - // you stepped through both the "if" _and_ the "else" clause when source - // level stepping because the debugger stops regardless due to the BVR/BCR - // triggering a stop. - // - // It also means we can set breakpoints on instructions inside an an - // if/then block and correctly skip them if we use the BKPT instruction. - // The ARM and Thumb BKPT instructions are unconditional even when executed - // in a Thumb IT block. - // - // If your debugger inserts software traps in ARM/Thumb code, it will - // need to use 16 and 32 bit instruction for 16 and 32 bit thumb - // instructions respectively. If your debugger inserts a 16 bit thumb - // trap on top of a 32 bit thumb instruction for an opcode that is inside - // an if/then, it will change the it/then to conditionally execute your - // 16 bit trap and then cause your program to crash if it executes the - // trailing 16 bits (the second half of the 32 bit thumb instruction you - // partially overwrote). - - RegisterContextSP reg_ctx_sp (thread.GetRegisterContext()); - if (reg_ctx_sp) - { - const uint32_t cpsr = reg_ctx_sp->GetFlags(0); - if (cpsr != 0) - { - // Read the J and T bits to get the ISETSTATE - const uint32_t J = Bit32(cpsr, 24); - const uint32_t T = Bit32(cpsr, 5); - const uint32_t ISETSTATE = J << 1 | T; - if (ISETSTATE == 0) - { - // NOTE: I am pretty sure we want to enable the code below - // that detects when we stop on an instruction in ARM mode - // that is conditional and the condition doesn't pass. This - // can happen if you set a breakpoint on an instruction that - // is conditional. We currently will _always_ stop on the - // instruction which is bad. You can also run into this while - // single stepping and you could appear to run code in the "if" - // and in the "else" clause because it would stop at all of the - // conditional instructions in both. - // In such cases, we really don't want to stop at this location. - // I will check with the lldb-dev list first before I enable this. +static void StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread) { + // We need to check if we are stopped in Thumb mode in a IT instruction + // and detect if the condition doesn't pass. If this is the case it means + // we won't actually execute this instruction. If this happens we need to + // clear the stop reason to no thread plans think we are stopped for a + // reason and the plans should keep going. + // + // We do this because when single stepping many ARM processes, debuggers + // often use the BVR/BCR registers that says "stop when the PC is not + // equal to its current value". This method of stepping means we can end + // up stopping on instructions inside an if/then block that wouldn't get + // executed. By fixing this we can stop the debugger from seeming like + // you stepped through both the "if" _and_ the "else" clause when source + // level stepping because the debugger stops regardless due to the BVR/BCR + // triggering a stop. + // + // It also means we can set breakpoints on instructions inside an an + // if/then block and correctly skip them if we use the BKPT instruction. + // The ARM and Thumb BKPT instructions are unconditional even when executed + // in a Thumb IT block. + // + // If your debugger inserts software traps in ARM/Thumb code, it will + // need to use 16 and 32 bit instruction for 16 and 32 bit thumb + // instructions respectively. If your debugger inserts a 16 bit thumb + // trap on top of a 32 bit thumb instruction for an opcode that is inside + // an if/then, it will change the it/then to conditionally execute your + // 16 bit trap and then cause your program to crash if it executes the + // trailing 16 bits (the second half of the 32 bit thumb instruction you + // partially overwrote). + + RegisterContextSP reg_ctx_sp(thread.GetRegisterContext()); + if (reg_ctx_sp) { + const uint32_t cpsr = reg_ctx_sp->GetFlags(0); + if (cpsr != 0) { + // Read the J and T bits to get the ISETSTATE + const uint32_t J = Bit32(cpsr, 24); + const uint32_t T = Bit32(cpsr, 5); + const uint32_t ISETSTATE = J << 1 | T; + if (ISETSTATE == 0) { +// NOTE: I am pretty sure we want to enable the code below +// that detects when we stop on an instruction in ARM mode +// that is conditional and the condition doesn't pass. This +// can happen if you set a breakpoint on an instruction that +// is conditional. We currently will _always_ stop on the +// instruction which is bad. You can also run into this while +// single stepping and you could appear to run code in the "if" +// and in the "else" clause because it would stop at all of the +// conditional instructions in both. +// In such cases, we really don't want to stop at this location. +// I will check with the lldb-dev list first before I enable this. #if 0 // ARM mode: check for condition on intsruction const addr_t pc = reg_ctx_sp->GetPC(); @@ -1492,120 +1533,101 @@ StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread) } } #endif - } - else if (ISETSTATE == 1) - { - // Thumb mode - const uint32_t ITSTATE = Bits32 (cpsr, 15, 10) << 2 | Bits32 (cpsr, 26, 25); - if (ITSTATE != 0) - { - const uint32_t condition = Bits32(ITSTATE, 7, 4); - if (!ARMConditionPassed(condition, cpsr)) - { - // We ARE stopped in a Thumb IT instruction on an instruction whose - // condition doesn't pass so this instruction won't get executed. - // Regardless of why it stopped, we need to clear the stop info - thread.SetStopInfo (StopInfoSP()); - } - } - } + } else if (ISETSTATE == 1) { + // Thumb mode + const uint32_t ITSTATE = + Bits32(cpsr, 15, 10) << 2 | Bits32(cpsr, 26, 25); + if (ITSTATE != 0) { + const uint32_t condition = Bits32(ITSTATE, 7, 4); + if (!ARMConditionPassed(condition, cpsr)) { + // We ARE stopped in a Thumb IT instruction on an instruction whose + // condition doesn't pass so this instruction won't get executed. + // Regardless of why it stopped, we need to clear the stop info + thread.SetStopInfo(StopInfoSP()); + } } + } } + } } ArchSpec::StopInfoOverrideCallbackType -ArchSpec::GetStopInfoOverrideCallback () const -{ - const llvm::Triple::ArchType machine = GetMachine(); - if (machine == llvm::Triple::arm) - return StopInfoOverrideCallbackTypeARM; - return nullptr; +ArchSpec::GetStopInfoOverrideCallback() const { + const llvm::Triple::ArchType machine = GetMachine(); + if (machine == llvm::Triple::arm) + return StopInfoOverrideCallbackTypeARM; + return nullptr; } -bool -ArchSpec::IsFullySpecifiedTriple () const -{ - const auto& user_specified_triple = GetTriple(); - - bool user_triple_fully_specified = false; - - if ((user_specified_triple.getOS() != llvm::Triple::UnknownOS) || TripleOSWasSpecified()) - { - if ((user_specified_triple.getVendor() != llvm::Triple::UnknownVendor) || TripleVendorWasSpecified()) - { - const unsigned unspecified = 0; - if (user_specified_triple.getOSMajorVersion() != unspecified) - { - user_triple_fully_specified = true; - } - } +bool ArchSpec::IsFullySpecifiedTriple() const { + const auto &user_specified_triple = GetTriple(); + + bool user_triple_fully_specified = false; + + if ((user_specified_triple.getOS() != llvm::Triple::UnknownOS) || + TripleOSWasSpecified()) { + if ((user_specified_triple.getVendor() != llvm::Triple::UnknownVendor) || + TripleVendorWasSpecified()) { + const unsigned unspecified = 0; + if (user_specified_triple.getOSMajorVersion() != unspecified) { + user_triple_fully_specified = true; + } } - - return user_triple_fully_specified; + } + + return user_triple_fully_specified; } -void -ArchSpec::PiecewiseTripleCompare (const ArchSpec &other, - bool &arch_different, - bool &vendor_different, - bool &os_different, - bool &os_version_different, - bool &env_different) -{ - const llvm::Triple &me(GetTriple()); - const llvm::Triple &them(other.GetTriple()); - - arch_different = (me.getArch() != them.getArch()); - - vendor_different = (me.getVendor() != them.getVendor()); - - os_different = (me.getOS() != them.getOS()); - - os_version_different = (me.getOSMajorVersion() != them.getOSMajorVersion()); - - env_different = (me.getEnvironment() != them.getEnvironment()); +void ArchSpec::PiecewiseTripleCompare( + const ArchSpec &other, bool &arch_different, bool &vendor_different, + bool &os_different, bool &os_version_different, bool &env_different) { + const llvm::Triple &me(GetTriple()); + const llvm::Triple &them(other.GetTriple()); + + arch_different = (me.getArch() != them.getArch()); + + vendor_different = (me.getVendor() != them.getVendor()); + + os_different = (me.getOS() != them.getOS()); + + os_version_different = (me.getOSMajorVersion() != them.getOSMajorVersion()); + + env_different = (me.getEnvironment() != them.getEnvironment()); } -bool -ArchSpec::IsAlwaysThumbInstructions () const -{ - std::string Error; - if (GetTriple().getArch() == llvm::Triple::arm || GetTriple().getArch() == llvm::Triple::thumb) - { - // v. https://en.wikipedia.org/wiki/ARM_Cortex-M - // - // Cortex-M0 through Cortex-M7 are ARM processor cores which can only - // execute thumb instructions. We map the cores to arch names like this: - // - // Cortex-M0, Cortex-M0+, Cortex-M1: armv6m - // Cortex-M3: armv7m - // Cortex-M4, Cortex-M7: armv7em - - if (GetCore() == ArchSpec::Core::eCore_arm_armv7m - || GetCore() == ArchSpec::Core::eCore_arm_armv7em - || GetCore() == ArchSpec::Core::eCore_arm_armv6m) - { - return true; - } +bool ArchSpec::IsAlwaysThumbInstructions() const { + std::string Error; + if (GetTriple().getArch() == llvm::Triple::arm || + GetTriple().getArch() == llvm::Triple::thumb) { + // v. https://en.wikipedia.org/wiki/ARM_Cortex-M + // + // Cortex-M0 through Cortex-M7 are ARM processor cores which can only + // execute thumb instructions. We map the cores to arch names like this: + // + // Cortex-M0, Cortex-M0+, Cortex-M1: armv6m + // Cortex-M3: armv7m + // Cortex-M4, Cortex-M7: armv7em + + if (GetCore() == ArchSpec::Core::eCore_arm_armv7m || + GetCore() == ArchSpec::Core::eCore_arm_armv7em || + GetCore() == ArchSpec::Core::eCore_arm_armv6m) { + return true; } - return false; + } + return false; } -void -ArchSpec::DumpTriple(Stream &s) const -{ - const llvm::Triple &triple = GetTriple(); - llvm::StringRef arch_str = triple.getArchName(); - llvm::StringRef vendor_str = triple.getVendorName(); - llvm::StringRef os_str = triple.getOSName(); - llvm::StringRef environ_str = triple.getEnvironmentName(); - - s.Printf("%s-%s-%s", - arch_str.empty() ? "*" : arch_str.str().c_str(), - vendor_str.empty() ? "*" : vendor_str.str().c_str(), - os_str.empty() ? "*" : os_str.str().c_str() - ); - - if (!environ_str.empty()) - s.Printf("-%s", environ_str.str().c_str()); +void ArchSpec::DumpTriple(Stream &s) const { + const llvm::Triple &triple = GetTriple(); + llvm::StringRef arch_str = triple.getArchName(); + llvm::StringRef vendor_str = triple.getVendorName(); + llvm::StringRef os_str = triple.getOSName(); + llvm::StringRef environ_str = triple.getEnvironmentName(); + + s.Printf("%s-%s-%s", arch_str.empty() ? "*" : arch_str.str().c_str(), + vendor_str.empty() ? "*" : vendor_str.str().c_str(), + os_str.empty() ? "*" : os_str.str().c_str()); + + if (!environ_str.empty()) + s.Printf("-%s", environ_str.str().c_str()); } diff --git a/lldb/source/Core/Baton.cpp b/lldb/source/Core/Baton.cpp index 8bed01be883..1031e045c33 100644 --- a/lldb/source/Core/Baton.cpp +++ b/lldb/source/Core/Baton.cpp @@ -18,7 +18,4 @@ using namespace lldb; using namespace lldb_private; -void -Baton::GetDescription (Stream *s, lldb::DescriptionLevel level) const -{ -} +void Baton::GetDescription(Stream *s, lldb::DescriptionLevel level) const {} diff --git a/lldb/source/Core/Broadcaster.cpp b/lldb/source/Core/Broadcaster.cpp index fb93f7772fb..9f1ec53ac6b 100644 --- a/lldb/source/Core/Broadcaster.cpp +++ b/lldb/source/Core/Broadcaster.cpp @@ -13,533 +13,463 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Core/Log.h" #include "lldb/Core/Event.h" #include "lldb/Core/Listener.h" +#include "lldb/Core/Log.h" #include "lldb/Core/StreamString.h" using namespace lldb; using namespace lldb_private; -Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp, const char *name) : - m_broadcaster_sp(new BroadcasterImpl(*this)), - m_manager_sp(manager_sp), - m_broadcaster_name(name) -{ - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); - if (log) - log->Printf ("%p Broadcaster::Broadcaster(\"%s\")", - static_cast(this), GetBroadcasterName().AsCString()); +Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp, const char *name) + : m_broadcaster_sp(new BroadcasterImpl(*this)), m_manager_sp(manager_sp), + m_broadcaster_name(name) { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); + if (log) + log->Printf("%p Broadcaster::Broadcaster(\"%s\")", + static_cast(this), GetBroadcasterName().AsCString()); } Broadcaster::BroadcasterImpl::BroadcasterImpl(Broadcaster &broadcaster) - : m_broadcaster(broadcaster), m_listeners(), m_listeners_mutex(), m_hijacking_listeners(), m_hijacking_masks() -{ -} + : m_broadcaster(broadcaster), m_listeners(), m_listeners_mutex(), + m_hijacking_listeners(), m_hijacking_masks() {} -Broadcaster::~Broadcaster() -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); - if (log) - log->Printf ("%p Broadcaster::~Broadcaster(\"%s\")", - static_cast(this), m_broadcaster_name.AsCString()); +Broadcaster::~Broadcaster() { + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); + if (log) + log->Printf("%p Broadcaster::~Broadcaster(\"%s\")", + static_cast(this), m_broadcaster_name.AsCString()); - Clear(); + Clear(); } -void -Broadcaster::CheckInWithManager () -{ - if (m_manager_sp) - { - m_manager_sp->SignUpListenersForBroadcaster(*this); - } +void Broadcaster::CheckInWithManager() { + if (m_manager_sp) { + m_manager_sp->SignUpListenersForBroadcaster(*this); + } } llvm::SmallVector, 4> -Broadcaster::BroadcasterImpl::GetListeners() -{ - llvm::SmallVector, 4> listeners; - listeners.reserve(m_listeners.size()); - - for (auto it = m_listeners.begin(); it != m_listeners.end();) - { - lldb::ListenerSP curr_listener_sp(it->first.lock()); - if (curr_listener_sp && it->second) - { - listeners.emplace_back(std::move(curr_listener_sp), it->second); - ++it; +Broadcaster::BroadcasterImpl::GetListeners() { + llvm::SmallVector, 4> listeners; + listeners.reserve(m_listeners.size()); + + for (auto it = m_listeners.begin(); it != m_listeners.end();) { + lldb::ListenerSP curr_listener_sp(it->first.lock()); + if (curr_listener_sp && it->second) { + listeners.emplace_back(std::move(curr_listener_sp), it->second); + ++it; + } else + it = m_listeners.erase(it); + } + + return listeners; +} + +void Broadcaster::BroadcasterImpl::Clear() { + std::lock_guard guard(m_listeners_mutex); + + // Make sure the listener forgets about this broadcaster. We do + // this in the broadcaster in case the broadcaster object initiates + // the removal. + for (auto &pair : GetListeners()) + pair.first->BroadcasterWillDestruct(&m_broadcaster); + + m_listeners.clear(); +} + +Broadcaster *Broadcaster::BroadcasterImpl::GetBroadcaster() { + return &m_broadcaster; +} + +bool Broadcaster::BroadcasterImpl::GetEventNames( + Stream &s, uint32_t event_mask, bool prefix_with_broadcaster_name) const { + uint32_t num_names_added = 0; + if (event_mask && !m_event_names.empty()) { + event_names_map::const_iterator end = m_event_names.end(); + for (uint32_t bit = 1u, mask = event_mask; mask != 0 && bit != 0; + bit <<= 1, mask >>= 1) { + if (mask & 1) { + event_names_map::const_iterator pos = m_event_names.find(bit); + if (pos != end) { + if (num_names_added > 0) + s.PutCString(", "); + + if (prefix_with_broadcaster_name) { + s.PutCString(GetBroadcasterName()); + s.PutChar('.'); + } + s.PutCString(pos->second.c_str()); + ++num_names_added; } - else - it = m_listeners.erase(it); + } } - - return listeners; + } + return num_names_added > 0; } -void -Broadcaster::BroadcasterImpl::Clear() -{ - std::lock_guard guard(m_listeners_mutex); - - // Make sure the listener forgets about this broadcaster. We do - // this in the broadcaster in case the broadcaster object initiates - // the removal. - for(auto &pair : GetListeners()) - pair.first->BroadcasterWillDestruct (&m_broadcaster); - - m_listeners.clear(); -} +void Broadcaster::AddInitialEventsToListener( + const lldb::ListenerSP &listener_sp, uint32_t requested_events) {} -Broadcaster * -Broadcaster::BroadcasterImpl::GetBroadcaster() -{ - return &m_broadcaster; -} +uint32_t +Broadcaster::BroadcasterImpl::AddListener(const lldb::ListenerSP &listener_sp, + uint32_t event_mask) { + if (!listener_sp) + return 0; -bool -Broadcaster::BroadcasterImpl::GetEventNames (Stream &s, uint32_t event_mask, bool prefix_with_broadcaster_name) const -{ - uint32_t num_names_added = 0; - if (event_mask && !m_event_names.empty()) - { - event_names_map::const_iterator end = m_event_names.end(); - for (uint32_t bit=1u, mask=event_mask; mask != 0 && bit != 0; bit <<= 1, mask >>= 1) - { - if (mask & 1) - { - event_names_map::const_iterator pos = m_event_names.find(bit); - if (pos != end) - { - if (num_names_added > 0) - s.PutCString(", "); - - if (prefix_with_broadcaster_name) - { - s.PutCString (GetBroadcasterName()); - s.PutChar('.'); - } - s.PutCString(pos->second.c_str()); - ++num_names_added; - } - } - } - } - return num_names_added > 0; -} + std::lock_guard guard(m_listeners_mutex); -void -Broadcaster::AddInitialEventsToListener (const lldb::ListenerSP &listener_sp, uint32_t requested_events) -{ -} + // See if we already have this listener, and if so, update its mask -uint32_t -Broadcaster::BroadcasterImpl::AddListener (const lldb::ListenerSP &listener_sp, uint32_t event_mask) -{ - if (!listener_sp) - return 0; + bool handled = false; - std::lock_guard guard(m_listeners_mutex); + for (auto &pair : GetListeners()) { + if (pair.first == listener_sp) { + handled = true; + pair.second |= event_mask; + m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask); + break; + } + } - // See if we already have this listener, and if so, update its mask + if (!handled) { + // Grant a new listener the available event bits + m_listeners.push_back( + std::make_pair(lldb::ListenerWP(listener_sp), event_mask)); - bool handled = false; + // Individual broadcasters decide whether they have outstanding data when a + // listener attaches, and insert it into the listener with this method. + m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask); + } - for(auto &pair: GetListeners()) - { - if (pair.first == listener_sp) - { - handled = true; - pair.second |= event_mask; - m_broadcaster.AddInitialEventsToListener (listener_sp, event_mask); - break; - } - } + // Return the event bits that were granted to the listener + return event_mask; +} - if (!handled) - { - // Grant a new listener the available event bits - m_listeners.push_back(std::make_pair(lldb::ListenerWP(listener_sp), event_mask)); +bool Broadcaster::BroadcasterImpl::EventTypeHasListeners(uint32_t event_type) { + std::lock_guard guard(m_listeners_mutex); - // Individual broadcasters decide whether they have outstanding data when a - // listener attaches, and insert it into the listener with this method. - m_broadcaster.AddInitialEventsToListener (listener_sp, event_mask); - } + if (!m_hijacking_listeners.empty() && event_type & m_hijacking_masks.back()) + return true; - // Return the event bits that were granted to the listener - return event_mask; + for (auto &pair : GetListeners()) { + if (pair.second & event_type) + return true; + } + return false; } -bool -Broadcaster::BroadcasterImpl::EventTypeHasListeners (uint32_t event_type) -{ - std::lock_guard guard(m_listeners_mutex); - - if (!m_hijacking_listeners.empty() && event_type & m_hijacking_masks.back()) - return true; - - for(auto &pair: GetListeners()) - { - if (pair.second & event_type) - return true; - } +bool Broadcaster::BroadcasterImpl::RemoveListener( + lldb_private::Listener *listener, uint32_t event_mask) { + if (!listener) return false; -} -bool -Broadcaster::BroadcasterImpl::RemoveListener (lldb_private::Listener *listener, uint32_t event_mask) -{ - if (!listener) - return false; - - std::lock_guard guard(m_listeners_mutex); - for (auto &pair : GetListeners()) - { - if (pair.first.get() == listener) - { - pair.second &= ~event_mask; - return true; - } + std::lock_guard guard(m_listeners_mutex); + for (auto &pair : GetListeners()) { + if (pair.first.get() == listener) { + pair.second &= ~event_mask; + return true; } - return false; + } + return false; } -bool -Broadcaster::BroadcasterImpl::RemoveListener (const lldb::ListenerSP &listener_sp, uint32_t event_mask) -{ - return RemoveListener (listener_sp.get(), event_mask); +bool Broadcaster::BroadcasterImpl::RemoveListener( + const lldb::ListenerSP &listener_sp, uint32_t event_mask) { + return RemoveListener(listener_sp.get(), event_mask); } -void -Broadcaster::BroadcasterImpl::BroadcastEvent (EventSP &event_sp) -{ - return PrivateBroadcastEvent (event_sp, false); +void Broadcaster::BroadcasterImpl::BroadcastEvent(EventSP &event_sp) { + return PrivateBroadcastEvent(event_sp, false); } -void -Broadcaster::BroadcasterImpl::BroadcastEventIfUnique (EventSP &event_sp) -{ - return PrivateBroadcastEvent (event_sp, true); +void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(EventSP &event_sp) { + return PrivateBroadcastEvent(event_sp, true); } -void -Broadcaster::BroadcasterImpl::PrivateBroadcastEvent (EventSP &event_sp, bool unique) -{ - // Can't add a nullptr event... - if (!event_sp) - return; +void Broadcaster::BroadcasterImpl::PrivateBroadcastEvent(EventSP &event_sp, + bool unique) { + // Can't add a nullptr event... + if (!event_sp) + return; - // Update the broadcaster on this event - event_sp->SetBroadcaster (&m_broadcaster); + // Update the broadcaster on this event + event_sp->SetBroadcaster(&m_broadcaster); - const uint32_t event_type = event_sp->GetType(); + const uint32_t event_type = event_sp->GetType(); - std::lock_guard guard(m_listeners_mutex); + std::lock_guard guard(m_listeners_mutex); - ListenerSP hijacking_listener_sp; + ListenerSP hijacking_listener_sp; - if (!m_hijacking_listeners.empty()) - { - assert (!m_hijacking_masks.empty()); - hijacking_listener_sp = m_hijacking_listeners.back(); - if ((event_type & m_hijacking_masks.back()) == 0) - hijacking_listener_sp.reset(); - } + if (!m_hijacking_listeners.empty()) { + assert(!m_hijacking_masks.empty()); + hijacking_listener_sp = m_hijacking_listeners.back(); + if ((event_type & m_hijacking_masks.back()) == 0) + hijacking_listener_sp.reset(); + } - Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EVENTS)); - if (log) - { - StreamString event_description; - event_sp->Dump (&event_description); - log->Printf ("%p Broadcaster(\"%s\")::BroadcastEvent (event_sp = {%s}, unique =%i) hijack = %p", - static_cast(this), GetBroadcasterName(), - event_description.GetData(), unique, - static_cast(hijacking_listener_sp.get())); - } + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); + if (log) { + StreamString event_description; + event_sp->Dump(&event_description); + log->Printf("%p Broadcaster(\"%s\")::BroadcastEvent (event_sp = {%s}, " + "unique =%i) hijack = %p", + static_cast(this), GetBroadcasterName(), + event_description.GetData(), unique, + static_cast(hijacking_listener_sp.get())); + } - if (hijacking_listener_sp) - { - if (unique && hijacking_listener_sp->PeekAtNextEventForBroadcasterWithType (&m_broadcaster, event_type)) - return; - hijacking_listener_sp->AddEvent (event_sp); - } - else - { - for (auto &pair : GetListeners()) - { - if (!(pair.second & event_type)) - continue; - if (unique && pair.first->PeekAtNextEventForBroadcasterWithType (&m_broadcaster, event_type)) - continue; - - pair.first->AddEvent (event_sp); - } + if (hijacking_listener_sp) { + if (unique && + hijacking_listener_sp->PeekAtNextEventForBroadcasterWithType( + &m_broadcaster, event_type)) + return; + hijacking_listener_sp->AddEvent(event_sp); + } else { + for (auto &pair : GetListeners()) { + if (!(pair.second & event_type)) + continue; + if (unique && + pair.first->PeekAtNextEventForBroadcasterWithType(&m_broadcaster, + event_type)) + continue; + + pair.first->AddEvent(event_sp); } + } } -void -Broadcaster::BroadcasterImpl::BroadcastEvent (uint32_t event_type, EventData *event_data) -{ - EventSP event_sp (new Event (event_type, event_data)); - PrivateBroadcastEvent (event_sp, false); +void Broadcaster::BroadcasterImpl::BroadcastEvent(uint32_t event_type, + EventData *event_data) { + EventSP event_sp(new Event(event_type, event_data)); + PrivateBroadcastEvent(event_sp, false); } -void -Broadcaster::BroadcasterImpl::BroadcastEvent (uint32_t event_type, const lldb::EventDataSP &event_data_sp) -{ - EventSP event_sp (new Event (event_type, event_data_sp)); - PrivateBroadcastEvent (event_sp, false); +void Broadcaster::BroadcasterImpl::BroadcastEvent( + uint32_t event_type, const lldb::EventDataSP &event_data_sp) { + EventSP event_sp(new Event(event_type, event_data_sp)); + PrivateBroadcastEvent(event_sp, false); } -void -Broadcaster::BroadcasterImpl::BroadcastEventIfUnique (uint32_t event_type, EventData *event_data) -{ - EventSP event_sp (new Event (event_type, event_data)); - PrivateBroadcastEvent (event_sp, true); +void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique( + uint32_t event_type, EventData *event_data) { + EventSP event_sp(new Event(event_type, event_data)); + PrivateBroadcastEvent(event_sp, true); } -bool -Broadcaster::BroadcasterImpl::HijackBroadcaster (const lldb::ListenerSP &listener_sp, uint32_t event_mask) -{ - std::lock_guard guard(m_listeners_mutex); - - Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EVENTS)); - if (log) - log->Printf ("%p Broadcaster(\"%s\")::HijackBroadcaster (listener(\"%s\")=%p)", - static_cast(this), GetBroadcasterName(), - listener_sp->m_name.c_str(), static_cast(listener_sp.get())); - m_hijacking_listeners.push_back(listener_sp); - m_hijacking_masks.push_back(event_mask); - return true; +bool Broadcaster::BroadcasterImpl::HijackBroadcaster( + const lldb::ListenerSP &listener_sp, uint32_t event_mask) { + std::lock_guard guard(m_listeners_mutex); + + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); + if (log) + log->Printf( + "%p Broadcaster(\"%s\")::HijackBroadcaster (listener(\"%s\")=%p)", + static_cast(this), GetBroadcasterName(), + listener_sp->m_name.c_str(), static_cast(listener_sp.get())); + m_hijacking_listeners.push_back(listener_sp); + m_hijacking_masks.push_back(event_mask); + return true; } -bool -Broadcaster::BroadcasterImpl::IsHijackedForEvent (uint32_t event_mask) -{ - std::lock_guard guard(m_listeners_mutex); +bool Broadcaster::BroadcasterImpl::IsHijackedForEvent(uint32_t event_mask) { + std::lock_guard guard(m_listeners_mutex); - if (!m_hijacking_listeners.empty()) - return (event_mask & m_hijacking_masks.back()) != 0; - return false; + if (!m_hijacking_listeners.empty()) + return (event_mask & m_hijacking_masks.back()) != 0; + return false; } -const char * -Broadcaster::BroadcasterImpl::GetHijackingListenerName() -{ - if (m_hijacking_listeners.size()) - { - return m_hijacking_listeners.back()->GetName(); - } - else - { - return nullptr; - } +const char *Broadcaster::BroadcasterImpl::GetHijackingListenerName() { + if (m_hijacking_listeners.size()) { + return m_hijacking_listeners.back()->GetName(); + } else { + return nullptr; + } } -void -Broadcaster::BroadcasterImpl::RestoreBroadcaster () -{ - std::lock_guard guard(m_listeners_mutex); - - if (!m_hijacking_listeners.empty()) - { - Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EVENTS)); - if (log) - { - ListenerSP listener_sp = m_hijacking_listeners.back(); - log->Printf ("%p Broadcaster(\"%s\")::RestoreBroadcaster (about to pop listener(\"%s\")=%p)", - static_cast(this), - GetBroadcasterName(), - listener_sp->m_name.c_str(), static_cast(listener_sp.get())); - } - m_hijacking_listeners.pop_back(); +void Broadcaster::BroadcasterImpl::RestoreBroadcaster() { + std::lock_guard guard(m_listeners_mutex); + + if (!m_hijacking_listeners.empty()) { + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS)); + if (log) { + ListenerSP listener_sp = m_hijacking_listeners.back(); + log->Printf("%p Broadcaster(\"%s\")::RestoreBroadcaster (about to pop " + "listener(\"%s\")=%p)", + static_cast(this), GetBroadcasterName(), + listener_sp->m_name.c_str(), + static_cast(listener_sp.get())); } - if (!m_hijacking_masks.empty()) - m_hijacking_masks.pop_back(); + m_hijacking_listeners.pop_back(); + } + if (!m_hijacking_masks.empty()) + m_hijacking_masks.pop_back(); } -ConstString & -Broadcaster::GetBroadcasterClass() const -{ - static ConstString class_name ("lldb.anonymous"); - return class_name; +ConstString &Broadcaster::GetBroadcasterClass() const { + static ConstString class_name("lldb.anonymous"); + return class_name; } BroadcastEventSpec::BroadcastEventSpec(const BroadcastEventSpec &rhs) = default; -bool -BroadcastEventSpec::operator< (const BroadcastEventSpec &rhs) const -{ - if (GetBroadcasterClass() == rhs.GetBroadcasterClass()) - { - return GetEventBits() < rhs.GetEventBits(); - } - else - { - return GetBroadcasterClass() < rhs.GetBroadcasterClass(); - } +bool BroadcastEventSpec::operator<(const BroadcastEventSpec &rhs) const { + if (GetBroadcasterClass() == rhs.GetBroadcasterClass()) { + return GetEventBits() < rhs.GetEventBits(); + } else { + return GetBroadcasterClass() < rhs.GetBroadcasterClass(); + } } -BroadcastEventSpec & -BroadcastEventSpec::operator=(const BroadcastEventSpec &rhs) = default; +BroadcastEventSpec &BroadcastEventSpec:: +operator=(const BroadcastEventSpec &rhs) = default; + +BroadcasterManager::BroadcasterManager() : m_manager_mutex() {} -BroadcasterManager::BroadcasterManager() : m_manager_mutex() -{ +lldb::BroadcasterManagerSP BroadcasterManager::MakeBroadcasterManager() { + return BroadcasterManagerSP(new BroadcasterManager()); } -lldb::BroadcasterManagerSP -BroadcasterManager::MakeBroadcasterManager() -{ - return BroadcasterManagerSP(new BroadcasterManager()); +uint32_t BroadcasterManager::RegisterListenerForEvents( + const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) { + std::lock_guard guard(m_manager_mutex); + + collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end(); + uint32_t available_bits = event_spec.GetEventBits(); + + while (iter != end_iter && + (iter = find_if(iter, end_iter, + BroadcasterClassMatches( + event_spec.GetBroadcasterClass()))) != end_iter) { + available_bits &= ~((*iter).first.GetEventBits()); + iter++; + } + + if (available_bits != 0) { + m_event_map.insert(event_listener_key( + BroadcastEventSpec(event_spec.GetBroadcasterClass(), available_bits), + listener_sp)); + m_listeners.insert(listener_sp); + } + + return available_bits; } -uint32_t -BroadcasterManager::RegisterListenerForEvents (const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) -{ - std::lock_guard guard(m_manager_mutex); - - collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end(); - uint32_t available_bits = event_spec.GetEventBits(); - - while (iter != end_iter - && (iter = find_if (iter, end_iter, BroadcasterClassMatches(event_spec.GetBroadcasterClass()))) != end_iter) - { - available_bits &= ~((*iter).first.GetEventBits()); - iter++; - } - - if (available_bits != 0) - { - m_event_map.insert (event_listener_key (BroadcastEventSpec (event_spec.GetBroadcasterClass(), available_bits), listener_sp)); - m_listeners.insert(listener_sp); +bool BroadcasterManager::UnregisterListenerForEvents( + const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) { + std::lock_guard guard(m_manager_mutex); + bool removed_some = false; + + if (m_listeners.erase(listener_sp) == 0) + return false; + + ListenerMatchesAndSharedBits predicate(event_spec, listener_sp); + std::vector to_be_readded; + uint32_t event_bits_to_remove = event_spec.GetEventBits(); + + // Go through the map and delete the exact matches, and build a list of + // matches that weren't exact to re-add: + while (true) { + collection::iterator iter, end_iter = m_event_map.end(); + iter = find_if(m_event_map.begin(), end_iter, predicate); + if (iter == end_iter) { + break; + } else { + uint32_t iter_event_bits = (*iter).first.GetEventBits(); + removed_some = true; + + if (event_bits_to_remove != iter_event_bits) { + uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove; + to_be_readded.push_back(BroadcastEventSpec( + event_spec.GetBroadcasterClass(), new_event_bits)); + } + m_event_map.erase(iter); } - - return available_bits; + } + + // Okay now add back the bits that weren't completely removed: + for (size_t i = 0; i < to_be_readded.size(); i++) { + m_event_map.insert(event_listener_key(to_be_readded[i], listener_sp)); + } + + return removed_some; } -bool -BroadcasterManager::UnregisterListenerForEvents (const lldb::ListenerSP &listener_sp, BroadcastEventSpec event_spec) -{ - std::lock_guard guard(m_manager_mutex); - bool removed_some = false; - - if (m_listeners.erase(listener_sp) == 0) - return false; - - ListenerMatchesAndSharedBits predicate (event_spec, listener_sp); - std::vector to_be_readded; - uint32_t event_bits_to_remove = event_spec.GetEventBits(); - - // Go through the map and delete the exact matches, and build a list of matches that weren't exact to re-add: - while (true) - { - collection::iterator iter, end_iter = m_event_map.end(); - iter = find_if (m_event_map.begin(), end_iter, predicate); - if (iter == end_iter) - { - break; - } - else - { - uint32_t iter_event_bits = (*iter).first.GetEventBits(); - removed_some = true; - - if (event_bits_to_remove != iter_event_bits) - { - uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove; - to_be_readded.push_back(BroadcastEventSpec (event_spec.GetBroadcasterClass(), new_event_bits)); - } - m_event_map.erase (iter); - } - } - - // Okay now add back the bits that weren't completely removed: - for (size_t i = 0; i < to_be_readded.size(); i++) - { - m_event_map.insert (event_listener_key (to_be_readded[i], listener_sp)); - } - - return removed_some; +ListenerSP BroadcasterManager::GetListenerForEventSpec( + BroadcastEventSpec event_spec) const { + std::lock_guard guard(m_manager_mutex); + + collection::const_iterator iter, end_iter = m_event_map.end(); + iter = find_if(m_event_map.begin(), end_iter, + BroadcastEventSpecMatches(event_spec)); + if (iter != end_iter) + return (*iter).second; + else + return nullptr; } - -ListenerSP -BroadcasterManager::GetListenerForEventSpec (BroadcastEventSpec event_spec) const -{ - std::lock_guard guard(m_manager_mutex); - - collection::const_iterator iter, end_iter = m_event_map.end(); - iter = find_if (m_event_map.begin(), end_iter, BroadcastEventSpecMatches (event_spec)); - if (iter != end_iter) - return (*iter).second; + +void BroadcasterManager::RemoveListener(Listener *listener) { + std::lock_guard guard(m_manager_mutex); + ListenerMatchesPointer predicate(listener); + listener_collection::iterator iter = m_listeners.begin(), + end_iter = m_listeners.end(); + + std::find_if(iter, end_iter, predicate); + if (iter != end_iter) + m_listeners.erase(iter); + + while (true) { + collection::iterator iter, end_iter = m_event_map.end(); + iter = find_if(m_event_map.begin(), end_iter, predicate); + if (iter == end_iter) + break; else - return nullptr; + m_event_map.erase(iter); + } } -void -BroadcasterManager::RemoveListener(Listener *listener) -{ - std::lock_guard guard(m_manager_mutex); - ListenerMatchesPointer predicate (listener); - listener_collection::iterator iter = m_listeners.begin(), end_iter = m_listeners.end(); - - std::find_if (iter, end_iter, predicate); - if (iter != end_iter) - m_listeners.erase(iter); - - while (true) - { - collection::iterator iter, end_iter = m_event_map.end(); - iter = find_if (m_event_map.begin(), end_iter, predicate); - if (iter == end_iter) - break; - else - m_event_map.erase(iter); - } -} +void BroadcasterManager::RemoveListener(const lldb::ListenerSP &listener_sp) { + std::lock_guard guard(m_manager_mutex); + ListenerMatches predicate(listener_sp); -void -BroadcasterManager::RemoveListener (const lldb::ListenerSP &listener_sp) -{ - std::lock_guard guard(m_manager_mutex); - ListenerMatches predicate (listener_sp); - - if (m_listeners.erase (listener_sp) == 0) - return; - - while (true) - { - collection::iterator iter, end_iter = m_event_map.end(); - iter = find_if (m_event_map.begin(), end_iter, predicate); - if (iter == end_iter) - break; - else - m_event_map.erase(iter); - } + if (m_listeners.erase(listener_sp) == 0) + return; + + while (true) { + collection::iterator iter, end_iter = m_event_map.end(); + iter = find_if(m_event_map.begin(), end_iter, predicate); + if (iter == end_iter) + break; + else + m_event_map.erase(iter); + } } - -void -BroadcasterManager::SignUpListenersForBroadcaster (Broadcaster &broadcaster) -{ - std::lock_guard guard(m_manager_mutex); - - collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end(); - - while (iter != end_iter - && (iter = find_if (iter, end_iter, BroadcasterClassMatches(broadcaster.GetBroadcasterClass()))) != end_iter) - { - (*iter).second->StartListeningForEvents (&broadcaster, (*iter).first.GetEventBits()); - iter++; - } + +void BroadcasterManager::SignUpListenersForBroadcaster( + Broadcaster &broadcaster) { + std::lock_guard guard(m_manager_mutex); + + collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end(); + + while (iter != end_iter && + (iter = find_if(iter, end_iter, + BroadcasterClassMatches( + broadcaster.GetBroadcasterClass()))) != end_iter) { + (*iter).second->StartListeningForEvents(&broadcaster, + (*iter).first.GetEventBits()); + iter++; + } } -void -BroadcasterManager::Clear () -{ - std::lock_guard guard(m_manager_mutex); - listener_collection::iterator end_iter = m_listeners.end(); - - for (listener_collection::iterator iter = m_listeners.begin(); iter != end_iter; iter++) - (*iter)->BroadcasterManagerWillDestruct(this->shared_from_this()); - m_listeners.clear(); - m_event_map.clear(); +void BroadcasterManager::Clear() { + std::lock_guard guard(m_manager_mutex); + listener_collection::iterator end_iter = m_listeners.end(); + + for (listener_collection::iterator iter = m_listeners.begin(); + iter != end_iter; iter++) + (*iter)->BroadcasterManagerWillDestruct(this->shared_from_this()); + m_listeners.clear(); + m_event_map.clear(); } diff --git a/lldb/source/Core/Communication.cpp b/lldb/source/Core/Communication.cpp index dbd0f775eeb..a7114cea4ab 100644 --- a/lldb/source/Core/Communication.cpp +++ b/lldb/source/Core/Communication.cpp @@ -15,10 +15,10 @@ // Project includes #include "lldb/Core/Communication.h" #include "lldb/Core/Connection.h" +#include "lldb/Core/Event.h" #include "lldb/Core/Listener.h" #include "lldb/Core/Log.h" #include "lldb/Core/Timer.h" -#include "lldb/Core/Event.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostThread.h" #include "lldb/Host/ThreadLauncher.h" @@ -26,441 +26,398 @@ using namespace lldb; using namespace lldb_private; -ConstString & -Communication::GetStaticBroadcasterClass () -{ - static ConstString class_name ("lldb.communication"); - return class_name; +ConstString &Communication::GetStaticBroadcasterClass() { + static ConstString class_name("lldb.communication"); + return class_name; } Communication::Communication(const char *name) - : Broadcaster(nullptr, name), - m_connection_sp(), - m_read_thread_enabled(false), - m_read_thread_did_exit(false), - m_bytes(), - m_bytes_mutex(), - m_write_mutex(), - m_synchronize_mutex(), - m_callback(nullptr), - m_callback_baton(nullptr), - m_close_on_eof(true) + : Broadcaster(nullptr, name), m_connection_sp(), + m_read_thread_enabled(false), m_read_thread_did_exit(false), m_bytes(), + m_bytes_mutex(), m_write_mutex(), m_synchronize_mutex(), + m_callback(nullptr), m_callback_baton(nullptr), m_close_on_eof(true) { - lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, - "%p Communication::Communication (name = %s)", this, name); - - SetEventName(eBroadcastBitDisconnected, "disconnected"); - SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes"); - SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit"); - SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit"); - SetEventName(eBroadcastBitPacketAvailable, "packet available"); - SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input"); - - CheckInWithManager(); + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, + "%p Communication::Communication (name = %s)", this, name); + + SetEventName(eBroadcastBitDisconnected, "disconnected"); + SetEventName(eBroadcastBitReadThreadGotBytes, "got bytes"); + SetEventName(eBroadcastBitReadThreadDidExit, "read thread did exit"); + SetEventName(eBroadcastBitReadThreadShouldExit, "read thread should exit"); + SetEventName(eBroadcastBitPacketAvailable, "packet available"); + SetEventName(eBroadcastBitNoMorePendingInput, "no more pending input"); + + CheckInWithManager(); } -Communication::~Communication() -{ - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, - "%p Communication::~Communication (name = %s)", - this, GetBroadcasterName().AsCString()); - Clear(); +Communication::~Communication() { + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, + "%p Communication::~Communication (name = %s)", this, + GetBroadcasterName().AsCString()); + Clear(); } -void -Communication::Clear() -{ - SetReadThreadBytesReceivedCallback(nullptr, nullptr); - Disconnect(nullptr); - StopReadThread(nullptr); +void Communication::Clear() { + SetReadThreadBytesReceivedCallback(nullptr, nullptr); + Disconnect(nullptr); + StopReadThread(nullptr); } -ConnectionStatus -Communication::Connect (const char *url, Error *error_ptr) -{ - Clear(); +ConnectionStatus Communication::Connect(const char *url, Error *error_ptr) { + Clear(); - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Connect (url = %s)", this, url); + lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION, + "%p Communication::Connect (url = %s)", + this, url); - lldb::ConnectionSP connection_sp (m_connection_sp); - if (connection_sp) - return connection_sp->Connect (url, error_ptr); - if (error_ptr) - error_ptr->SetErrorString("Invalid connection."); - return eConnectionStatusNoConnection; + lldb::ConnectionSP connection_sp(m_connection_sp); + if (connection_sp) + return connection_sp->Connect(url, error_ptr); + if (error_ptr) + error_ptr->SetErrorString("Invalid connection."); + return eConnectionStatusNoConnection; } -ConnectionStatus -Communication::Disconnect (Error *error_ptr) -{ - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); - - lldb::ConnectionSP connection_sp (m_connection_sp); - if (connection_sp) - { - ConnectionStatus status = connection_sp->Disconnect (error_ptr); - // We currently don't protect connection_sp with any mutex for - // multi-threaded environments. So lets not nuke our connection class - // without putting some multi-threaded protections in. We also probably - // don't want to pay for the overhead it might cause if every time we - // access the connection we have to take a lock. - // - // This unique pointer will cleanup after itself when this object goes away, - // so there is no need to currently have it destroy itself immediately - // upon disconnnect. - //connection_sp.reset(); - return status; - } - return eConnectionStatusNoConnection; +ConnectionStatus Communication::Disconnect(Error *error_ptr) { + lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION, + "%p Communication::Disconnect ()", this); + + lldb::ConnectionSP connection_sp(m_connection_sp); + if (connection_sp) { + ConnectionStatus status = connection_sp->Disconnect(error_ptr); + // We currently don't protect connection_sp with any mutex for + // multi-threaded environments. So lets not nuke our connection class + // without putting some multi-threaded protections in. We also probably + // don't want to pay for the overhead it might cause if every time we + // access the connection we have to take a lock. + // + // This unique pointer will cleanup after itself when this object goes away, + // so there is no need to currently have it destroy itself immediately + // upon disconnnect. + // connection_sp.reset(); + return status; + } + return eConnectionStatusNoConnection; } -bool -Communication::IsConnected () const -{ - lldb::ConnectionSP connection_sp(m_connection_sp); - return (connection_sp ? connection_sp->IsConnected() : false); +bool Communication::IsConnected() const { + lldb::ConnectionSP connection_sp(m_connection_sp); + return (connection_sp ? connection_sp->IsConnected() : false); } -bool -Communication::HasConnection () const -{ - return m_connection_sp.get() != nullptr; +bool Communication::HasConnection() const { + return m_connection_sp.get() != nullptr; } -size_t -Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) -{ - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, - "%p Communication::Read (dst = %p, dst_len = %" PRIu64 ", timeout = %u usec) connection = %p", - this, - dst, - (uint64_t)dst_len, - timeout_usec, - m_connection_sp.get()); - - if (m_read_thread_enabled) - { - // We have a dedicated read thread that is getting data for us - size_t cached_bytes = GetCachedBytes (dst, dst_len); - if (cached_bytes > 0 || timeout_usec == 0) - { - status = eConnectionStatusSuccess; - return cached_bytes; - } - - if (!m_connection_sp) - { - if (error_ptr) - error_ptr->SetErrorString("Invalid connection."); - status = eConnectionStatusNoConnection; - return 0; - } - - ListenerSP listener_sp(Listener::MakeListener("Communication::Read")); - listener_sp->StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); - EventSP event_sp; - std::chrono::microseconds timeout = std::chrono::microseconds(0); - if (timeout_usec != UINT32_MAX) - timeout = std::chrono::microseconds(timeout_usec); - while (listener_sp->WaitForEvent(timeout, event_sp)) - { - const uint32_t event_type = event_sp->GetType(); - if (event_type & eBroadcastBitReadThreadGotBytes) - { - return GetCachedBytes (dst, dst_len); - } - - if (event_type & eBroadcastBitReadThreadDidExit) - { - if (GetCloseOnEOF ()) - Disconnect(nullptr); - break; - } - } - return 0; +size_t Communication::Read(void *dst, size_t dst_len, uint32_t timeout_usec, + ConnectionStatus &status, Error *error_ptr) { + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_COMMUNICATION, + "%p Communication::Read (dst = %p, dst_len = %" PRIu64 + ", timeout = %u usec) connection = %p", + this, dst, (uint64_t)dst_len, timeout_usec, m_connection_sp.get()); + + if (m_read_thread_enabled) { + // We have a dedicated read thread that is getting data for us + size_t cached_bytes = GetCachedBytes(dst, dst_len); + if (cached_bytes > 0 || timeout_usec == 0) { + status = eConnectionStatusSuccess; + return cached_bytes; } - // We aren't using a read thread, just read the data synchronously in this - // thread. - lldb::ConnectionSP connection_sp (m_connection_sp); - if (connection_sp) - { - return connection_sp->Read (dst, dst_len, timeout_usec, status, error_ptr); + if (!m_connection_sp) { + if (error_ptr) + error_ptr->SetErrorString("Invalid connection."); + status = eConnectionStatusNoConnection; + return 0; } - if (error_ptr) - error_ptr->SetErrorString("Invalid connection."); - status = eConnectionStatusNoConnection; + ListenerSP listener_sp(Listener::MakeListener("Communication::Read")); + listener_sp->StartListeningForEvents( + this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); + EventSP event_sp; + std::chrono::microseconds timeout = std::chrono::microseconds(0); + if (timeout_usec != UINT32_MAX) + timeout = std::chrono::microseconds(timeout_usec); + while (listener_sp->WaitForEvent(timeout, event_sp)) { + const uint32_t event_type = event_sp->GetType(); + if (event_type & eBroadcastBitReadThreadGotBytes) { + return GetCachedBytes(dst, dst_len); + } + + if (event_type & eBroadcastBitReadThreadDidExit) { + if (GetCloseOnEOF()) + Disconnect(nullptr); + break; + } + } return 0; + } + + // We aren't using a read thread, just read the data synchronously in this + // thread. + lldb::ConnectionSP connection_sp(m_connection_sp); + if (connection_sp) { + return connection_sp->Read(dst, dst_len, timeout_usec, status, error_ptr); + } + + if (error_ptr) + error_ptr->SetErrorString("Invalid connection."); + status = eConnectionStatusNoConnection; + return 0; } -size_t -Communication::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) -{ - lldb::ConnectionSP connection_sp (m_connection_sp); +size_t Communication::Write(const void *src, size_t src_len, + ConnectionStatus &status, Error *error_ptr) { + lldb::ConnectionSP connection_sp(m_connection_sp); - std::lock_guard guard(m_write_mutex); - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, - "%p Communication::Write (src = %p, src_len = %" PRIu64 ") connection = %p", - this, - src, - (uint64_t)src_len, - connection_sp.get()); + std::lock_guard guard(m_write_mutex); + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_COMMUNICATION, + "%p Communication::Write (src = %p, src_len = %" PRIu64 + ") connection = %p", + this, src, (uint64_t)src_len, connection_sp.get()); - if (connection_sp) - return connection_sp->Write (src, src_len, status, error_ptr); + if (connection_sp) + return connection_sp->Write(src, src_len, status, error_ptr); - if (error_ptr) - error_ptr->SetErrorString("Invalid connection."); - status = eConnectionStatusNoConnection; - return 0; + if (error_ptr) + error_ptr->SetErrorString("Invalid connection."); + status = eConnectionStatusNoConnection; + return 0; } -bool -Communication::StartReadThread (Error *error_ptr) -{ - if (error_ptr) - error_ptr->Clear(); +bool Communication::StartReadThread(Error *error_ptr) { + if (error_ptr) + error_ptr->Clear(); - if (m_read_thread.IsJoinable()) - return true; + if (m_read_thread.IsJoinable()) + return true; - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, - "%p Communication::StartReadThread ()", this); + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this); - char thread_name[1024]; - snprintf(thread_name, sizeof(thread_name), "", GetBroadcasterName().AsCString()); + char thread_name[1024]; + snprintf(thread_name, sizeof(thread_name), "", + GetBroadcasterName().AsCString()); - m_read_thread_enabled = true; - m_read_thread_did_exit = false; - m_read_thread = ThreadLauncher::LaunchThread(thread_name, Communication::ReadThread, this, error_ptr); - if (!m_read_thread.IsJoinable()) - m_read_thread_enabled = false; - return m_read_thread_enabled; + m_read_thread_enabled = true; + m_read_thread_did_exit = false; + m_read_thread = ThreadLauncher::LaunchThread( + thread_name, Communication::ReadThread, this, error_ptr); + if (!m_read_thread.IsJoinable()) + m_read_thread_enabled = false; + return m_read_thread_enabled; } -bool -Communication::StopReadThread (Error *error_ptr) -{ - if (!m_read_thread.IsJoinable()) - return true; +bool Communication::StopReadThread(Error *error_ptr) { + if (!m_read_thread.IsJoinable()) + return true; - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, - "%p Communication::StopReadThread ()", this); + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this); - m_read_thread_enabled = false; + m_read_thread_enabled = false; - BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr); + BroadcastEvent(eBroadcastBitReadThreadShouldExit, nullptr); - // error = m_read_thread.Cancel(); + // error = m_read_thread.Cancel(); - Error error = m_read_thread.Join(nullptr); - return error.Success(); + Error error = m_read_thread.Join(nullptr); + return error.Success(); } -bool -Communication::JoinReadThread (Error *error_ptr) -{ - if (!m_read_thread.IsJoinable()) - return true; +bool Communication::JoinReadThread(Error *error_ptr) { + if (!m_read_thread.IsJoinable()) + return true; - Error error = m_read_thread.Join(nullptr); - return error.Success(); + Error error = m_read_thread.Join(nullptr); + return error.Success(); } -size_t -Communication::GetCachedBytes (void *dst, size_t dst_len) -{ - std::lock_guard guard(m_bytes_mutex); - if (!m_bytes.empty()) - { - // If DST is nullptr and we have a thread, then return the number - // of bytes that are available so the caller can call again - if (dst == nullptr) - return m_bytes.size(); +size_t Communication::GetCachedBytes(void *dst, size_t dst_len) { + std::lock_guard guard(m_bytes_mutex); + if (!m_bytes.empty()) { + // If DST is nullptr and we have a thread, then return the number + // of bytes that are available so the caller can call again + if (dst == nullptr) + return m_bytes.size(); - const size_t len = std::min(dst_len, m_bytes.size()); + const size_t len = std::min(dst_len, m_bytes.size()); - ::memcpy (dst, m_bytes.c_str(), len); - m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); + ::memcpy(dst, m_bytes.c_str(), len); + m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); - return len; - } - return 0; + return len; + } + return 0; } -void -Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) -{ - lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, - "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64 ", broadcast = %i)", - this, bytes, (uint64_t)len, broadcast); - if ((bytes == nullptr || len == 0) - && (status != lldb::eConnectionStatusEndOfFile)) - return; - if (m_callback) - { - // If the user registered a callback, then call it and do not broadcast - m_callback (m_callback_baton, bytes, len); - } - else if (bytes != nullptr && len > 0) - { - std::lock_guard guard(m_bytes_mutex); - m_bytes.append ((const char *)bytes, len); - if (broadcast) - BroadcastEventIfUnique (eBroadcastBitReadThreadGotBytes); - } +void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len, + bool broadcast, + ConnectionStatus status) { + lldb_private::LogIfAnyCategoriesSet( + LIBLLDB_LOG_COMMUNICATION, + "%p Communication::AppendBytesToCache (src = %p, src_len = %" PRIu64 + ", broadcast = %i)", + this, bytes, (uint64_t)len, broadcast); + if ((bytes == nullptr || len == 0) && + (status != lldb::eConnectionStatusEndOfFile)) + return; + if (m_callback) { + // If the user registered a callback, then call it and do not broadcast + m_callback(m_callback_baton, bytes, len); + } else if (bytes != nullptr && len > 0) { + std::lock_guard guard(m_bytes_mutex); + m_bytes.append((const char *)bytes, len); + if (broadcast) + BroadcastEventIfUnique(eBroadcastBitReadThreadGotBytes); + } } -size_t -Communication::ReadFromConnection (void *dst, - size_t dst_len, - uint32_t timeout_usec, - ConnectionStatus &status, - Error *error_ptr) -{ - lldb::ConnectionSP connection_sp(m_connection_sp); - return (connection_sp ? connection_sp->Read(dst, dst_len, timeout_usec, status, error_ptr) : 0); +size_t Communication::ReadFromConnection(void *dst, size_t dst_len, + uint32_t timeout_usec, + ConnectionStatus &status, + Error *error_ptr) { + lldb::ConnectionSP connection_sp(m_connection_sp); + return ( + connection_sp + ? connection_sp->Read(dst, dst_len, timeout_usec, status, error_ptr) + : 0); } -bool -Communication::ReadThreadIsRunning () -{ - return m_read_thread_enabled; -} +bool Communication::ReadThreadIsRunning() { return m_read_thread_enabled; } -lldb::thread_result_t -Communication::ReadThread (lldb::thread_arg_t p) -{ - Communication *comm = (Communication *)p; - - Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); - - if (log) - log->Printf ("%p Communication::ReadThread () thread starting...", p); - - uint8_t buf[1024]; - - Error error; - ConnectionStatus status = eConnectionStatusSuccess; - bool done = false; - while (!done && comm->m_read_thread_enabled) - { - size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), 5 * TimeValue::MicroSecPerSec, status, &error); - if (bytes_read > 0) - comm->AppendBytesToCache (buf, bytes_read, true, status); - else if ((bytes_read == 0) - && status == eConnectionStatusEndOfFile) - { - if (comm->GetCloseOnEOF ()) - comm->Disconnect (); - comm->AppendBytesToCache (buf, bytes_read, true, status); - } - - switch (status) - { - case eConnectionStatusSuccess: - break; - - case eConnectionStatusEndOfFile: - done = true; - break; - case eConnectionStatusError: // Check GetError() for details - if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) - { - // EIO on a pipe is usually caused by remote shutdown - comm->Disconnect (); - done = true; - } - if (log) - error.LogIfError (log, - "%p Communication::ReadFromConnection () => status = %s", - p, - Communication::ConnectionStatusAsCString (status)); - break; - case eConnectionStatusInterrupted: // Synchronization signal from SynchronizeWithReadThread() - // The connection returns eConnectionStatusInterrupted only when there is no - // input pending to be read, so we can signal that. - comm->BroadcastEvent (eBroadcastBitNoMorePendingInput); - break; - case eConnectionStatusNoConnection: // No connection - case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection - done = true; - LLVM_FALLTHROUGH; - case eConnectionStatusTimedOut: // Request timed out - if (log) - error.LogIfError (log, - "%p Communication::ReadFromConnection () => status = %s", - p, - Communication::ConnectionStatusAsCString (status)); - break; - } +lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) { + Communication *comm = (Communication *)p; + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); + + if (log) + log->Printf("%p Communication::ReadThread () thread starting...", p); + + uint8_t buf[1024]; + + Error error; + ConnectionStatus status = eConnectionStatusSuccess; + bool done = false; + while (!done && comm->m_read_thread_enabled) { + size_t bytes_read = comm->ReadFromConnection( + buf, sizeof(buf), 5 * TimeValue::MicroSecPerSec, status, &error); + if (bytes_read > 0) + comm->AppendBytesToCache(buf, bytes_read, true, status); + else if ((bytes_read == 0) && status == eConnectionStatusEndOfFile) { + if (comm->GetCloseOnEOF()) + comm->Disconnect(); + comm->AppendBytesToCache(buf, bytes_read, true, status); } - log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION); - if (log) - log->Printf ("%p Communication::ReadThread () thread exiting...", p); - - comm->m_read_thread_did_exit = true; - // Let clients know that this thread is exiting - comm->BroadcastEvent (eBroadcastBitNoMorePendingInput); - comm->BroadcastEvent (eBroadcastBitReadThreadDidExit); - return NULL; + + switch (status) { + case eConnectionStatusSuccess: + break; + + case eConnectionStatusEndOfFile: + done = true; + break; + case eConnectionStatusError: // Check GetError() for details + if (error.GetType() == eErrorTypePOSIX && error.GetError() == EIO) { + // EIO on a pipe is usually caused by remote shutdown + comm->Disconnect(); + done = true; + } + if (log) + error.LogIfError( + log, "%p Communication::ReadFromConnection () => status = %s", p, + Communication::ConnectionStatusAsCString(status)); + break; + case eConnectionStatusInterrupted: // Synchronization signal from + // SynchronizeWithReadThread() + // The connection returns eConnectionStatusInterrupted only when there is + // no + // input pending to be read, so we can signal that. + comm->BroadcastEvent(eBroadcastBitNoMorePendingInput); + break; + case eConnectionStatusNoConnection: // No connection + case eConnectionStatusLostConnection: // Lost connection while connected to + // a valid connection + done = true; + LLVM_FALLTHROUGH; + case eConnectionStatusTimedOut: // Request timed out + if (log) + error.LogIfError( + log, "%p Communication::ReadFromConnection () => status = %s", p, + Communication::ConnectionStatusAsCString(status)); + break; + } + } + log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION); + if (log) + log->Printf("%p Communication::ReadThread () thread exiting...", p); + + comm->m_read_thread_did_exit = true; + // Let clients know that this thread is exiting + comm->BroadcastEvent(eBroadcastBitNoMorePendingInput); + comm->BroadcastEvent(eBroadcastBitReadThreadDidExit); + return NULL; } -void -Communication::SetReadThreadBytesReceivedCallback(ReadThreadBytesReceived callback, - void *callback_baton) -{ - m_callback = callback; - m_callback_baton = callback_baton; +void Communication::SetReadThreadBytesReceivedCallback( + ReadThreadBytesReceived callback, void *callback_baton) { + m_callback = callback; + m_callback_baton = callback_baton; } -void -Communication::SynchronizeWithReadThread () -{ - // Only one thread can do the synchronization dance at a time. - std::lock_guard guard(m_synchronize_mutex); +void Communication::SynchronizeWithReadThread() { + // Only one thread can do the synchronization dance at a time. + std::lock_guard guard(m_synchronize_mutex); - // First start listening for the synchronization event. - ListenerSP listener_sp(Listener::MakeListener("Communication::SyncronizeWithReadThread")); - listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput); + // First start listening for the synchronization event. + ListenerSP listener_sp( + Listener::MakeListener("Communication::SyncronizeWithReadThread")); + listener_sp->StartListeningForEvents(this, eBroadcastBitNoMorePendingInput); - // If the thread is not running, there is no point in synchronizing. - if (!m_read_thread_enabled || m_read_thread_did_exit) - return; + // If the thread is not running, there is no point in synchronizing. + if (!m_read_thread_enabled || m_read_thread_did_exit) + return; - // Notify the read thread. - m_connection_sp->InterruptRead(); + // Notify the read thread. + m_connection_sp->InterruptRead(); - // Wait for the synchronization event. - EventSP event_sp; - listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp); + // Wait for the synchronization event. + EventSP event_sp; + listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp); } -void -Communication::SetConnection (Connection *connection) -{ - Disconnect(nullptr); - StopReadThread(nullptr); - m_connection_sp.reset(connection); +void Communication::SetConnection(Connection *connection) { + Disconnect(nullptr); + StopReadThread(nullptr); + m_connection_sp.reset(connection); } const char * -Communication::ConnectionStatusAsCString (lldb::ConnectionStatus status) -{ - switch (status) - { - case eConnectionStatusSuccess: return "success"; - case eConnectionStatusError: return "error"; - case eConnectionStatusTimedOut: return "timed out"; - case eConnectionStatusNoConnection: return "no connection"; - case eConnectionStatusLostConnection: return "lost connection"; - case eConnectionStatusEndOfFile: return "end of file"; - case eConnectionStatusInterrupted: return "interrupted"; - } - - static char unknown_state_string[64]; - snprintf(unknown_state_string, sizeof (unknown_state_string), "ConnectionStatus = %i", status); - return unknown_state_string; +Communication::ConnectionStatusAsCString(lldb::ConnectionStatus status) { + switch (status) { + case eConnectionStatusSuccess: + return "success"; + case eConnectionStatusError: + return "error"; + case eConnectionStatusTimedOut: + return "timed out"; + case eConnectionStatusNoConnection: + return "no connection"; + case eConnectionStatusLostConnection: + return "lost connection"; + case eConnectionStatusEndOfFile: + return "end of file"; + case eConnectionStatusInterrupted: + return "interrupted"; + } + + static char unknown_state_string[64]; + snprintf(unknown_state_string, sizeof(unknown_state_string), + "ConnectionStatus = %i", status); + return unknown_state_string; } diff --git a/lldb/source/Core/Connection.cpp b/lldb/source/Core/Connection.cpp index 3f740a1ed82..1ae046b8a01 100644 --- a/lldb/source/Core/Connection.cpp +++ b/lldb/source/Core/Connection.cpp @@ -21,20 +21,14 @@ using namespace lldb_private; -Connection::Connection () -{ -} +Connection::Connection() {} -Connection::~Connection () -{ -} +Connection::~Connection() {} -Connection * -Connection::CreateDefaultConnection(const char *url) -{ +Connection *Connection::CreateDefaultConnection(const char *url) { #if defined(_WIN32) - if (strstr(url, "file://") == url) - return new ConnectionGenericFile(); + if (strstr(url, "file://") == url) + return new ConnectionGenericFile(); #endif - return new ConnectionFileDescriptor(); + return new ConnectionFileDescriptor(); } diff --git a/lldb/source/Core/ConnectionMachPort.cpp b/lldb/source/Core/ConnectionMachPort.cpp index e04c4890557..1fc87dc01f6 100644 --- a/lldb/source/Core/ConnectionMachPort.cpp +++ b/lldb/source/Core/ConnectionMachPort.cpp @@ -23,309 +23,237 @@ using namespace lldb; using namespace lldb_private; -struct MessageType -{ - mach_msg_header_t head; - ConnectionMachPort::PayloadType payload; +struct MessageType { + mach_msg_header_t head; + ConnectionMachPort::PayloadType payload; }; +ConnectionMachPort::ConnectionMachPort() + : Connection(), m_task(mach_task_self()), m_port(MACH_PORT_TYPE_NONE) {} +ConnectionMachPort::~ConnectionMachPort() { Disconnect(NULL); } -ConnectionMachPort::ConnectionMachPort () : - Connection(), - m_task(mach_task_self()), - m_port(MACH_PORT_TYPE_NONE) -{ +bool ConnectionMachPort::IsConnected() const { + return m_port != MACH_PORT_TYPE_NONE; } -ConnectionMachPort::~ConnectionMachPort () -{ - Disconnect (NULL); -} +ConnectionStatus ConnectionMachPort::Connect(const char *s, Error *error_ptr) { + if (IsConnected()) { + if (error_ptr) + error_ptr->SetErrorString("already connected"); + return eConnectionStatusError; + } -bool -ConnectionMachPort::IsConnected () const -{ - return m_port != MACH_PORT_TYPE_NONE; -} + if (s == NULL || s[0] == '\0') { + if (error_ptr) + error_ptr->SetErrorString("empty connect URL"); + return eConnectionStatusError; + } -ConnectionStatus -ConnectionMachPort::Connect (const char *s, Error *error_ptr) -{ - if (IsConnected()) - { - if (error_ptr) - error_ptr->SetErrorString ("already connected"); - return eConnectionStatusError; - } - - if (s == NULL || s[0] == '\0') - { - if (error_ptr) - error_ptr->SetErrorString ("empty connect URL"); - return eConnectionStatusError; - } - - ConnectionStatus status = eConnectionStatusError; - - if (0 == strncmp (s, "bootstrap-checkin://", strlen("bootstrap-checkin://"))) - { - s += strlen("bootstrap-checkin://"); - - if (*s) - { - status = BootstrapCheckIn (s, error_ptr); - } - else - { - if (error_ptr) - error_ptr->SetErrorString ("bootstrap port name is empty"); - } - } - else if (0 == strncmp (s, "bootstrap-lookup://", strlen("bootstrap-lookup://"))) - { - s += strlen("bootstrap-lookup://"); - if (*s) - { - status = BootstrapLookup (s, error_ptr); - } - else - { - if (error_ptr) - error_ptr->SetErrorString ("bootstrap port name is empty"); - } - } - else - { - if (error_ptr) - error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s); - } + ConnectionStatus status = eConnectionStatusError; + if (0 == strncmp(s, "bootstrap-checkin://", strlen("bootstrap-checkin://"))) { + s += strlen("bootstrap-checkin://"); - if (status == eConnectionStatusSuccess) - { - if (error_ptr) - error_ptr->Clear(); - m_uri.assign(s); + if (*s) { + status = BootstrapCheckIn(s, error_ptr); + } else { + if (error_ptr) + error_ptr->SetErrorString("bootstrap port name is empty"); } - else - { - Disconnect(NULL); + } else if (0 == + strncmp(s, "bootstrap-lookup://", strlen("bootstrap-lookup://"))) { + s += strlen("bootstrap-lookup://"); + if (*s) { + status = BootstrapLookup(s, error_ptr); + } else { + if (error_ptr) + error_ptr->SetErrorString("bootstrap port name is empty"); } - - return status; -} + } else { + if (error_ptr) + error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'", + s); + } -ConnectionStatus -ConnectionMachPort::BootstrapCheckIn (const char *port, Error *error_ptr) -{ - mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; - - /* Getting bootstrap server port */ - kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); - if (kret == KERN_SUCCESS) - { - name_t port_name; - int len = snprintf(port_name, sizeof(port_name), "%s", port); - if (static_cast(len) < sizeof(port_name)) - { - kret = ::bootstrap_check_in (bootstrap_port, - port_name, - &m_port); - } - else - { - Disconnect(NULL); - if (error_ptr) - error_ptr->SetErrorString ("bootstrap is too long"); - return eConnectionStatusError; - } - } - - if (kret != KERN_SUCCESS) - { - Disconnect(NULL); - if (error_ptr) - error_ptr->SetError (kret, eErrorTypeMachKernel); - return eConnectionStatusError; - } - return eConnectionStatusSuccess; + if (status == eConnectionStatusSuccess) { + if (error_ptr) + error_ptr->Clear(); + m_uri.assign(s); + } else { + Disconnect(NULL); + } + + return status; } -lldb::ConnectionStatus -ConnectionMachPort::BootstrapLookup (const char *port, - Error *error_ptr) -{ - name_t port_name; +ConnectionStatus ConnectionMachPort::BootstrapCheckIn(const char *port, + Error *error_ptr) { + mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; - if (port && port[0]) - { - if (static_cast(::snprintf (port_name, sizeof (port_name), "%s", port)) >= sizeof (port_name)) - { - if (error_ptr) - error_ptr->SetErrorString ("port netname is too long"); - return eConnectionStatusError; - } - } - else - { - if (error_ptr) - error_ptr->SetErrorString ("empty port netname"); - return eConnectionStatusError; + /* Getting bootstrap server port */ + kern_return_t kret = + task_get_bootstrap_port(mach_task_self(), &bootstrap_port); + if (kret == KERN_SUCCESS) { + name_t port_name; + int len = snprintf(port_name, sizeof(port_name), "%s", port); + if (static_cast(len) < sizeof(port_name)) { + kret = ::bootstrap_check_in(bootstrap_port, port_name, &m_port); + } else { + Disconnect(NULL); + if (error_ptr) + error_ptr->SetErrorString("bootstrap is too long"); + return eConnectionStatusError; } + } - mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; - - /* Getting bootstrap server port */ - kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); - if (kret == KERN_SUCCESS) - { - kret = ::bootstrap_look_up (bootstrap_port, - port_name, - &m_port); - } + if (kret != KERN_SUCCESS) { + Disconnect(NULL); + if (error_ptr) + error_ptr->SetError(kret, eErrorTypeMachKernel); + return eConnectionStatusError; + } + return eConnectionStatusSuccess; +} - if (kret != KERN_SUCCESS) - { - if (error_ptr) - error_ptr->SetError (kret, eErrorTypeMachKernel); - return eConnectionStatusError; +lldb::ConnectionStatus ConnectionMachPort::BootstrapLookup(const char *port, + Error *error_ptr) { + name_t port_name; + + if (port && port[0]) { + if (static_cast(::snprintf(port_name, sizeof(port_name), "%s", + port)) >= sizeof(port_name)) { + if (error_ptr) + error_ptr->SetErrorString("port netname is too long"); + return eConnectionStatusError; } + } else { + if (error_ptr) + error_ptr->SetErrorString("empty port netname"); + return eConnectionStatusError; + } - return eConnectionStatusSuccess; -} + mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; -ConnectionStatus -ConnectionMachPort::Disconnect (Error *error_ptr) -{ - kern_return_t kret; - - // TODO: verify if we need to netname_check_out for - // either or both - if (m_port != MACH_PORT_TYPE_NONE) - { - kret = ::mach_port_deallocate (m_task, m_port); - if (error_ptr) - error_ptr->SetError (kret, eErrorTypeMachKernel); - m_port = MACH_PORT_TYPE_NONE; - } - m_uri.clear(); + /* Getting bootstrap server port */ + kern_return_t kret = + task_get_bootstrap_port(mach_task_self(), &bootstrap_port); + if (kret == KERN_SUCCESS) { + kret = ::bootstrap_look_up(bootstrap_port, port_name, &m_port); + } + + if (kret != KERN_SUCCESS) { + if (error_ptr) + error_ptr->SetError(kret, eErrorTypeMachKernel); + return eConnectionStatusError; + } - return eConnectionStatusSuccess; + return eConnectionStatusSuccess; } -size_t -ConnectionMachPort::Read (void *dst, - size_t dst_len, - uint32_t timeout_usec, - ConnectionStatus &status, - Error *error_ptr) -{ - PayloadType payload; - - kern_return_t kret = Receive (payload); - if (kret == KERN_SUCCESS) - { - memcpy (dst, payload.data, payload.data_length); - status = eConnectionStatusSuccess; - return payload.data_length; - } - +ConnectionStatus ConnectionMachPort::Disconnect(Error *error_ptr) { + kern_return_t kret; + + // TODO: verify if we need to netname_check_out for + // either or both + if (m_port != MACH_PORT_TYPE_NONE) { + kret = ::mach_port_deallocate(m_task, m_port); if (error_ptr) - error_ptr->SetError (kret, eErrorTypeMachKernel); - status = eConnectionStatusError; - return 0; -} + error_ptr->SetError(kret, eErrorTypeMachKernel); + m_port = MACH_PORT_TYPE_NONE; + } + m_uri.clear(); -size_t -ConnectionMachPort::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) -{ - PayloadType payload; - payload.command = 0; - payload.data_length = src_len; - const size_t max_payload_size = sizeof(payload.data); - if (src_len > max_payload_size) - payload.data_length = max_payload_size; - memcpy (payload.data, src, payload.data_length); - - if (Send (payload) == KERN_SUCCESS) - { - status = eConnectionStatusSuccess; - return payload.data_length; - } - status = eConnectionStatusError; - return 0; + return eConnectionStatusSuccess; } -std::string -ConnectionMachPort::GetURI() -{ - return m_uri; +size_t ConnectionMachPort::Read(void *dst, size_t dst_len, + uint32_t timeout_usec, ConnectionStatus &status, + Error *error_ptr) { + PayloadType payload; + + kern_return_t kret = Receive(payload); + if (kret == KERN_SUCCESS) { + memcpy(dst, payload.data, payload.data_length); + status = eConnectionStatusSuccess; + return payload.data_length; + } + + if (error_ptr) + error_ptr->SetError(kret, eErrorTypeMachKernel); + status = eConnectionStatusError; + return 0; } -ConnectionStatus -ConnectionMachPort::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) -{ - return eConnectionStatusLostConnection; +size_t ConnectionMachPort::Write(const void *src, size_t src_len, + ConnectionStatus &status, Error *error_ptr) { + PayloadType payload; + payload.command = 0; + payload.data_length = src_len; + const size_t max_payload_size = sizeof(payload.data); + if (src_len > max_payload_size) + payload.data_length = max_payload_size; + memcpy(payload.data, src, payload.data_length); + + if (Send(payload) == KERN_SUCCESS) { + status = eConnectionStatusSuccess; + return payload.data_length; + } + status = eConnectionStatusError; + return 0; } -kern_return_t -ConnectionMachPort::Send (const PayloadType &payload) -{ - struct MessageType message; - - /* (i) Form the message : */ - - /* (i.a) Fill the header fields : */ - message.head.msgh_bits = MACH_MSGH_BITS_REMOTE (MACH_MSG_TYPE_MAKE_SEND) | - MACH_MSGH_BITS_OTHER (MACH_MSGH_BITS_COMPLEX); - message.head.msgh_size = sizeof(MessageType); - message.head.msgh_local_port = MACH_PORT_NULL; - message.head.msgh_remote_port = m_port; - - /* (i.b) Explain the message type ( an integer ) */ - // message.type.msgt_name = MACH_MSG_TYPE_INTEGER_32; - // message.type.msgt_size = 32; - // message.type.msgt_number = 1; - // message.type.msgt_inline = TRUE; - // message.type.msgt_longform = FALSE; - // message.type.msgt_deallocate = FALSE; - /* message.type.msgt_unused = 0; */ /* not needed, I think */ - - /* (i.c) Fill the message with the given integer : */ - message.payload = payload; - - /* (ii) Send the message : */ - kern_return_t kret = ::mach_msg (&message.head, - MACH_SEND_MSG, - message.head.msgh_size, - 0, - MACH_PORT_NULL, - MACH_MSG_TIMEOUT_NONE, - MACH_PORT_NULL); - - return kret; +std::string ConnectionMachPort::GetURI() { return m_uri; } + +ConnectionStatus ConnectionMachPort::BytesAvailable(uint32_t timeout_usec, + Error *error_ptr) { + return eConnectionStatusLostConnection; } -kern_return_t -ConnectionMachPort::Receive (PayloadType &payload) -{ - MessageType message; - message.head.msgh_size = sizeof(MessageType); - - kern_return_t kret = ::mach_msg (&message.head, - MACH_RCV_MSG, - 0, - sizeof(MessageType), - m_port, - MACH_MSG_TIMEOUT_NONE, - MACH_PORT_NULL); - - if (kret == KERN_SUCCESS) - payload = message.payload; - - return kret; +kern_return_t ConnectionMachPort::Send(const PayloadType &payload) { + struct MessageType message; + + /* (i) Form the message : */ + + /* (i.a) Fill the header fields : */ + message.head.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND) | + MACH_MSGH_BITS_OTHER(MACH_MSGH_BITS_COMPLEX); + message.head.msgh_size = sizeof(MessageType); + message.head.msgh_local_port = MACH_PORT_NULL; + message.head.msgh_remote_port = m_port; + + /* (i.b) Explain the message type ( an integer ) */ + // message.type.msgt_name = MACH_MSG_TYPE_INTEGER_32; + // message.type.msgt_size = 32; + // message.type.msgt_number = 1; + // message.type.msgt_inline = TRUE; + // message.type.msgt_longform = FALSE; + // message.type.msgt_deallocate = FALSE; + /* message.type.msgt_unused = 0; */ /* not needed, I think */ + + /* (i.c) Fill the message with the given integer : */ + message.payload = payload; + + /* (ii) Send the message : */ + kern_return_t kret = + ::mach_msg(&message.head, MACH_SEND_MSG, message.head.msgh_size, 0, + MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); + + return kret; } +kern_return_t ConnectionMachPort::Receive(PayloadType &payload) { + MessageType message; + message.head.msgh_size = sizeof(MessageType); + + kern_return_t kret = + ::mach_msg(&message.head, MACH_RCV_MSG, 0, sizeof(MessageType), m_port, + MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); + + if (kret == KERN_SUCCESS) + payload = message.payload; + + return kret; +} #endif // #if defined(__APPLE__) diff --git a/lldb/source/Core/ConnectionSharedMemory.cpp b/lldb/source/Core/ConnectionSharedMemory.cpp index 46948b842e0..74487b017e4 100644 --- a/lldb/source/Core/ConnectionSharedMemory.cpp +++ b/lldb/source/Core/ConnectionSharedMemory.cpp @@ -15,10 +15,10 @@ #ifdef _WIN32 #include "lldb/Host/windows/windows.h" #else +#include #include #include #include -#include #endif // C++ Includes @@ -26,8 +26,8 @@ #include // Other libraries and framework includes -#include "llvm/Support/MathExtras.h" #include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/MathExtras.h" // Project includes #include "lldb/Core/Communication.h" @@ -37,135 +37,110 @@ using namespace lldb; using namespace lldb_private; -ConnectionSharedMemory::ConnectionSharedMemory () : - Connection(), - m_name(), - m_fd (-1), - m_mmap() -{ -} - -ConnectionSharedMemory::~ConnectionSharedMemory () -{ - Disconnect(nullptr); -} - -bool -ConnectionSharedMemory::IsConnected () const -{ - return m_fd >= 0; -} - -ConnectionStatus -ConnectionSharedMemory::Connect (const char *s, Error *error_ptr) -{ -// if (s && s[0]) -// { -// if (strstr(s, "shm-create://")) -// { -// } -// else if (strstr(s, "shm-connect://")) -// { -// } -// if (error_ptr) -// error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s); -// return eConnectionStatusError; -// } - if (error_ptr) - error_ptr->SetErrorString("invalid connect arguments"); - return eConnectionStatusError; +ConnectionSharedMemory::ConnectionSharedMemory() + : Connection(), m_name(), m_fd(-1), m_mmap() {} + +ConnectionSharedMemory::~ConnectionSharedMemory() { Disconnect(nullptr); } + +bool ConnectionSharedMemory::IsConnected() const { return m_fd >= 0; } + +ConnectionStatus ConnectionSharedMemory::Connect(const char *s, + Error *error_ptr) { + // if (s && s[0]) + // { + // if (strstr(s, "shm-create://")) + // { + // } + // else if (strstr(s, "shm-connect://")) + // { + // } + // if (error_ptr) + // error_ptr->SetErrorStringWithFormat ("unsupported connection + // URL: '%s'", s); + // return eConnectionStatusError; + // } + if (error_ptr) + error_ptr->SetErrorString("invalid connect arguments"); + return eConnectionStatusError; } -ConnectionStatus -ConnectionSharedMemory::Disconnect (Error *error_ptr) -{ - m_mmap.Clear(); - if (!m_name.empty()) - { +ConnectionStatus ConnectionSharedMemory::Disconnect(Error *error_ptr) { + m_mmap.Clear(); + if (!m_name.empty()) { #ifdef _WIN32 - close(m_fd); - m_fd = -1; + close(m_fd); + m_fd = -1; #else - shm_unlink (m_name.c_str()); + shm_unlink(m_name.c_str()); #endif - m_name.clear(); - } - return eConnectionStatusSuccess; + m_name.clear(); + } + return eConnectionStatusSuccess; } -size_t -ConnectionSharedMemory::Read (void *dst, - size_t dst_len, - uint32_t timeout_usec, - ConnectionStatus &status, - Error *error_ptr) -{ - status = eConnectionStatusSuccess; - return 0; +size_t ConnectionSharedMemory::Read(void *dst, size_t dst_len, + uint32_t timeout_usec, + ConnectionStatus &status, + Error *error_ptr) { + status = eConnectionStatusSuccess; + return 0; } -size_t -ConnectionSharedMemory::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) -{ - status = eConnectionStatusSuccess; - return 0; +size_t ConnectionSharedMemory::Write(const void *src, size_t src_len, + ConnectionStatus &status, + Error *error_ptr) { + status = eConnectionStatusSuccess; + return 0; } -std::string -ConnectionSharedMemory::GetURI() -{ - // TODO: fix when Connect is fixed? - return ""; +std::string ConnectionSharedMemory::GetURI() { + // TODO: fix when Connect is fixed? + return ""; } -ConnectionStatus -ConnectionSharedMemory::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) -{ - return eConnectionStatusLostConnection; +ConnectionStatus ConnectionSharedMemory::BytesAvailable(uint32_t timeout_usec, + Error *error_ptr) { + return eConnectionStatusLostConnection; } -ConnectionStatus -ConnectionSharedMemory::Open (bool create, const char *name, size_t size, Error *error_ptr) -{ - if (m_fd != -1) - { - if (error_ptr) - error_ptr->SetErrorString("already open"); - return eConnectionStatusError; - } - - m_name.assign (name); +ConnectionStatus ConnectionSharedMemory::Open(bool create, const char *name, + size_t size, Error *error_ptr) { + if (m_fd != -1) { + if (error_ptr) + error_ptr->SetErrorString("already open"); + return eConnectionStatusError; + } + + m_name.assign(name); #ifdef _WIN32 - HANDLE handle = INVALID_HANDLE_VALUE; - std::wstring wname; - if (llvm::ConvertUTF8toWide(name, wname)) - { - if (create) - { - handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, llvm::Hi_32(size), - llvm::Lo_32(size), wname.c_str()); - } - else - handle = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, wname.c_str()); - } - - m_fd = _open_osfhandle((intptr_t)handle, 0); + HANDLE handle = INVALID_HANDLE_VALUE; + std::wstring wname; + if (llvm::ConvertUTF8toWide(name, wname)) { + if (create) { + handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, + llvm::Hi_32(size), llvm::Lo_32(size), + wname.c_str()); + } else + handle = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, wname.c_str()); + } + + m_fd = _open_osfhandle((intptr_t)handle, 0); #else - int oflag = O_RDWR; - if (create) - oflag |= O_CREAT; - m_fd = ::shm_open (m_name.c_str(), oflag, S_IRUSR|S_IWUSR); + int oflag = O_RDWR; + if (create) + oflag |= O_CREAT; + m_fd = ::shm_open(m_name.c_str(), oflag, S_IRUSR | S_IWUSR); - if (create) - ::ftruncate (m_fd, size); + if (create) + ::ftruncate(m_fd, size); #endif - if (m_mmap.MemoryMapFromFileDescriptor(m_fd, 0, size, true, false) == size) - return eConnectionStatusSuccess; + if (m_mmap.MemoryMapFromFileDescriptor(m_fd, 0, size, true, false) == size) + return eConnectionStatusSuccess; - Disconnect(nullptr); - return eConnectionStatusError; + Disconnect(nullptr); + return eConnectionStatusError; } #endif // __ANDROID_NDK__ diff --git a/lldb/source/Core/ConstString.cpp b/lldb/source/Core/ConstString.cpp index f983f1444d7..21b4d3d76f1 100644 --- a/lldb/source/Core/ConstString.cpp +++ b/lldb/source/Core/ConstString.cpp @@ -15,8 +15,8 @@ #include // Other libraries and framework includes -#include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringMap.h" #include "llvm/Support/RWMutex.h" // Project includes @@ -24,180 +24,159 @@ using namespace lldb_private; -class Pool -{ +class Pool { public: - typedef const char * StringPoolValueType; - typedef llvm::StringMap StringPool; - typedef llvm::StringMapEntry StringPoolEntryType; - - static StringPoolEntryType & - GetStringMapEntryFromKeyData (const char *keyData) - { - char *ptr = const_cast(keyData) - sizeof (StringPoolEntryType); - return *reinterpret_cast(ptr); - } - - size_t - GetConstCStringLength (const char *ccstr) const - { - if (ccstr != nullptr) - { - const uint8_t h = hash (llvm::StringRef(ccstr)); - llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); - const StringPoolEntryType& entry = GetStringMapEntryFromKeyData (ccstr); - return entry.getKey().size(); - } - return 0; + typedef const char *StringPoolValueType; + typedef llvm::StringMap + StringPool; + typedef llvm::StringMapEntry StringPoolEntryType; + + static StringPoolEntryType & + GetStringMapEntryFromKeyData(const char *keyData) { + char *ptr = const_cast(keyData) - sizeof(StringPoolEntryType); + return *reinterpret_cast(ptr); + } + + size_t GetConstCStringLength(const char *ccstr) const { + if (ccstr != nullptr) { + const uint8_t h = hash(llvm::StringRef(ccstr)); + llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); + const StringPoolEntryType &entry = GetStringMapEntryFromKeyData(ccstr); + return entry.getKey().size(); } - - StringPoolValueType - GetMangledCounterpart (const char *ccstr) const - { - if (ccstr != nullptr) - { - const uint8_t h = hash (llvm::StringRef(ccstr)); - llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); - return GetStringMapEntryFromKeyData (ccstr).getValue(); - } - return nullptr; + return 0; + } + + StringPoolValueType GetMangledCounterpart(const char *ccstr) const { + if (ccstr != nullptr) { + const uint8_t h = hash(llvm::StringRef(ccstr)); + llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); + return GetStringMapEntryFromKeyData(ccstr).getValue(); } - - bool - SetMangledCounterparts (const char *key_ccstr, const char *value_ccstr) - { - if (key_ccstr != nullptr && value_ccstr != nullptr) - { - { - const uint8_t h = hash (llvm::StringRef(key_ccstr)); - llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); - GetStringMapEntryFromKeyData (key_ccstr).setValue(value_ccstr); - } - { - const uint8_t h = hash (llvm::StringRef(value_ccstr)); - llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); - GetStringMapEntryFromKeyData (value_ccstr).setValue(key_ccstr); - } - return true; - } - return false; + return nullptr; + } + + bool SetMangledCounterparts(const char *key_ccstr, const char *value_ccstr) { + if (key_ccstr != nullptr && value_ccstr != nullptr) { + { + const uint8_t h = hash(llvm::StringRef(key_ccstr)); + llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); + GetStringMapEntryFromKeyData(key_ccstr).setValue(value_ccstr); + } + { + const uint8_t h = hash(llvm::StringRef(value_ccstr)); + llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); + GetStringMapEntryFromKeyData(value_ccstr).setValue(key_ccstr); + } + return true; } + return false; + } - const char * - GetConstCString (const char *cstr) - { - if (cstr != nullptr) - return GetConstCStringWithLength (cstr, strlen (cstr)); - return nullptr; - } + const char *GetConstCString(const char *cstr) { + if (cstr != nullptr) + return GetConstCStringWithLength(cstr, strlen(cstr)); + return nullptr; + } - const char * - GetConstCStringWithLength (const char *cstr, size_t cstr_len) - { - if (cstr != nullptr) - return GetConstCStringWithStringRef(llvm::StringRef(cstr, cstr_len)); - return nullptr; + const char *GetConstCStringWithLength(const char *cstr, size_t cstr_len) { + if (cstr != nullptr) + return GetConstCStringWithStringRef(llvm::StringRef(cstr, cstr_len)); + return nullptr; + } + + const char *GetConstCStringWithStringRef(const llvm::StringRef &string_ref) { + if (string_ref.data()) { + const uint8_t h = hash(string_ref); + + { + llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); + auto it = m_string_pools[h].m_string_map.find(string_ref); + if (it != m_string_pools[h].m_string_map.end()) + return it->getKeyData(); + } + + llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); + StringPoolEntryType &entry = + *m_string_pools[h] + .m_string_map.insert(std::make_pair(string_ref, nullptr)) + .first; + return entry.getKeyData(); } - - const char * - GetConstCStringWithStringRef (const llvm::StringRef &string_ref) - { - if (string_ref.data()) - { - const uint8_t h = hash (string_ref); - - { - llvm::sys::SmartScopedReader rlock(m_string_pools[h].m_mutex); - auto it = m_string_pools[h].m_string_map.find (string_ref); - if (it != m_string_pools[h].m_string_map.end()) - return it->getKeyData(); - } - - llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); - StringPoolEntryType& entry = *m_string_pools[h].m_string_map.insert (std::make_pair (string_ref, nullptr)).first; - return entry.getKeyData(); - } - return nullptr; + return nullptr; + } + + const char * + GetConstCStringAndSetMangledCounterPart(const char *demangled_cstr, + const char *mangled_ccstr) { + if (demangled_cstr != nullptr) { + const char *demangled_ccstr = nullptr; + + { + llvm::StringRef string_ref(demangled_cstr); + const uint8_t h = hash(string_ref); + llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); + + // Make string pool entry with the mangled counterpart already set + StringPoolEntryType &entry = + *m_string_pools[h] + .m_string_map.insert(std::make_pair(string_ref, mangled_ccstr)) + .first; + + // Extract the const version of the demangled_cstr + demangled_ccstr = entry.getKeyData(); + } + + { + // Now assign the demangled const string as the counterpart of the + // mangled const string... + const uint8_t h = hash(llvm::StringRef(mangled_ccstr)); + llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); + GetStringMapEntryFromKeyData(mangled_ccstr).setValue(demangled_ccstr); + } + + // Return the constant demangled C string + return demangled_ccstr; } - - const char * - GetConstCStringAndSetMangledCounterPart (const char *demangled_cstr, const char *mangled_ccstr) - { - if (demangled_cstr != nullptr) - { - const char *demangled_ccstr = nullptr; - - { - llvm::StringRef string_ref (demangled_cstr); - const uint8_t h = hash (string_ref); - llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); - - // Make string pool entry with the mangled counterpart already set - StringPoolEntryType& entry = *m_string_pools[h].m_string_map.insert ( - std::make_pair (string_ref, mangled_ccstr)).first; - - // Extract the const version of the demangled_cstr - demangled_ccstr = entry.getKeyData(); - } - - { - // Now assign the demangled const string as the counterpart of the - // mangled const string... - const uint8_t h = hash (llvm::StringRef(mangled_ccstr)); - llvm::sys::SmartScopedWriter wlock(m_string_pools[h].m_mutex); - GetStringMapEntryFromKeyData (mangled_ccstr).setValue(demangled_ccstr); - } - - // Return the constant demangled C string - return demangled_ccstr; - } - return nullptr; + return nullptr; + } + + const char *GetConstTrimmedCStringWithLength(const char *cstr, + size_t cstr_len) { + if (cstr != nullptr) { + const size_t trimmed_len = std::min(strlen(cstr), cstr_len); + return GetConstCStringWithLength(cstr, trimmed_len); } - - const char * - GetConstTrimmedCStringWithLength (const char *cstr, size_t cstr_len) - { - if (cstr != nullptr) - { - const size_t trimmed_len = std::min (strlen (cstr), cstr_len); - return GetConstCStringWithLength (cstr, trimmed_len); - } - return nullptr; - } - - //------------------------------------------------------------------ - // Return the size in bytes that this object and any items in its - // collection of uniqued strings + data count values takes in - // memory. - //------------------------------------------------------------------ - size_t - MemorySize() const - { - size_t mem_size = sizeof(Pool); - for (const auto& pool : m_string_pools) - { - llvm::sys::SmartScopedReader rlock(pool.m_mutex); - for (const auto& entry : pool.m_string_map) - mem_size += sizeof(StringPoolEntryType) + entry.getKey().size(); - } - return mem_size; + return nullptr; + } + + //------------------------------------------------------------------ + // Return the size in bytes that this object and any items in its + // collection of uniqued strings + data count values takes in + // memory. + //------------------------------------------------------------------ + size_t MemorySize() const { + size_t mem_size = sizeof(Pool); + for (const auto &pool : m_string_pools) { + llvm::sys::SmartScopedReader rlock(pool.m_mutex); + for (const auto &entry : pool.m_string_map) + mem_size += sizeof(StringPoolEntryType) + entry.getKey().size(); } + return mem_size; + } protected: - uint8_t - hash(const llvm::StringRef &s) const - { - uint32_t h = llvm::HashString(s); - return ((h >> 24) ^ (h >> 16) ^ (h >> 8) ^ h) & 0xff; - } + uint8_t hash(const llvm::StringRef &s) const { + uint32_t h = llvm::HashString(s); + return ((h >> 24) ^ (h >> 16) ^ (h >> 8) ^ h) & 0xff; + } - struct PoolEntry - { - mutable llvm::sys::SmartRWMutex m_mutex; - StringPool m_string_map; - }; + struct PoolEntry { + mutable llvm::sys::SmartRWMutex m_mutex; + StringPool m_string_map; + }; - std::array m_string_pools; + std::array m_string_pools; }; //---------------------------------------------------------------------- @@ -211,177 +190,147 @@ protected: // global destructor chain is run, and trying to make sure no destructors // touch ConstStrings is difficult. So we leak the pool instead. //---------------------------------------------------------------------- -static Pool & -StringPool() -{ - static std::once_flag g_pool_initialization_flag; - static Pool *g_string_pool = nullptr; - - std::call_once(g_pool_initialization_flag, [] () { - g_string_pool = new Pool(); - }); - - return *g_string_pool; -} +static Pool &StringPool() { + static std::once_flag g_pool_initialization_flag; + static Pool *g_string_pool = nullptr; -ConstString::ConstString (const char *cstr) : - m_string (StringPool().GetConstCString (cstr)) -{ -} + std::call_once(g_pool_initialization_flag, + []() { g_string_pool = new Pool(); }); -ConstString::ConstString (const char *cstr, size_t cstr_len) : - m_string (StringPool().GetConstCStringWithLength (cstr, cstr_len)) -{ + return *g_string_pool; } -ConstString::ConstString (const llvm::StringRef &s) : - m_string (StringPool().GetConstCStringWithLength (s.data(), s.size())) -{ -} +ConstString::ConstString(const char *cstr) + : m_string(StringPool().GetConstCString(cstr)) {} -bool -ConstString::operator < (const ConstString& rhs) const -{ - if (m_string == rhs.m_string) - return false; +ConstString::ConstString(const char *cstr, size_t cstr_len) + : m_string(StringPool().GetConstCStringWithLength(cstr, cstr_len)) {} - llvm::StringRef lhs_string_ref (m_string, StringPool().GetConstCStringLength (m_string)); - llvm::StringRef rhs_string_ref (rhs.m_string, StringPool().GetConstCStringLength (rhs.m_string)); +ConstString::ConstString(const llvm::StringRef &s) + : m_string(StringPool().GetConstCStringWithLength(s.data(), s.size())) {} - // If both have valid C strings, then return the comparison - if (lhs_string_ref.data() && rhs_string_ref.data()) - return lhs_string_ref < rhs_string_ref; +bool ConstString::operator<(const ConstString &rhs) const { + if (m_string == rhs.m_string) + return false; - // Else one of them was nullptr, so if LHS is nullptr then it is less than - return lhs_string_ref.data() == nullptr; + llvm::StringRef lhs_string_ref(m_string, + StringPool().GetConstCStringLength(m_string)); + llvm::StringRef rhs_string_ref( + rhs.m_string, StringPool().GetConstCStringLength(rhs.m_string)); + + // If both have valid C strings, then return the comparison + if (lhs_string_ref.data() && rhs_string_ref.data()) + return lhs_string_ref < rhs_string_ref; + + // Else one of them was nullptr, so if LHS is nullptr then it is less than + return lhs_string_ref.data() == nullptr; } -Stream& -lldb_private::operator << (Stream& s, const ConstString& str) -{ - const char *cstr = str.GetCString(); - if (cstr != nullptr) - s << cstr; +Stream &lldb_private::operator<<(Stream &s, const ConstString &str) { + const char *cstr = str.GetCString(); + if (cstr != nullptr) + s << cstr; - return s; + return s; } -size_t -ConstString::GetLength () const -{ - return StringPool().GetConstCStringLength (m_string); +size_t ConstString::GetLength() const { + return StringPool().GetConstCStringLength(m_string); } -bool -ConstString::Equals(const ConstString &lhs, const ConstString &rhs, const bool case_sensitive) -{ - if (lhs.m_string == rhs.m_string) - return true; - - // Since the pointers weren't equal, and identical ConstStrings always have identical pointers, - // the result must be false for case sensitive equality test. - if (case_sensitive) - return false; - - // perform case insensitive equality test - llvm::StringRef lhs_string_ref(lhs.m_string, StringPool().GetConstCStringLength(lhs.m_string)); - llvm::StringRef rhs_string_ref(rhs.m_string, StringPool().GetConstCStringLength(rhs.m_string)); - return lhs_string_ref.equals_lower(rhs_string_ref); +bool ConstString::Equals(const ConstString &lhs, const ConstString &rhs, + const bool case_sensitive) { + if (lhs.m_string == rhs.m_string) + return true; + + // Since the pointers weren't equal, and identical ConstStrings always have + // identical pointers, + // the result must be false for case sensitive equality test. + if (case_sensitive) + return false; + + // perform case insensitive equality test + llvm::StringRef lhs_string_ref( + lhs.m_string, StringPool().GetConstCStringLength(lhs.m_string)); + llvm::StringRef rhs_string_ref( + rhs.m_string, StringPool().GetConstCStringLength(rhs.m_string)); + return lhs_string_ref.equals_lower(rhs_string_ref); } -int -ConstString::Compare(const ConstString &lhs, const ConstString &rhs, const bool case_sensitive) -{ - // If the iterators are the same, this is the same string - const char *lhs_cstr = lhs.m_string; - const char *rhs_cstr = rhs.m_string; - if (lhs_cstr == rhs_cstr) - return 0; - if (lhs_cstr && rhs_cstr) - { - llvm::StringRef lhs_string_ref (lhs_cstr, StringPool().GetConstCStringLength (lhs_cstr)); - llvm::StringRef rhs_string_ref (rhs_cstr, StringPool().GetConstCStringLength (rhs_cstr)); - - if (case_sensitive) - { - return lhs_string_ref.compare(rhs_string_ref); - } - else - { - return lhs_string_ref.compare_lower(rhs_string_ref); - } +int ConstString::Compare(const ConstString &lhs, const ConstString &rhs, + const bool case_sensitive) { + // If the iterators are the same, this is the same string + const char *lhs_cstr = lhs.m_string; + const char *rhs_cstr = rhs.m_string; + if (lhs_cstr == rhs_cstr) + return 0; + if (lhs_cstr && rhs_cstr) { + llvm::StringRef lhs_string_ref( + lhs_cstr, StringPool().GetConstCStringLength(lhs_cstr)); + llvm::StringRef rhs_string_ref( + rhs_cstr, StringPool().GetConstCStringLength(rhs_cstr)); + + if (case_sensitive) { + return lhs_string_ref.compare(rhs_string_ref); + } else { + return lhs_string_ref.compare_lower(rhs_string_ref); } + } - if (lhs_cstr) - return +1; // LHS isn't nullptr but RHS is - else - return -1; // LHS is nullptr but RHS isn't + if (lhs_cstr) + return +1; // LHS isn't nullptr but RHS is + else + return -1; // LHS is nullptr but RHS isn't } -void -ConstString::Dump(Stream *s, const char *fail_value) const -{ - if (s != nullptr) - { - const char *cstr = AsCString (fail_value); - if (cstr != nullptr) - s->PutCString (cstr); - } +void ConstString::Dump(Stream *s, const char *fail_value) const { + if (s != nullptr) { + const char *cstr = AsCString(fail_value); + if (cstr != nullptr) + s->PutCString(cstr); + } } -void -ConstString::DumpDebug(Stream *s) const -{ - const char *cstr = GetCString (); - size_t cstr_len = GetLength(); - // Only print the parens if we have a non-nullptr string - const char *parens = cstr ? "\"" : ""; - s->Printf("%*p: ConstString, string = %s%s%s, length = %" PRIu64, - static_cast(sizeof(void*) * 2), - static_cast(this), parens, cstr, parens, - static_cast(cstr_len)); +void ConstString::DumpDebug(Stream *s) const { + const char *cstr = GetCString(); + size_t cstr_len = GetLength(); + // Only print the parens if we have a non-nullptr string + const char *parens = cstr ? "\"" : ""; + s->Printf("%*p: ConstString, string = %s%s%s, length = %" PRIu64, + static_cast(sizeof(void *) * 2), + static_cast(this), parens, cstr, parens, + static_cast(cstr_len)); } -void -ConstString::SetCString (const char *cstr) -{ - m_string = StringPool().GetConstCString (cstr); +void ConstString::SetCString(const char *cstr) { + m_string = StringPool().GetConstCString(cstr); } -void -ConstString::SetString (const llvm::StringRef &s) -{ - m_string = StringPool().GetConstCStringWithLength (s.data(), s.size()); +void ConstString::SetString(const llvm::StringRef &s) { + m_string = StringPool().GetConstCStringWithLength(s.data(), s.size()); } -void -ConstString::SetCStringWithMangledCounterpart (const char *demangled, const ConstString &mangled) -{ - m_string = StringPool().GetConstCStringAndSetMangledCounterPart (demangled, mangled.m_string); +void ConstString::SetCStringWithMangledCounterpart(const char *demangled, + const ConstString &mangled) { + m_string = StringPool().GetConstCStringAndSetMangledCounterPart( + demangled, mangled.m_string); } -bool -ConstString::GetMangledCounterpart (ConstString &counterpart) const -{ - counterpart.m_string = StringPool().GetMangledCounterpart(m_string); - return (bool)counterpart; +bool ConstString::GetMangledCounterpart(ConstString &counterpart) const { + counterpart.m_string = StringPool().GetMangledCounterpart(m_string); + return (bool)counterpart; } -void -ConstString::SetCStringWithLength (const char *cstr, size_t cstr_len) -{ - m_string = StringPool().GetConstCStringWithLength(cstr, cstr_len); +void ConstString::SetCStringWithLength(const char *cstr, size_t cstr_len) { + m_string = StringPool().GetConstCStringWithLength(cstr, cstr_len); } -void -ConstString::SetTrimmedCStringWithLength (const char *cstr, size_t cstr_len) -{ - m_string = StringPool().GetConstTrimmedCStringWithLength (cstr, cstr_len); +void ConstString::SetTrimmedCStringWithLength(const char *cstr, + size_t cstr_len) { + m_string = StringPool().GetConstTrimmedCStringWithLength(cstr, cstr_len); } -size_t -ConstString::StaticMemorySize() -{ - // Get the size of the static string pool - return StringPool().MemorySize(); +size_t ConstString::StaticMemorySize() { + // Get the size of the static string pool + return StringPool().MemorySize(); } diff --git a/lldb/source/Core/CxaDemangle.cpp b/lldb/source/Core/CxaDemangle.cpp index 4bb0af52e20..5c1c2683418 100644 --- a/lldb/source/Core/CxaDemangle.cpp +++ b/lldb/source/Core/CxaDemangle.cpp @@ -16,11 +16,11 @@ // - Include for fprintf, stderr like entities. //---------------------------------------------------------------------- -#include "llvm/Support/Compiler.h" // LLVM_{NOEXCEPT, CONSTEXPR, ALIGNAS} +#include "llvm/Support/Compiler.h" // LLVM_{NOEXCEPT, CONSTEXPR, ALIGNAS} #include "lldb/Host/PosixApi.h" #include "lldb/lldb-private.h" -#undef _LIBCPP_EXTERN_TEMPLATE // Avoid warning below +#undef _LIBCPP_EXTERN_TEMPLATE // Avoid warning below //===-------------------------- cxa_demangle.cpp --------------------------===// // @@ -34,237 +34,202 @@ #define _LIBCPP_EXTERN_TEMPLATE(...) #define _LIBCPP_NO_EXCEPTIONS -#include #include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include -namespace lldb_private -{ +namespace lldb_private { -namespace -{ +namespace { -enum -{ - unknown_error = -4, - invalid_args = -3, - invalid_mangled_name, - memory_alloc_failure, - success +enum { + unknown_error = -4, + invalid_args = -3, + invalid_mangled_name, + memory_alloc_failure, + success }; template - const char* parse_type(const char* first, const char* last, C& db); +const char *parse_type(const char *first, const char *last, C &db); template - const char* parse_encoding(const char* first, const char* last, C& db); +const char *parse_encoding(const char *first, const char *last, C &db); template - const char* parse_name(const char* first, const char* last, C& db, - bool* ends_with_template_args = 0); +const char *parse_name(const char *first, const char *last, C &db, + bool *ends_with_template_args = 0); template - const char* parse_expression(const char* first, const char* last, C& db); +const char *parse_expression(const char *first, const char *last, C &db); template - const char* parse_template_args(const char* first, const char* last, C& db); +const char *parse_template_args(const char *first, const char *last, C &db); template - const char* parse_operator_name(const char* first, const char* last, C& db); +const char *parse_operator_name(const char *first, const char *last, C &db); template - const char* parse_unqualified_name(const char* first, const char* last, C& db); -template - const char* parse_decltype(const char* first, const char* last, C& db); - +const char *parse_unqualified_name(const char *first, const char *last, C &db); template -void -print_stack(const C& db) -{ - fprintf(stderr, "---------\n"); - fprintf(stderr, "names:\n"); - for (auto& s : db.names) - fprintf(stderr, "{%s#%s}\n", s.first.c_str(), s.second.c_str()); - int i = -1; - fprintf(stderr, "subs:\n"); - for (auto& v : db.subs) - { - if (i >= 0) - fprintf(stderr, "S%i_ = {", i); - else - fprintf(stderr, "S_ = {"); - for (auto& s : v) - fprintf(stderr, "{%s#%s}", s.first.c_str(), s.second.c_str()); - fprintf(stderr, "}\n"); - ++i; - } - fprintf(stderr, "template_param:\n"); - for (auto& t : db.template_param) - { - fprintf(stderr, "--\n"); - i = -1; - for (auto& v : t) - { - if (i >= 0) - fprintf(stderr, "T%i_ = {", i); - else - fprintf(stderr, "T_ = {"); - for (auto& s : v) - fprintf(stderr, "{%s#%s}", s.first.c_str(), s.second.c_str()); - fprintf(stderr, "}\n"); - ++i; - } +const char *parse_decltype(const char *first, const char *last, C &db); + +template void print_stack(const C &db) { + fprintf(stderr, "---------\n"); + fprintf(stderr, "names:\n"); + for (auto &s : db.names) + fprintf(stderr, "{%s#%s}\n", s.first.c_str(), s.second.c_str()); + int i = -1; + fprintf(stderr, "subs:\n"); + for (auto &v : db.subs) { + if (i >= 0) + fprintf(stderr, "S%i_ = {", i); + else + fprintf(stderr, "S_ = {"); + for (auto &s : v) + fprintf(stderr, "{%s#%s}", s.first.c_str(), s.second.c_str()); + fprintf(stderr, "}\n"); + ++i; + } + fprintf(stderr, "template_param:\n"); + for (auto &t : db.template_param) { + fprintf(stderr, "--\n"); + i = -1; + for (auto &v : t) { + if (i >= 0) + fprintf(stderr, "T%i_ = {", i); + else + fprintf(stderr, "T_ = {"); + for (auto &s : v) + fprintf(stderr, "{%s#%s}", s.first.c_str(), s.second.c_str()); + fprintf(stderr, "}\n"); + ++i; } - fprintf(stderr, "---------\n\n"); + } + fprintf(stderr, "---------\n\n"); } template -void -print_state(const char* msg, const char* first, const char* last, const C& db) -{ - fprintf(stderr, "%s: ", msg); - for (; first != last; ++first) - fprintf(stderr, "%c", *first); - fprintf(stderr, "\n"); - print_stack(db); +void print_state(const char *msg, const char *first, const char *last, + const C &db) { + fprintf(stderr, "%s: ", msg); + for (; first != last; ++first) + fprintf(stderr, "%c", *first); + fprintf(stderr, "\n"); + print_stack(db); } // ::= [n] -const char* -parse_number(const char* first, const char* last) -{ - if (first != last) - { - const char* t = first; - if (*t == 'n') - ++t; - if (t != last) - { - if (*t == '0') - { - first = t+1; - } - else if ('1' <= *t && *t <= '9') - { - first = t+1; - while (first != last && std::isdigit(*first)) - ++first; - } - } +const char *parse_number(const char *first, const char *last) { + if (first != last) { + const char *t = first; + if (*t == 'n') + ++t; + if (t != last) { + if (*t == '0') { + first = t + 1; + } else if ('1' <= *t && *t <= '9') { + first = t + 1; + while (first != last && std::isdigit(*first)) + ++first; + } } - return first; + } + return first; } -template -struct float_data; +template struct float_data; -template <> -struct float_data -{ - static const size_t mangled_size = 8; - static const size_t max_demangled_size = 24; - static const char* spec; +template <> struct float_data { + static const size_t mangled_size = 8; + static const size_t max_demangled_size = 24; + static const char *spec; }; -const char* float_data::spec = "%af"; +const char *float_data::spec = "%af"; -template <> -struct float_data -{ - static const size_t mangled_size = 16; - static const size_t max_demangled_size = 32; - static const char* spec; +template <> struct float_data { + static const size_t mangled_size = 16; + static const size_t max_demangled_size = 32; + static const char *spec; }; -const char* float_data::spec = "%a"; +const char *float_data::spec = "%a"; -template <> -struct float_data -{ +template <> struct float_data { #if defined(__arm__) - static const size_t mangled_size = 16; + static const size_t mangled_size = 16; #else - static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms + static const size_t mangled_size = + 20; // May need to be adjusted to 16 or 24 on other platforms #endif - static const size_t max_demangled_size = 40; - static const char* spec; + static const size_t max_demangled_size = 40; + static const char *spec; }; -const char* float_data::spec = "%LaL"; +const char *float_data::spec = "%LaL"; template -const char* -parse_floating_number(const char* first, const char* last, C& db) -{ - const size_t N = float_data::mangled_size; - if (static_cast(last - first) > N) - { - last = first + N; - union - { - Float value; - char buf[sizeof(Float)]; - }; - const char* t = first; - char* e = buf; - for (; t != last; ++t, ++e) - { - if (!isxdigit(*t)) - return first; - unsigned d1 = isdigit(*t) ? static_cast(*t - '0') : - static_cast(*t - 'a' + 10); - ++t; - unsigned d0 = isdigit(*t) ? static_cast(*t - '0') : - static_cast(*t - 'a' + 10); - *e = static_cast((d1 << 4) + d0); - } - if (*t == 'E') - { +const char *parse_floating_number(const char *first, const char *last, C &db) { + const size_t N = float_data::mangled_size; + if (static_cast(last - first) > N) { + last = first + N; + union { + Float value; + char buf[sizeof(Float)]; + }; + const char *t = first; + char *e = buf; + for (; t != last; ++t, ++e) { + if (!isxdigit(*t)) + return first; + unsigned d1 = isdigit(*t) ? static_cast(*t - '0') + : static_cast(*t - 'a' + 10); + ++t; + unsigned d0 = isdigit(*t) ? static_cast(*t - '0') + : static_cast(*t - 'a' + 10); + *e = static_cast((d1 << 4) + d0); + } + if (*t == 'E') { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - std::reverse(buf, e); + std::reverse(buf, e); #endif - char num[float_data::max_demangled_size] = {0}; - int n = snprintf(num, sizeof(num), float_data::spec, value); - if (static_cast(n) >= sizeof(num)) - return first; - db.names.push_back(typename C::String(num, static_cast(n))); - first = t+1; - } + char num[float_data::max_demangled_size] = {0}; + int n = snprintf(num, sizeof(num), float_data::spec, value); + if (static_cast(n) >= sizeof(num)) + return first; + db.names.push_back(typename C::String(num, static_cast(n))); + first = t + 1; } - return first; + } + return first; } // ::= template -const char* -parse_source_name(const char* first, const char* last, C& db) -{ - if (first != last) - { - char c = *first; - if (isdigit(c) && first+1 != last) - { - const char* t = first+1; - size_t n = static_cast(c - '0'); - for (c = *t; isdigit(c); c = *t) - { - n = n * 10 + static_cast(c - '0'); - if (++t == last) - return first; - } - if (static_cast(last - t) >= n) - { - typename C::String r(t, n); - if (r.substr(0, 10) == "_GLOBAL__N") - db.names.push_back("(anonymous namespace)"); - else - db.names.push_back(std::move(r)); - first = t + n; - } - } +const char *parse_source_name(const char *first, const char *last, C &db) { + if (first != last) { + char c = *first; + if (isdigit(c) && first + 1 != last) { + const char *t = first + 1; + size_t n = static_cast(c - '0'); + for (c = *t; isdigit(c); c = *t) { + n = n * 10 + static_cast(c - '0'); + if (++t == last) + return first; + } + if (static_cast(last - t) >= n) { + typename C::String r(t, n); + if (r.substr(0, 10) == "_GLOBAL__N") + db.names.push_back("(anonymous namespace)"); + else + db.names.push_back(std::move(r)); + first = t + n; + } } - return first; + } + return first; } // ::= S _ @@ -279,79 +244,70 @@ parse_source_name(const char* first, const char* last, C& db) // ::= Sd # ::std::basic_iostream > template -const char* -parse_substitution(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - if (*first == 'S') - { - switch (first[1]) - { - case 'a': - db.names.push_back("std::allocator"); - first += 2; - break; - case 'b': - db.names.push_back("std::basic_string"); - first += 2; - break; - case 's': - db.names.push_back("std::string"); - first += 2; - break; - case 'i': - db.names.push_back("std::istream"); - first += 2; - break; - case 'o': - db.names.push_back("std::ostream"); - first += 2; - break; - case 'd': - db.names.push_back("std::iostream"); - first += 2; - break; - case '_': - if (!db.subs.empty()) - { - for (const auto& n : db.subs.front()) - db.names.push_back(n); - first += 2; - } - break; - default: - if (std::isdigit(first[1]) || std::isupper(first[1])) - { - size_t sub = 0; - const char* t = first+1; - if (std::isdigit(*t)) - sub = static_cast(*t - '0'); - else - sub = static_cast(*t - 'A') + 10; - for (++t; t != last && (std::isdigit(*t) || std::isupper(*t)); ++t) - { - sub *= 36; - if (std::isdigit(*t)) - sub += static_cast(*t - '0'); - else - sub += static_cast(*t - 'A') + 10; - } - if (t == last || *t != '_') - return first; - ++sub; - if (sub < db.subs.size()) - { - for (const auto& n : db.subs[sub]) - db.names.push_back(n); - first = t+1; - } - } - break; - } +const char *parse_substitution(const char *first, const char *last, C &db) { + if (last - first >= 2) { + if (*first == 'S') { + switch (first[1]) { + case 'a': + db.names.push_back("std::allocator"); + first += 2; + break; + case 'b': + db.names.push_back("std::basic_string"); + first += 2; + break; + case 's': + db.names.push_back("std::string"); + first += 2; + break; + case 'i': + db.names.push_back("std::istream"); + first += 2; + break; + case 'o': + db.names.push_back("std::ostream"); + first += 2; + break; + case 'd': + db.names.push_back("std::iostream"); + first += 2; + break; + case '_': + if (!db.subs.empty()) { + for (const auto &n : db.subs.front()) + db.names.push_back(n); + first += 2; + } + break; + default: + if (std::isdigit(first[1]) || std::isupper(first[1])) { + size_t sub = 0; + const char *t = first + 1; + if (std::isdigit(*t)) + sub = static_cast(*t - '0'); + else + sub = static_cast(*t - 'A') + 10; + for (++t; t != last && (std::isdigit(*t) || std::isupper(*t)); ++t) { + sub *= 36; + if (std::isdigit(*t)) + sub += static_cast(*t - '0'); + else + sub += static_cast(*t - 'A') + 10; + } + if (t == last || *t != '_') + return first; + ++sub; + if (sub < db.subs.size()) { + for (const auto &n : db.subs[sub]) + db.names.push_back(n); + first = t + 1; + } } + break; + } } - return first; + } + return first; } // ::= v # void @@ -387,587 +343,513 @@ parse_substitution(const char* first, const char* last, C& db) // ::= u # vendor extended type template -const char* -parse_builtin_type(const char* first, const char* last, C& db) -{ - if (first != last) - { - switch (*first) - { - case 'v': - db.names.push_back("void"); - ++first; - break; - case 'w': - db.names.push_back("wchar_t"); - ++first; - break; - case 'b': - db.names.push_back("bool"); - ++first; - break; - case 'c': - db.names.push_back("char"); - ++first; - break; - case 'a': - db.names.push_back("signed char"); - ++first; - break; +const char *parse_builtin_type(const char *first, const char *last, C &db) { + if (first != last) { + switch (*first) { + case 'v': + db.names.push_back("void"); + ++first; + break; + case 'w': + db.names.push_back("wchar_t"); + ++first; + break; + case 'b': + db.names.push_back("bool"); + ++first; + break; + case 'c': + db.names.push_back("char"); + ++first; + break; + case 'a': + db.names.push_back("signed char"); + ++first; + break; + case 'h': + db.names.push_back("unsigned char"); + ++first; + break; + case 's': + db.names.push_back("short"); + ++first; + break; + case 't': + db.names.push_back("unsigned short"); + ++first; + break; + case 'i': + db.names.push_back("int"); + ++first; + break; + case 'j': + db.names.push_back("unsigned int"); + ++first; + break; + case 'l': + db.names.push_back("long"); + ++first; + break; + case 'm': + db.names.push_back("unsigned long"); + ++first; + break; + case 'x': + db.names.push_back("long long"); + ++first; + break; + case 'y': + db.names.push_back("unsigned long long"); + ++first; + break; + case 'n': + db.names.push_back("__int128"); + ++first; + break; + case 'o': + db.names.push_back("unsigned __int128"); + ++first; + break; + case 'f': + db.names.push_back("float"); + ++first; + break; + case 'd': + db.names.push_back("double"); + ++first; + break; + case 'e': + db.names.push_back("long double"); + ++first; + break; + case 'g': + db.names.push_back("__float128"); + ++first; + break; + case 'z': + db.names.push_back("..."); + ++first; + break; + case 'u': { + const char *t = parse_source_name(first + 1, last, db); + if (t != first + 1) + first = t; + } break; + case 'D': + if (first + 1 != last) { + switch (first[1]) { + case 'd': + db.names.push_back("decimal64"); + first += 2; + break; + case 'e': + db.names.push_back("decimal128"); + first += 2; + break; + case 'f': + db.names.push_back("decimal32"); + first += 2; + break; case 'h': - db.names.push_back("unsigned char"); - ++first; - break; - case 's': - db.names.push_back("short"); - ++first; - break; - case 't': - db.names.push_back("unsigned short"); - ++first; - break; + db.names.push_back("decimal16"); + first += 2; + break; case 'i': - db.names.push_back("int"); - ++first; - break; - case 'j': - db.names.push_back("unsigned int"); - ++first; - break; - case 'l': - db.names.push_back("long"); - ++first; - break; - case 'm': - db.names.push_back("unsigned long"); - ++first; - break; - case 'x': - db.names.push_back("long long"); - ++first; - break; - case 'y': - db.names.push_back("unsigned long long"); - ++first; - break; + db.names.push_back("char32_t"); + first += 2; + break; + case 's': + db.names.push_back("char16_t"); + first += 2; + break; + case 'a': + db.names.push_back("auto"); + first += 2; + break; + case 'c': + db.names.push_back("decltype(auto)"); + first += 2; + break; case 'n': - db.names.push_back("__int128"); - ++first; - break; - case 'o': - db.names.push_back("unsigned __int128"); - ++first; - break; - case 'f': - db.names.push_back("float"); - ++first; - break; - case 'd': - db.names.push_back("double"); - ++first; - break; - case 'e': - db.names.push_back("long double"); - ++first; - break; - case 'g': - db.names.push_back("__float128"); - ++first; - break; - case 'z': - db.names.push_back("..."); - ++first; - break; - case 'u': - { - const char*t = parse_source_name(first+1, last, db); - if (t != first+1) - first = t; - } - break; - case 'D': - if (first+1 != last) - { - switch (first[1]) - { - case 'd': - db.names.push_back("decimal64"); - first += 2; - break; - case 'e': - db.names.push_back("decimal128"); - first += 2; - break; - case 'f': - db.names.push_back("decimal32"); - first += 2; - break; - case 'h': - db.names.push_back("decimal16"); - first += 2; - break; - case 'i': - db.names.push_back("char32_t"); - first += 2; - break; - case 's': - db.names.push_back("char16_t"); - first += 2; - break; - case 'a': - db.names.push_back("auto"); - first += 2; - break; - case 'c': - db.names.push_back("decltype(auto)"); - first += 2; - break; - case 'n': - db.names.push_back("std::nullptr_t"); - first += 2; - break; - } - } - break; + db.names.push_back("std::nullptr_t"); + first += 2; + break; } + } + break; } - return first; + } + return first; } // ::= [r] [V] [K] -const char* -parse_cv_qualifiers(const char* first, const char* last, unsigned& cv) -{ - cv = 0; - if (first != last) - { - if (*first == 'r') - { - cv |= 4; - ++first; - } - if (*first == 'V') - { - cv |= 2; - ++first; - } - if (*first == 'K') - { - cv |= 1; - ++first; - } +const char *parse_cv_qualifiers(const char *first, const char *last, + unsigned &cv) { + cv = 0; + if (first != last) { + if (*first == 'r') { + cv |= 4; + ++first; + } + if (*first == 'V') { + cv |= 2; + ++first; } - return first; + if (*first == 'K') { + cv |= 1; + ++first; + } + } + return first; } // ::= T_ # first template parameter // ::= T _ template -const char* -parse_template_param(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - if (*first == 'T') - { - if (first[1] == '_') - { - if (db.template_param.empty()) - return first; - if (!db.template_param.back().empty()) - { - for (auto& t : db.template_param.back().front()) - db.names.push_back(t); - first += 2; - } - else - { - db.names.push_back("T_"); - first += 2; - db.fix_forward_references = true; - } - } - else if (isdigit(first[1])) - { - const char* t = first+1; - size_t sub = static_cast(*t - '0'); - for (++t; t != last && isdigit(*t); ++t) - { - sub *= 10; - sub += static_cast(*t - '0'); - } - if (t == last || *t != '_' || db.template_param.empty()) - return first; - ++sub; - if (sub < db.template_param.back().size()) - { - for (auto& temp : db.template_param.back()[sub]) - db.names.push_back(temp); - first = t+1; - } - else - { - db.names.push_back(typename C::String(first, t+1)); - first = t+1; - db.fix_forward_references = true; - } - } +const char *parse_template_param(const char *first, const char *last, C &db) { + if (last - first >= 2) { + if (*first == 'T') { + if (first[1] == '_') { + if (db.template_param.empty()) + return first; + if (!db.template_param.back().empty()) { + for (auto &t : db.template_param.back().front()) + db.names.push_back(t); + first += 2; + } else { + db.names.push_back("T_"); + first += 2; + db.fix_forward_references = true; + } + } else if (isdigit(first[1])) { + const char *t = first + 1; + size_t sub = static_cast(*t - '0'); + for (++t; t != last && isdigit(*t); ++t) { + sub *= 10; + sub += static_cast(*t - '0'); } + if (t == last || *t != '_' || db.template_param.empty()) + return first; + ++sub; + if (sub < db.template_param.back().size()) { + for (auto &temp : db.template_param.back()[sub]) + db.names.push_back(temp); + first = t + 1; + } else { + db.names.push_back(typename C::String(first, t + 1)); + first = t + 1; + db.fix_forward_references = true; + } + } } - return first; + } + return first; } -// cc # const_cast (expression) +// cc # const_cast +// (expression) template -const char* -parse_const_cast_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'c' && first[1] == 'c') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto expr = db.names.back().move_full(); - db.names.pop_back(); - db.names.back() = "const_cast<" + db.names.back().move_full() + ">(" + expr + ")"; - first = t1; - } - } +const char *parse_const_cast_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'c' && first[1] == 'c') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto expr = db.names.back().move_full(); + db.names.pop_back(); + db.names.back() = + "const_cast<" + db.names.back().move_full() + ">(" + expr + ")"; + first = t1; + } } - return first; + } + return first; } -// dc # dynamic_cast (expression) +// dc # dynamic_cast +// (expression) template -const char* -parse_dynamic_cast_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'd' && first[1] == 'c') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto expr = db.names.back().move_full(); - db.names.pop_back(); - db.names.back() = "dynamic_cast<" + db.names.back().move_full() + ">(" + expr + ")"; - first = t1; - } - } +const char *parse_dynamic_cast_expr(const char *first, const char *last, + C &db) { + if (last - first >= 3 && first[0] == 'd' && first[1] == 'c') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto expr = db.names.back().move_full(); + db.names.pop_back(); + db.names.back() = + "dynamic_cast<" + db.names.back().move_full() + ">(" + expr + ")"; + first = t1; + } } - return first; + } + return first; } -// rc # reinterpret_cast (expression) +// rc # reinterpret_cast +// (expression) template -const char* -parse_reinterpret_cast_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'r' && first[1] == 'c') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto expr = db.names.back().move_full(); - db.names.pop_back(); - db.names.back() = "reinterpret_cast<" + db.names.back().move_full() + ">(" + expr + ")"; - first = t1; - } - } +const char *parse_reinterpret_cast_expr(const char *first, const char *last, + C &db) { + if (last - first >= 3 && first[0] == 'r' && first[1] == 'c') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto expr = db.names.back().move_full(); + db.names.pop_back(); + db.names.back() = "reinterpret_cast<" + db.names.back().move_full() + + ">(" + expr + ")"; + first = t1; + } } - return first; + } + return first; } -// sc # static_cast (expression) +// sc # static_cast +// (expression) template -const char* -parse_static_cast_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 'c') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto expr = db.names.back().move_full(); - db.names.pop_back(); - db.names.back() = "static_cast<" + db.names.back().move_full() + ">(" + expr + ")"; - first = t1; - } - } +const char *parse_static_cast_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 'c') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto expr = db.names.back().move_full(); + db.names.pop_back(); + db.names.back() = + "static_cast<" + db.names.back().move_full() + ">(" + expr + ")"; + first = t1; + } } - return first; + } + return first; } // sp # pack expansion template -const char* -parse_pack_expansion(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 'p') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - first = t; - } - return first; +const char *parse_pack_expansion(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 'p') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) + first = t; + } + return first; } // st # sizeof (a type) template -const char* -parse_sizeof_type_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 't') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "sizeof (" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_sizeof_type_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 't') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "sizeof (" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } // sz # sizeof (a expression) template -const char* -parse_sizeof_expr_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 'z') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "sizeof (" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_sizeof_expr_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 'z') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "sizeof (" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } -// sZ # size of a parameter pack +// sZ # size of a parameter +// pack template -const char* -parse_sizeof_param_pack_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 'Z' && first[2] == 'T') - { - size_t k0 = db.names.size(); - const char* t = parse_template_param(first+2, last, db); - size_t k1 = db.names.size(); - if (t != first+2) - { - typename C::String tmp("sizeof...("); - size_t k = k0; - if (k != k1) - { - tmp += db.names[k].move_full(); - for (++k; k != k1; ++k) - tmp += ", " + db.names[k].move_full(); - } - tmp += ")"; - for (; k1 != k0; --k1) - db.names.pop_back(); - db.names.push_back(std::move(tmp)); - first = t; - } +const char *parse_sizeof_param_pack_expr(const char *first, const char *last, + C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 'Z' && + first[2] == 'T') { + size_t k0 = db.names.size(); + const char *t = parse_template_param(first + 2, last, db); + size_t k1 = db.names.size(); + if (t != first + 2) { + typename C::String tmp("sizeof...("); + size_t k = k0; + if (k != k1) { + tmp += db.names[k].move_full(); + for (++k; k != k1; ++k) + tmp += ", " + db.names[k].move_full(); + } + tmp += ")"; + for (; k1 != k0; --k1) + db.names.pop_back(); + db.names.push_back(std::move(tmp)); + first = t; } - return first; + } + return first; } -// ::= fp _ # L == 0, first parameter -// ::= fp _ # L == 0, second and later parameters -// ::= fL p _ # L > 0, first parameter -// ::= fL p _ # L > 0, second and later parameters +// ::= fp _ # L == 0, first parameter +// ::= fp _ # L == 0, second and later parameters +// ::= fL p +// _ # L > 0, first parameter +// ::= fL p +// _ # L > 0, second and +// later parameters template -const char* -parse_function_param(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && *first == 'f') - { - if (first[1] == 'p') - { - unsigned cv; - const char* t = parse_cv_qualifiers(first+2, last, cv); - const char* t1 = parse_number(t, last); - if (t1 != last && *t1 == '_') - { - db.names.push_back("fp" + typename C::String(t, t1)); - first = t1+1; - } - } - else if (first[1] == 'L') - { - unsigned cv; - const char* t0 = parse_number(first+2, last); - if (t0 != last && *t0 == 'p') - { - ++t0; - const char* t = parse_cv_qualifiers(t0, last, cv); - const char* t1 = parse_number(t, last); - if (t1 != last && *t1 == '_') - { - db.names.push_back("fp" + typename C::String(t, t1)); - first = t1+1; - } - } +const char *parse_function_param(const char *first, const char *last, C &db) { + if (last - first >= 3 && *first == 'f') { + if (first[1] == 'p') { + unsigned cv; + const char *t = parse_cv_qualifiers(first + 2, last, cv); + const char *t1 = parse_number(t, last); + if (t1 != last && *t1 == '_') { + db.names.push_back("fp" + typename C::String(t, t1)); + first = t1 + 1; + } + } else if (first[1] == 'L') { + unsigned cv; + const char *t0 = parse_number(first + 2, last); + if (t0 != last && *t0 == 'p') { + ++t0; + const char *t = parse_cv_qualifiers(t0, last, cv); + const char *t1 = parse_number(t, last); + if (t1 != last && *t1 == '_') { + db.names.push_back("fp" + typename C::String(t, t1)); + first = t1 + 1; } + } } - return first; + } + return first; } -// sZ # size of a function parameter pack +// sZ # size of a function +// parameter pack template -const char* -parse_sizeof_function_param_pack_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 's' && first[1] == 'Z' && first[2] == 'f') - { - const char* t = parse_function_param(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "sizeof...(" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_sizeof_function_param_pack_expr(const char *first, + const char *last, C &db) { + if (last - first >= 3 && first[0] == 's' && first[1] == 'Z' && + first[2] == 'f') { + const char *t = parse_function_param(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "sizeof...(" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } // te # typeid (expression) // ti # typeid (type) template -const char* -parse_typeid_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 't' && (first[1] == 'e' || first[1] == 'i')) - { - const char* t; - if (first[1] == 'e') - t = parse_expression(first+2, last, db); - else - t = parse_type(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "typeid(" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_typeid_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 't' && + (first[1] == 'e' || first[1] == 'i')) { + const char *t; + if (first[1] == 'e') + t = parse_expression(first + 2, last, db); + else + t = parse_type(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "typeid(" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } // tw # throw expression template -const char* -parse_throw_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 't' && first[1] == 'w') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "throw " + db.names.back().move_full(); - first = t; - } +const char *parse_throw_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 't' && first[1] == 'w') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "throw " + db.names.back().move_full(); + first = t; } - return first; + } + return first; } // ds # expr.*expr template -const char* -parse_dot_star_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'd' && first[1] == 's') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto expr = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += ".*" + expr; - first = t1; - } - } +const char *parse_dot_star_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'd' && first[1] == 's') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto expr = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += ".*" + expr; + first = t1; + } } - return first; + } + return first; } // ::= [ ] template -const char* -parse_simple_id(const char* first, const char* last, C& db) -{ - if (first != last) - { - const char* t = parse_source_name(first, last, db); - if (t != first) - { - const char* t1 = parse_template_args(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - } - first = t1; - } - else - first = t; - } - return first; +const char *parse_simple_id(const char *first, const char *last, C &db) { + if (first != last) { + const char *t = parse_source_name(first, last, db); + if (t != first) { + const char *t1 = parse_template_args(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + } + first = t1; + } else + first = t; + } + return first; } // ::= @@ -975,615 +857,552 @@ parse_simple_id(const char* first, const char* last, C& db) // ::= template -const char* -parse_unresolved_type(const char* first, const char* last, C& db) -{ - if (first != last) - { - const char* t = first; - switch (*first) - { - case 'T': - { - size_t k0 = db.names.size(); - t = parse_template_param(first, last, db); - size_t k1 = db.names.size(); - if (t != first && k1 == k0 + 1) - { - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - else - { - for (; k1 != k0; --k1) - db.names.pop_back(); - } - break; - } - case 'D': - t = parse_decltype(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - break; - case 'S': - t = parse_substitution(first, last, db); - if (t != first) - first = t; - else - { - if (last - first > 2 && first[1] == 't') - { - t = parse_unqualified_name(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "std::"); - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - } - } - break; - } +const char *parse_unresolved_type(const char *first, const char *last, C &db) { + if (first != last) { + const char *t = first; + switch (*first) { + case 'T': { + size_t k0 = db.names.size(); + t = parse_template_param(first, last, db); + size_t k1 = db.names.size(); + if (t != first && k1 == k0 + 1) { + db.subs.push_back( + typename C::sub_type(1, db.names.back(), db.names.get_allocator())); + first = t; + } else { + for (; k1 != k0; --k1) + db.names.pop_back(); + } + break; } - return first; -} - -// ::= # e.g., ~T or ~decltype(f()) -// ::= # e.g., ~A<2*N> - -template -const char* -parse_destructor_name(const char* first, const char* last, C& db) -{ - if (first != last) - { - const char* t = parse_unresolved_type(first, last, db); - if (t == first) - t = parse_simple_id(first, last, db); - if (t != first) - { + case 'D': + t = parse_decltype(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.subs.push_back( + typename C::sub_type(1, db.names.back(), db.names.get_allocator())); + first = t; + } + break; + case 'S': + t = parse_substitution(first, last, db); + if (t != first) + first = t; + else { + if (last - first > 2 && first[1] == 't') { + t = parse_unqualified_name(first + 2, last, db); + if (t != first + 2) { if (db.names.empty()) - return first; - db.names.back().first.insert(0, "~"); + return first; + db.names.back().first.insert(0, "std::"); + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); first = t; + } } + } + break; } - return first; + } + return first; } -// ::= # unresolved name -// extension ::= # unresolved operator-function-id -// extension ::= # unresolved operator template-id -// ::= on # unresolved operator-function-id -// ::= on # unresolved operator template-id -// ::= dn # destructor or pseudo-destructor; -// # e.g. ~X or ~X +// ::= # e.g., +// ~T or ~decltype(f()) +// ::= # e.g., +// ~A<2*N> template -const char* -parse_base_unresolved_name(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - if ((first[0] == 'o' || first[0] == 'd') && first[1] == 'n') - { - if (first[0] == 'o') - { - const char* t = parse_operator_name(first+2, last, db); - if (t != first+2) - { - first = parse_template_args(t, last, db); - if (first != t) - { - if (db.names.size() < 2) - return first; - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - } - } - } - else - { - const char* t = parse_destructor_name(first+2, last, db); - if (t != first+2) - first = t; - } - } - else - { - const char* t = parse_simple_id(first, last, db); - if (t == first) - { - t = parse_operator_name(first, last, db); - if (t != first) - { - first = parse_template_args(t, last, db); - if (first != t) - { - if (db.names.size() < 2) - return first; - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - } - } - } - else - first = t; - } +const char *parse_destructor_name(const char *first, const char *last, C &db) { + if (first != last) { + const char *t = parse_unresolved_type(first, last, db); + if (t == first) + t = parse_simple_id(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "~"); + first = t; } - return first; + } + return first; } -// ::= +// ::= # +// unresolved name +// extension ::= # +// unresolved operator-function-id +// extension ::= # +// unresolved operator template-id +// ::= on # +// unresolved operator-function-id +// ::= on # +// unresolved operator template-id +// ::= dn # +// destructor or pseudo-destructor; +// # +// e.g. +// ~X or +// ~X template -const char* -parse_unresolved_qualifier_level(const char* first, const char* last, C& db) -{ - return parse_simple_id(first, last, db); -} +const char *parse_base_unresolved_name(const char *first, const char *last, + C &db) { + if (last - first >= 2) { + if ((first[0] == 'o' || first[0] == 'd') && first[1] == 'n') { + if (first[0] == 'o') { + const char *t = parse_operator_name(first + 2, last, db); + if (t != first + 2) { + first = parse_template_args(t, last, db); + if (first != t) { + if (db.names.size() < 2) + return first; + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + } + } + } else { + const char *t = parse_destructor_name(first + 2, last, db); + if (t != first + 2) + first = t; + } + } else { + const char *t = parse_simple_id(first, last, db); + if (t == first) { + t = parse_operator_name(first, last, db); + if (t != first) { + first = parse_template_args(t, last, db); + if (first != t) { + if (db.names.size() < 2) + return first; + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + } + } + } else + first = t; + } + } + return first; +} + +// ::= + +template +const char *parse_unresolved_qualifier_level(const char *first, + const char *last, C &db) { + return parse_simple_id(first, last, db); +} // -// extension ::= srN [] * E -// ::= [gs] # x or (with "gs") ::x -// ::= [gs] sr + E -// # A::x, N::y, A::z; "gs" means leading "::" -// ::= sr # T::x / decltype(p)::x -// extension ::= sr -// # T::N::x /decltype(p)::N::x -// (ignored) ::= srN + E +// extension ::= srN [] +// * E +// ::= [gs] # x or +// (with "gs") ::x +// ::= [gs] sr + E +// +// # A::x, +// N::y, +// A::z; +// "gs" +// means +// leading +// "::" +// ::= sr # T::x +// / decltype(p)::x +// extension ::= sr +// +// # +// T::N::x +// /decltype(p)::N::x +// (ignored) ::= srN + E +// template -const char* -parse_unresolved_name(const char* first, const char* last, C& db) -{ - if (last - first > 2) - { - const char* t = first; - bool global = false; - if (t[0] == 'g' && t[1] == 's') - { - global = true; - t += 2; +const char *parse_unresolved_name(const char *first, const char *last, C &db) { + if (last - first > 2) { + const char *t = first; + bool global = false; + if (t[0] == 'g' && t[1] == 's') { + global = true; + t += 2; + } + const char *t2 = parse_base_unresolved_name(t, last, db); + if (t2 != t) { + if (global) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "::"); + } + first = t2; + } else if (last - t > 2 && t[0] == 's' && t[1] == 'r') { + if (t[2] == 'N') { + t += 3; + const char *t1 = parse_unresolved_type(t, last, db); + if (t1 == t || t1 == last) + return first; + t = t1; + t1 = parse_template_args(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + t = t1; + if (t == last) { + db.names.pop_back(); + return first; + } } - const char* t2 = parse_base_unresolved_name(t, last, db); - if (t2 != t) - { - if (global) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "::"); - } - first = t2; + while (*t != 'E') { + t1 = parse_unresolved_qualifier_level(t, last, db); + if (t1 == t || t1 == last || db.names.size() < 2) + return first; + auto s = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "::" + std::move(s); + t = t1; } - else if (last - t > 2 && t[0] == 's' && t[1] == 'r') - { - if (t[2] == 'N') - { - t += 3; - const char* t1 = parse_unresolved_type(t, last, db); - if (t1 == t || t1 == last) - return first; - t = t1; - t1 = parse_template_args(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - t = t1; - if (t == last) - { - db.names.pop_back(); - return first; - } - } - while (*t != 'E') - { - t1 = parse_unresolved_qualifier_level(t, last, db); - if (t1 == t || t1 == last || db.names.size() < 2) - return first; - auto s = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "::" + std::move(s); - t = t1; - } - ++t; - t1 = parse_base_unresolved_name(t, last, db); - if (t1 == t) - { - if (!db.names.empty()) - db.names.pop_back(); - return first; - } - if (db.names.size() < 2) - return first; - auto s = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "::" + std::move(s); - first = t1; - } - else - { - t += 2; - const char* t1 = parse_unresolved_type(t, last, db); - if (t1 != t) - { - t = t1; - t1 = parse_template_args(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - t = t1; - } - t1 = parse_base_unresolved_name(t, last, db); - if (t1 == t) - { - if (!db.names.empty()) - db.names.pop_back(); - return first; - } - if (db.names.size() < 2) - return first; - auto s = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "::" + std::move(s); - first = t1; - } - else - { - t1 = parse_unresolved_qualifier_level(t, last, db); - if (t1 == t || t1 == last) - return first; - t = t1; - if (global) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "::"); - } - while (*t != 'E') - { - t1 = parse_unresolved_qualifier_level(t, last, db); - if (t1 == t || t1 == last || db.names.size() < 2) - return first; - auto s = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "::" + std::move(s); - t = t1; - } - ++t; - t1 = parse_base_unresolved_name(t, last, db); - if (t1 == t) - { - if (!db.names.empty()) - db.names.pop_back(); - return first; - } - if (db.names.size() < 2) - return first; - auto s = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "::" + std::move(s); - first = t1; - } - } + ++t; + t1 = parse_base_unresolved_name(t, last, db); + if (t1 == t) { + if (!db.names.empty()) + db.names.pop_back(); + return first; + } + if (db.names.size() < 2) + return first; + auto s = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "::" + std::move(s); + first = t1; + } else { + t += 2; + const char *t1 = parse_unresolved_type(t, last, db); + if (t1 != t) { + t = t1; + t1 = parse_template_args(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + t = t1; + } + t1 = parse_base_unresolved_name(t, last, db); + if (t1 == t) { + if (!db.names.empty()) + db.names.pop_back(); + return first; + } + if (db.names.size() < 2) + return first; + auto s = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "::" + std::move(s); + first = t1; + } else { + t1 = parse_unresolved_qualifier_level(t, last, db); + if (t1 == t || t1 == last) + return first; + t = t1; + if (global) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "::"); + } + while (*t != 'E') { + t1 = parse_unresolved_qualifier_level(t, last, db); + if (t1 == t || t1 == last || db.names.size() < 2) + return first; + auto s = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "::" + std::move(s); + t = t1; + } + ++t; + t1 = parse_base_unresolved_name(t, last, db); + if (t1 == t) { + if (!db.names.empty()) + db.names.pop_back(); + return first; + } + if (db.names.size() < 2) + return first; + auto s = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "::" + std::move(s); + first = t1; } + } } - return first; + } + return first; } // dt # expr.name template -const char* -parse_dot_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'd' && first[1] == 't') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_unresolved_name(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto name = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "." + name; - first = t1; - } - } +const char *parse_dot_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'd' && first[1] == 't') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_unresolved_name(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto name = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "." + name; + first = t1; + } } - return first; + } + return first; } // cl + E # call template -const char* -parse_call_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 4 && first[0] == 'c' && first[1] == 'l') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - if (t == last) - return first; - if (db.names.empty()) - return first; - db.names.back().first += db.names.back().second; - db.names.back().second = typename C::String(); - db.names.back().first.append("("); - bool first_expr = true; - while (*t != 'E') - { - const char* t1 = parse_expression(t, last, db); - if (t1 == t || t1 == last) - return first; - if (db.names.empty()) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - if (!tmp.empty()) - { - if (db.names.empty()) - return first; - if (!first_expr) - { - db.names.back().first.append(", "); - first_expr = false; - } - db.names.back().first.append(tmp); - } - t = t1; - } - ++t; - if (db.names.empty()) - return first; - db.names.back().first.append(")"); - first = t; +const char *parse_call_expr(const char *first, const char *last, C &db) { + if (last - first >= 4 && first[0] == 'c' && first[1] == 'l') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + if (t == last) + return first; + if (db.names.empty()) + return first; + db.names.back().first += db.names.back().second; + db.names.back().second = typename C::String(); + db.names.back().first.append("("); + bool first_expr = true; + while (*t != 'E') { + const char *t1 = parse_expression(t, last, db); + if (t1 == t || t1 == last) + return first; + if (db.names.empty()) + return first; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + if (!tmp.empty()) { + if (db.names.empty()) + return first; + if (!first_expr) { + db.names.back().first.append(", "); + first_expr = false; + } + db.names.back().first.append(tmp); } + t = t1; + } + ++t; + if (db.names.empty()) + return first; + db.names.back().first.append(")"); + first = t; } - return first; + } + return first; } // [gs] nw * _ E # new (expr-list) type -// [gs] nw * _ # new (expr-list) type (init) +// [gs] nw * _ # new (expr-list) type +// (init) // [gs] na * _ E # new[] (expr-list) type -// [gs] na * _ # new[] (expr-list) type (init) -// ::= pi * E # parenthesized initialization +// [gs] na * _ # new[] (expr-list) type +// (init) +// ::= pi * E # parenthesized +// initialization template -const char* -parse_new_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 4) - { - const char* t = first; - bool parsed_gs = false; - if (t[0] == 'g' && t[1] == 's') - { - t += 2; - parsed_gs = true; +const char *parse_new_expr(const char *first, const char *last, C &db) { + if (last - first >= 4) { + const char *t = first; + bool parsed_gs = false; + if (t[0] == 'g' && t[1] == 's') { + t += 2; + parsed_gs = true; + } + if (t[0] == 'n' && (t[1] == 'w' || t[1] == 'a')) { + bool is_array = t[1] == 'a'; + t += 2; + if (t == last) + return first; + bool has_expr_list = false; + bool first_expr = true; + while (*t != '_') { + const char *t1 = parse_expression(t, last, db); + if (t1 == t || t1 == last) + return first; + has_expr_list = true; + if (!first_expr) { + if (db.names.empty()) + return first; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + if (!tmp.empty()) { + if (db.names.empty()) + return first; + db.names.back().first.append(", "); + db.names.back().first.append(tmp); + first_expr = false; + } } - if (t[0] == 'n' && (t[1] == 'w' || t[1] == 'a')) - { - bool is_array = t[1] == 'a'; - t += 2; - if (t == last) - return first; - bool has_expr_list = false; - bool first_expr = true; - while (*t != '_') - { - const char* t1 = parse_expression(t, last, db); - if (t1 == t || t1 == last) - return first; - has_expr_list = true; - if (!first_expr) - { - if (db.names.empty()) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - if (!tmp.empty()) - { - if (db.names.empty()) - return first; - db.names.back().first.append(", "); - db.names.back().first.append(tmp); - first_expr = false; - } - } - t = t1; - } - ++t; - const char* t1 = parse_type(t, last, db); - if (t1 == t || t1 == last) - return first; - t = t1; - bool has_init = false; - if (last - t >= 3 && t[0] == 'p' && t[1] == 'i') - { - t += 2; - has_init = true; - first_expr = true; - while (*t != 'E') - { - t1 = parse_expression(t, last, db); - if (t1 == t || t1 == last) - return first; - if (!first_expr) - { - if (db.names.empty()) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - if (!tmp.empty()) - { - if (db.names.empty()) - return first; - db.names.back().first.append(", "); - db.names.back().first.append(tmp); - first_expr = false; - } - } - t = t1; - } - } - if (*t != 'E') - return first; - typename C::String init_list; - if (has_init) - { - if (db.names.empty()) - return first; - init_list = db.names.back().move_full(); - db.names.pop_back(); - } + t = t1; + } + ++t; + const char *t1 = parse_type(t, last, db); + if (t1 == t || t1 == last) + return first; + t = t1; + bool has_init = false; + if (last - t >= 3 && t[0] == 'p' && t[1] == 'i') { + t += 2; + has_init = true; + first_expr = true; + while (*t != 'E') { + t1 = parse_expression(t, last, db); + if (t1 == t || t1 == last) + return first; + if (!first_expr) { if (db.names.empty()) - return first; - auto type = db.names.back().move_full(); + return first; + auto tmp = db.names.back().move_full(); db.names.pop_back(); - typename C::String expr_list; - if (has_expr_list) - { - if (db.names.empty()) - return first; - expr_list = db.names.back().move_full(); - db.names.pop_back(); + if (!tmp.empty()) { + if (db.names.empty()) + return first; + db.names.back().first.append(", "); + db.names.back().first.append(tmp); + first_expr = false; } - typename C::String r; - if (parsed_gs) - r = "::"; - if (is_array) - r += "[] "; - else - r += " "; - if (has_expr_list) - r += "(" + expr_list + ") "; - r += type; - if (has_init) - r += " (" + init_list + ")"; - db.names.push_back(std::move(r)); - first = t+1; + } + t = t1; } + } + if (*t != 'E') + return first; + typename C::String init_list; + if (has_init) { + if (db.names.empty()) + return first; + init_list = db.names.back().move_full(); + db.names.pop_back(); + } + if (db.names.empty()) + return first; + auto type = db.names.back().move_full(); + db.names.pop_back(); + typename C::String expr_list; + if (has_expr_list) { + if (db.names.empty()) + return first; + expr_list = db.names.back().move_full(); + db.names.pop_back(); + } + typename C::String r; + if (parsed_gs) + r = "::"; + if (is_array) + r += "[] "; + else + r += " "; + if (has_expr_list) + r += "(" + expr_list + ") "; + r += type; + if (has_init) + r += " (" + init_list + ")"; + db.names.push_back(std::move(r)); + first = t + 1; } - return first; + } + return first; } -// cv # conversion with one argument -// cv _ * E # conversion with a different number of arguments +// cv # conversion with one +// argument +// cv _ * E # conversion with a +// different number of arguments template -const char* -parse_conversion_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'c' && first[1] == 'v') - { - bool try_to_parse_template_args = db.try_to_parse_template_args; - db.try_to_parse_template_args = false; - const char* t = parse_type(first+2, last, db); - db.try_to_parse_template_args = try_to_parse_template_args; - if (t != first+2 && t != last) - { - if (*t != '_') - { - const char* t1 = parse_expression(t, last, db); - if (t1 == t) - return first; - t = t1; - } - else - { - ++t; - if (t == last) - return first; - if (*t == 'E') - db.names.emplace_back(); - else - { - bool first_expr = true; - while (*t != 'E') - { - const char* t1 = parse_expression(t, last, db); - if (t1 == t || t1 == last) - return first; - if (!first_expr) - { - if (db.names.empty()) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - if (!tmp.empty()) - { - if (db.names.empty()) - return first; - db.names.back().first.append(", "); - db.names.back().first.append(tmp); - first_expr = false; - } - } - t = t1; - } - } - ++t; - } - if (db.names.size() < 2) +const char *parse_conversion_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'c' && first[1] == 'v') { + bool try_to_parse_template_args = db.try_to_parse_template_args; + db.try_to_parse_template_args = false; + const char *t = parse_type(first + 2, last, db); + db.try_to_parse_template_args = try_to_parse_template_args; + if (t != first + 2 && t != last) { + if (*t != '_') { + const char *t1 = parse_expression(t, last, db); + if (t1 == t) + return first; + t = t1; + } else { + ++t; + if (t == last) + return first; + if (*t == 'E') + db.names.emplace_back(); + else { + bool first_expr = true; + while (*t != 'E') { + const char *t1 = parse_expression(t, last, db); + if (t1 == t || t1 == last) + return first; + if (!first_expr) { + if (db.names.empty()) return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - db.names.back() = "(" + db.names.back().move_full() + ")(" + tmp + ")"; - first = t; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + if (!tmp.empty()) { + if (db.names.empty()) + return first; + db.names.back().first.append(", "); + db.names.back().first.append(tmp); + first_expr = false; + } + } + t = t1; + } } + ++t; + } + if (db.names.size() < 2) + return first; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + db.names.back() = "(" + db.names.back().move_full() + ")(" + tmp + ")"; + first = t; } - return first; + } + return first; } // pt # expr->name template -const char* -parse_arrow_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'p' && first[1] == 't') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - const char* t1 = parse_expression(t, last, db); - if (t1 != t) - { - if (db.names.size() < 2) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += "->"; - db.names.back().first += tmp; - first = t1; - } - } +const char *parse_arrow_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'p' && first[1] == 't') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + const char *t1 = parse_expression(t, last, db); + if (t1 != t) { + if (db.names.size() < 2) + return first; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += "->"; + db.names.back().first += tmp; + first = t1; + } } - return first; + } + return first; } // ::= R # & ref-qualifier @@ -1592,218 +1411,182 @@ parse_arrow_expr(const char* first, const char* last, C& db) // ::= F [Y] [] E template -const char* -parse_function_type(const char* first, const char* last, C& db) -{ - if (first != last && *first == 'F') - { - const char* t = first+1; - if (t != last) - { - if (*t == 'Y') - { - /* extern "C" */ - if (++t == last) - return first; - } - const char* t1 = parse_type(t, last, db); - if (t1 != t) - { - t = t1; - typename C::String sig("("); - int ref_qual = 0; - while (true) - { - if (t == last) - { - db.names.pop_back(); - return first; - } - if (*t == 'E') - { - ++t; - break; - } - if (*t == 'v') - { - ++t; - continue; - } - if (*t == 'R' && t+1 != last && t[1] == 'E') - { - ref_qual = 1; - ++t; - continue; - } - if (*t == 'O' && t+1 != last && t[1] == 'E') - { - ref_qual = 2; - ++t; - continue; - } - size_t k0 = db.names.size(); - t1 = parse_type(t, last, db); - size_t k1 = db.names.size(); - if (t1 == t || t1 == last) - return first; - for (size_t k = k0; k < k1; ++k) - { - if (sig.size() > 1) - sig += ", "; - sig += db.names[k].move_full(); - } - for (size_t k = k0; k < k1; ++k) - db.names.pop_back(); - t = t1; - } - sig += ")"; - switch (ref_qual) - { - case 1: - sig += " &"; - break; - case 2: - sig += " &&"; - break; - } - if (db.names.empty()) - return first; - db.names.back().first += " "; - db.names.back().second.insert(0, sig); - first = t; - } +const char *parse_function_type(const char *first, const char *last, C &db) { + if (first != last && *first == 'F') { + const char *t = first + 1; + if (t != last) { + if (*t == 'Y') { + /* extern "C" */ + if (++t == last) + return first; + } + const char *t1 = parse_type(t, last, db); + if (t1 != t) { + t = t1; + typename C::String sig("("); + int ref_qual = 0; + while (true) { + if (t == last) { + db.names.pop_back(); + return first; + } + if (*t == 'E') { + ++t; + break; + } + if (*t == 'v') { + ++t; + continue; + } + if (*t == 'R' && t + 1 != last && t[1] == 'E') { + ref_qual = 1; + ++t; + continue; + } + if (*t == 'O' && t + 1 != last && t[1] == 'E') { + ref_qual = 2; + ++t; + continue; + } + size_t k0 = db.names.size(); + t1 = parse_type(t, last, db); + size_t k1 = db.names.size(); + if (t1 == t || t1 == last) + return first; + for (size_t k = k0; k < k1; ++k) { + if (sig.size() > 1) + sig += ", "; + sig += db.names[k].move_full(); + } + for (size_t k = k0; k < k1; ++k) + db.names.pop_back(); + t = t1; + } + sig += ")"; + switch (ref_qual) { + case 1: + sig += " &"; + break; + case 2: + sig += " &&"; + break; } + if (db.names.empty()) + return first; + db.names.back().first += " "; + db.names.back().second.insert(0, sig); + first = t; + } } - return first; + } + return first; } // ::= M template -const char* -parse_pointer_to_member_type(const char* first, const char* last, C& db) -{ - if (first != last && *first == 'M') - { - const char* t = parse_type(first+1, last, db); - if (t != first+1) - { - const char* t2 = parse_type(t, last, db); - if (t2 != t) - { - if (db.names.size() < 2) - return first; - auto func = std::move(db.names.back()); - db.names.pop_back(); - auto class_type = std::move(db.names.back()); - if (!func.second.empty() && func.second.front() == '(') - { - db.names.back().first = std::move(func.first) + "(" + class_type.move_full() + "::*"; - db.names.back().second = ")" + std::move(func.second); - } - else - { - db.names.back().first = std::move(func.first) + " " + class_type.move_full() + "::*"; - db.names.back().second = std::move(func.second); - } - first = t2; - } +const char *parse_pointer_to_member_type(const char *first, const char *last, + C &db) { + if (first != last && *first == 'M') { + const char *t = parse_type(first + 1, last, db); + if (t != first + 1) { + const char *t2 = parse_type(t, last, db); + if (t2 != t) { + if (db.names.size() < 2) + return first; + auto func = std::move(db.names.back()); + db.names.pop_back(); + auto class_type = std::move(db.names.back()); + if (!func.second.empty() && func.second.front() == '(') { + db.names.back().first = + std::move(func.first) + "(" + class_type.move_full() + "::*"; + db.names.back().second = ")" + std::move(func.second); + } else { + db.names.back().first = + std::move(func.first) + " " + class_type.move_full() + "::*"; + db.names.back().second = std::move(func.second); } + first = t2; + } } - return first; + } + return first; } // ::= A _ // ::= A [] _ template -const char* -parse_array_type(const char* first, const char* last, C& db) -{ - if (first != last && *first == 'A' && first+1 != last) - { - if (first[1] == '_') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - if (db.names.back().second.substr(0, 2) == " [") - db.names.back().second.erase(0, 1); - db.names.back().second.insert(0, " []"); - first = t; - } - } - else if ('1' <= first[1] && first[1] <= '9') - { - const char* t = parse_number(first+1, last); - if (t != last && *t == '_') - { - const char* t2 = parse_type(t+1, last, db); - if (t2 != t+1) - { - if (db.names.empty()) - return first; - if (db.names.back().second.substr(0, 2) == " [") - db.names.back().second.erase(0, 1); - db.names.back().second.insert(0, " [" + typename C::String(first+1, t) + "]"); - first = t2; - } - } +const char *parse_array_type(const char *first, const char *last, C &db) { + if (first != last && *first == 'A' && first + 1 != last) { + if (first[1] == '_') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + if (db.names.back().second.substr(0, 2) == " [") + db.names.back().second.erase(0, 1); + db.names.back().second.insert(0, " []"); + first = t; + } + } else if ('1' <= first[1] && first[1] <= '9') { + const char *t = parse_number(first + 1, last); + if (t != last && *t == '_') { + const char *t2 = parse_type(t + 1, last, db); + if (t2 != t + 1) { + if (db.names.empty()) + return first; + if (db.names.back().second.substr(0, 2) == " [") + db.names.back().second.erase(0, 1); + db.names.back().second.insert( + 0, " [" + typename C::String(first + 1, t) + "]"); + first = t2; } - else - { - const char* t = parse_expression(first+1, last, db); - if (t != first+1 && t != last && *t == '_') - { - const char* t2 = parse_type(++t, last, db); - if (t2 != t) - { - if (db.names.size() < 2) - return first; - auto type = std::move(db.names.back()); - db.names.pop_back(); - auto expr = std::move(db.names.back()); - db.names.back().first = std::move(type.first); - if (type.second.substr(0, 2) == " [") - type.second.erase(0, 1); - db.names.back().second = " [" + expr.move_full() + "]" + std::move(type.second); - first = t2; - } - } + } + } else { + const char *t = parse_expression(first + 1, last, db); + if (t != first + 1 && t != last && *t == '_') { + const char *t2 = parse_type(++t, last, db); + if (t2 != t) { + if (db.names.size() < 2) + return first; + auto type = std::move(db.names.back()); + db.names.pop_back(); + auto expr = std::move(db.names.back()); + db.names.back().first = std::move(type.first); + if (type.second.substr(0, 2) == " [") + type.second.erase(0, 1); + db.names.back().second = + " [" + expr.move_full() + "]" + std::move(type.second); + first = t2; } + } } - return first; + } + return first; } -// ::= Dt E # decltype of an id-expression or class member access (C++0x) +// ::= Dt E # decltype of an id-expression or class +// member access (C++0x) // ::= DT E # decltype of an expression (C++0x) template -const char* -parse_decltype(const char* first, const char* last, C& db) -{ - if (last - first >= 4 && first[0] == 'D') - { - switch (first[1]) - { - case 't': - case 'T': - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2 && t != last && *t == 'E') - { - if (db.names.empty()) - return first; - db.names.back() = "decltype(" + db.names.back().move_full() + ")"; - first = t+1; - } - } - break; - } +const char *parse_decltype(const char *first, const char *last, C &db) { + if (last - first >= 4 && first[0] == 'D') { + switch (first[1]) { + case 't': + case 'T': { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2 && t != last && *t == 'E') { + if (db.names.empty()) + return first; + db.names.back() = "decltype(" + db.names.back().move_full() + ")"; + first = t + 1; + } + } break; } - return first; + } + return first; } // extension: @@ -1814,69 +1597,56 @@ parse_decltype(const char* first, const char* last, C& db) // ::= p # AltiVec vector pixel template -const char* -parse_vector_type(const char* first, const char* last, C& db) -{ - if (last - first > 3 && first[0] == 'D' && first[1] == 'v') - { - if ('1' <= first[2] && first[2] <= '9') - { - const char* t = parse_number(first+2, last); - if (t == last || *t != '_') - return first; - const char* num = first + 2; - size_t sz = static_cast(t - num); - if (++t != last) - { - if (*t != 'p') - { - const char* t1 = parse_type(t, last, db); - if (t1 != t) - { - if (db.names.empty()) - return first; - db.names.back().first += " vector[" + typename C::String(num, sz) + "]"; - first = t1; - } - } - else - { - ++t; - db.names.push_back("pixel vector[" + typename C::String(num, sz) + "]"); - first = t; - } - } +const char *parse_vector_type(const char *first, const char *last, C &db) { + if (last - first > 3 && first[0] == 'D' && first[1] == 'v') { + if ('1' <= first[2] && first[2] <= '9') { + const char *t = parse_number(first + 2, last); + if (t == last || *t != '_') + return first; + const char *num = first + 2; + size_t sz = static_cast(t - num); + if (++t != last) { + if (*t != 'p') { + const char *t1 = parse_type(t, last, db); + if (t1 != t) { + if (db.names.empty()) + return first; + db.names.back().first += + " vector[" + typename C::String(num, sz) + "]"; + first = t1; + } + } else { + ++t; + db.names.push_back("pixel vector[" + typename C::String(num, sz) + + "]"); + first = t; } - else - { - typename C::String num; - const char* t1 = first+2; - if (*t1 != '_') - { - const char* t = parse_expression(t1, last, db); - if (t != t1) - { - if (db.names.empty()) - return first; - num = db.names.back().move_full(); - db.names.pop_back(); - t1 = t; - } - } - if (t1 != last && *t1 == '_' && ++t1 != last) - { - const char* t = parse_type(t1, last, db); - if (t != t1) - { - if (db.names.empty()) - return first; - db.names.back().first += " vector[" + num + "]"; - first = t; - } - } + } + } else { + typename C::String num; + const char *t1 = first + 2; + if (*t1 != '_') { + const char *t = parse_expression(t1, last, db); + if (t != t1) { + if (db.names.empty()) + return first; + num = db.names.back().move_full(); + db.names.pop_back(); + t1 = t; + } + } + if (t1 != last && *t1 == '_' && ++t1 != last) { + const char *t = parse_type(t1, last, db); + if (t != t1) { + if (db.names.empty()) + return first; + db.names.back().first += " vector[" + num + "]"; + first = t; } + } } - return first; + } + return first; } // ::= @@ -1899,1026 +1669,893 @@ parse_vector_type(const char* first, const char* last, C& db) // extension := U # objc-type // extension := # starts with Dv -// ::= objcproto # k0 = 9 + + k1 -// := # PU<11+>objcproto 11objc_object 11objc_object -> id +// ::= objcproto # k0 = 9 + +// + k1 +// := # PU<11+>objcproto 11objc_object +// 11objc_object -> id template -const char* -parse_type(const char* first, const char* last, C& db) -{ - if (first != last) - { - switch (*first) - { - case 'r': - case 'V': - case 'K': - { - unsigned cv = 0; - const char* t = parse_cv_qualifiers(first, last, cv); - if (t != first) - { - bool is_function = *t == 'F'; - size_t k0 = db.names.size(); - const char* t1 = parse_type(t, last, db); - size_t k1 = db.names.size(); - if (t1 != t) - { - if (is_function) - db.subs.pop_back(); - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - { - if (is_function) - { - size_t p = db.names[k].second.size(); - if (db.names[k].second[p-2] == '&') - p -= 3; - else if (db.names[k].second.back() == '&') - p -= 2; - if (cv & 1) - { - db.names[k].second.insert(p, " const"); - p += 6; - } - if (cv & 2) - { - db.names[k].second.insert(p, " volatile"); - p += 9; - } - if (cv & 4) - db.names[k].second.insert(p, " restrict"); - } - else - { - if (cv & 1) - db.names[k].first.append(" const"); - if (cv & 2) - db.names[k].first.append(" volatile"); - if (cv & 4) - db.names[k].first.append(" restrict"); - } - db.subs.back().push_back(db.names[k]); - } - first = t1; - } - } +const char *parse_type(const char *first, const char *last, C &db) { + if (first != last) { + switch (*first) { + case 'r': + case 'V': + case 'K': { + unsigned cv = 0; + const char *t = parse_cv_qualifiers(first, last, cv); + if (t != first) { + bool is_function = *t == 'F'; + size_t k0 = db.names.size(); + const char *t1 = parse_type(t, last, db); + size_t k1 = db.names.size(); + if (t1 != t) { + if (is_function) + db.subs.pop_back(); + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) { + if (is_function) { + size_t p = db.names[k].second.size(); + if (db.names[k].second[p - 2] == '&') + p -= 3; + else if (db.names[k].second.back() == '&') + p -= 2; + if (cv & 1) { + db.names[k].second.insert(p, " const"); + p += 6; } - break; - default: - { - const char* t = parse_builtin_type(first, last, db); - if (t != first) - { - first = t; - } - else - { - switch (*first) - { - case 'A': - t = parse_array_type(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - first = t; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - } - break; - case 'C': - t = parse_type(first+1, last, db); - if (t != first+1) - { - if (db.names.empty()) - return first; - db.names.back().first.append(" complex"); - first = t; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - } - break; - case 'F': - t = parse_function_type(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - first = t; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - } - break; - case 'G': - t = parse_type(first+1, last, db); - if (t != first+1) - { - if (db.names.empty()) - return first; - db.names.back().first.append(" imaginary"); - first = t; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - } - break; - case 'M': - t = parse_pointer_to_member_type(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - first = t; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - } - break; - case 'O': - { - size_t k0 = db.names.size(); - t = parse_type(first+1, last, db); - size_t k1 = db.names.size(); - if (t != first+1) - { - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - { - if (db.names[k].second.substr(0, 2) == " [") - { - db.names[k].first += " ("; - db.names[k].second.insert(0, ")"); - } - else if (!db.names[k].second.empty() && - db.names[k].second.front() == '(') - { - db.names[k].first += "("; - db.names[k].second.insert(0, ")"); - } - db.names[k].first.append("&&"); - db.subs.back().push_back(db.names[k]); - } - first = t; - } - break; - } - case 'P': - { - size_t k0 = db.names.size(); - t = parse_type(first+1, last, db); - size_t k1 = db.names.size(); - if (t != first+1) - { - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - { - if (db.names[k].second.substr(0, 2) == " [") - { - db.names[k].first += " ("; - db.names[k].second.insert(0, ")"); - } - else if (!db.names[k].second.empty() && - db.names[k].second.front() == '(') - { - db.names[k].first += "("; - db.names[k].second.insert(0, ")"); - } - if (first[1] != 'U' || db.names[k].first.substr(0, 12) != "objc_object<") - { - db.names[k].first.append("*"); - } - else - { - db.names[k].first.replace(0, 11, "id"); - } - db.subs.back().push_back(db.names[k]); - } - first = t; - } - break; - } - case 'R': - { - size_t k0 = db.names.size(); - t = parse_type(first+1, last, db); - size_t k1 = db.names.size(); - if (t != first+1) - { - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - { - if (db.names[k].second.substr(0, 2) == " [") - { - db.names[k].first += " ("; - db.names[k].second.insert(0, ")"); - } - else if (!db.names[k].second.empty() && - db.names[k].second.front() == '(') - { - db.names[k].first += "("; - db.names[k].second.insert(0, ")"); - } - db.names[k].first.append("&"); - db.subs.back().push_back(db.names[k]); - } - first = t; - } - break; - } - case 'T': - { - size_t k0 = db.names.size(); - t = parse_template_param(first, last, db); - size_t k1 = db.names.size(); - if (t != first) - { - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - db.subs.back().push_back(db.names[k]); - if (db.try_to_parse_template_args && k1 == k0+1) - { - const char* t1 = parse_template_args(t, last, db); - if (t1 != t) - { - auto args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += std::move(args); - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - t = t1; - } - } - first = t; - } - break; - } - case 'U': - if (first+1 != last) - { - t = parse_source_name(first+1, last, db); - if (t != first+1) - { - const char* t2 = parse_type(t, last, db); - if (t2 != t) - { - if (db.names.size() < 2) - return first; - auto type = db.names.back().move_full(); - db.names.pop_back(); - if (db.names.back().first.substr(0, 9) != "objcproto") - { - db.names.back() = type + " " + db.names.back().move_full(); - } - else - { - auto proto = db.names.back().move_full(); - db.names.pop_back(); - t = parse_source_name(proto.data() + 9, proto.data() + proto.size(), db); - if (t != proto.data() + 9) - { - db.names.back() = type + "<" + db.names.back().move_full() + ">"; - } - else - { - db.names.push_back(type + " " + proto); - } - } - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t2; - } - } - } - break; - case 'S': - if (first+1 != last && first[1] == 't') - { - t = parse_name(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - } - else - { - t = parse_substitution(first, last, db); - if (t != first) - { - first = t; - // Parsed a substitution. If the substitution is a - // it might be followed by . - t = parse_template_args(first, last, db); - if (t != first) - { - if (db.names.size() < 2) - return first; - auto template_args = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first += template_args; - // Need to create substitution for - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - } - } - break; - case 'D': - if (first+1 != last) - { - switch (first[1]) - { - case 'p': - { - size_t k0 = db.names.size(); - t = parse_type(first+2, last, db); - size_t k1 = db.names.size(); - if (t != first+2) - { - db.subs.emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - db.subs.back().push_back(db.names[k]); - first = t; - return first; - } - break; - } - case 't': - case 'T': - t = parse_decltype(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - return first; - } - break; - case 'v': - t = parse_vector_type(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - return first; - } - break; - } - } - LLVM_FALLTHROUGH; - default: - // must check for builtin-types before class-enum-types to avoid - // ambiguities with operator-names - t = parse_builtin_type(first, last, db); - if (t != first) - { - first = t; - } - else - { - t = parse_name(first, last, db); - if (t != first) - { - if (db.names.empty()) - return first; - db.subs.push_back(typename C::sub_type(1, db.names.back(), db.names.get_allocator())); - first = t; - } - } - break; - } + if (cv & 2) { + db.names[k].second.insert(p, " volatile"); + p += 9; } - break; - } + if (cv & 4) + db.names[k].second.insert(p, " restrict"); + } else { + if (cv & 1) + db.names[k].first.append(" const"); + if (cv & 2) + db.names[k].first.append(" volatile"); + if (cv & 4) + db.names[k].first.append(" restrict"); + } + db.subs.back().push_back(db.names[k]); + } + first = t1; } - } - return first; -} - -// -// ::= aa # && -// ::= ad # & (unary) -// ::= an # & -// ::= aN # &= -// ::= aS # = -// ::= cl # () -// ::= cm # , -// ::= co # ~ -// ::= cv # (cast) -// ::= da # delete[] -// ::= de # * (unary) -// ::= dl # delete -// ::= dv # / -// ::= dV # /= -// ::= eo # ^ -// ::= eO # ^= -// ::= eq # == -// ::= ge # >= -// ::= gt # > -// ::= ix # [] -// ::= le # <= -// ::= li # operator "" -// ::= ls # << -// ::= lS # <<= -// ::= lt # < -// ::= mi # - -// ::= mI # -= -// ::= ml # * -// ::= mL # *= -// ::= mm # -- (postfix in context) -// ::= na # new[] -// ::= ne # != -// ::= ng # - (unary) -// ::= nt # ! -// ::= nw # new -// ::= oo # || -// ::= or # | -// ::= oR # |= -// ::= pm # ->* -// ::= pl # + -// ::= pL # += -// ::= pp # ++ (postfix in context) -// ::= ps # + (unary) -// ::= pt # -> -// ::= qu # ? -// ::= rm # % -// ::= rM # %= -// ::= rs # >> -// ::= rS # >>= -// ::= v # vendor extended operator - -template -const char* -parse_operator_name(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - switch (first[0]) - { - case 'a': - switch (first[1]) - { - case 'a': - db.names.push_back("operator&&"); - first += 2; - break; - case 'd': - case 'n': - db.names.push_back("operator&"); - first += 2; - break; - case 'N': - db.names.push_back("operator&="); - first += 2; - break; - case 'S': - db.names.push_back("operator="); - first += 2; - break; - } - break; - case 'c': - switch (first[1]) - { - case 'l': - db.names.push_back("operator()"); - first += 2; - break; - case 'm': - db.names.push_back("operator,"); - first += 2; - break; - case 'o': - db.names.push_back("operator~"); - first += 2; - break; - case 'v': - { - bool try_to_parse_template_args = db.try_to_parse_template_args; - db.try_to_parse_template_args = false; - const char* t = parse_type(first+2, last, db); - db.try_to_parse_template_args = try_to_parse_template_args; - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "operator "); - db.parsed_ctor_dtor_cv = true; - first = t; - } - } - break; - } - break; - case 'd': - switch (first[1]) - { - case 'a': - db.names.push_back("operator delete[]"); - first += 2; - break; - case 'e': - db.names.push_back("operator*"); - first += 2; - break; - case 'l': - db.names.push_back("operator delete"); - first += 2; - break; - case 'v': - db.names.push_back("operator/"); - first += 2; - break; - case 'V': - db.names.push_back("operator/="); - first += 2; - break; + } + } break; + default: { + const char *t = parse_builtin_type(first, last, db); + if (t != first) { + first = t; + } else { + switch (*first) { + case 'A': + t = parse_array_type(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + first = t; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + } + break; + case 'C': + t = parse_type(first + 1, last, db); + if (t != first + 1) { + if (db.names.empty()) + return first; + db.names.back().first.append(" complex"); + first = t; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + } + break; + case 'F': + t = parse_function_type(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + first = t; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + } + break; + case 'G': + t = parse_type(first + 1, last, db); + if (t != first + 1) { + if (db.names.empty()) + return first; + db.names.back().first.append(" imaginary"); + first = t; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + } + break; + case 'M': + t = parse_pointer_to_member_type(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + first = t; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + } + break; + case 'O': { + size_t k0 = db.names.size(); + t = parse_type(first + 1, last, db); + size_t k1 = db.names.size(); + if (t != first + 1) { + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) { + if (db.names[k].second.substr(0, 2) == " [") { + db.names[k].first += " ("; + db.names[k].second.insert(0, ")"); + } else if (!db.names[k].second.empty() && + db.names[k].second.front() == '(') { + db.names[k].first += "("; + db.names[k].second.insert(0, ")"); + } + db.names[k].first.append("&&"); + db.subs.back().push_back(db.names[k]); } - break; - case 'e': - switch (first[1]) - { - case 'o': - db.names.push_back("operator^"); - first += 2; - break; - case 'O': - db.names.push_back("operator^="); - first += 2; - break; - case 'q': - db.names.push_back("operator=="); - first += 2; - break; + first = t; + } + break; + } + case 'P': { + size_t k0 = db.names.size(); + t = parse_type(first + 1, last, db); + size_t k1 = db.names.size(); + if (t != first + 1) { + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) { + if (db.names[k].second.substr(0, 2) == " [") { + db.names[k].first += " ("; + db.names[k].second.insert(0, ")"); + } else if (!db.names[k].second.empty() && + db.names[k].second.front() == '(') { + db.names[k].first += "("; + db.names[k].second.insert(0, ")"); + } + if (first[1] != 'U' || + db.names[k].first.substr(0, 12) != "objc_object<") { + db.names[k].first.append("*"); + } else { + db.names[k].first.replace(0, 11, "id"); + } + db.subs.back().push_back(db.names[k]); } - break; - case 'g': - switch (first[1]) - { - case 'e': - db.names.push_back("operator>="); - first += 2; - break; - case 't': - db.names.push_back("operator>"); - first += 2; - break; + first = t; + } + break; + } + case 'R': { + size_t k0 = db.names.size(); + t = parse_type(first + 1, last, db); + size_t k1 = db.names.size(); + if (t != first + 1) { + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) { + if (db.names[k].second.substr(0, 2) == " [") { + db.names[k].first += " ("; + db.names[k].second.insert(0, ")"); + } else if (!db.names[k].second.empty() && + db.names[k].second.front() == '(') { + db.names[k].first += "("; + db.names[k].second.insert(0, ")"); + } + db.names[k].first.append("&"); + db.subs.back().push_back(db.names[k]); } - break; - case 'i': - if (first[1] == 'x') - { - db.names.push_back("operator[]"); - first += 2; + first = t; + } + break; + } + case 'T': { + size_t k0 = db.names.size(); + t = parse_template_param(first, last, db); + size_t k1 = db.names.size(); + if (t != first) { + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) + db.subs.back().push_back(db.names[k]); + if (db.try_to_parse_template_args && k1 == k0 + 1) { + const char *t1 = parse_template_args(t, last, db); + if (t1 != t) { + auto args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += std::move(args); + db.subs.push_back(typename C::sub_type( + 1, db.names.back(), db.names.get_allocator())); + t = t1; + } } - break; - case 'l': - switch (first[1]) - { - case 'e': - db.names.push_back("operator<="); - first += 2; - break; - case 'i': - { - const char* t = parse_source_name(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "operator\"\" "); - first = t; - } + first = t; + } + break; + } + case 'U': + if (first + 1 != last) { + t = parse_source_name(first + 1, last, db); + if (t != first + 1) { + const char *t2 = parse_type(t, last, db); + if (t2 != t) { + if (db.names.size() < 2) + return first; + auto type = db.names.back().move_full(); + db.names.pop_back(); + if (db.names.back().first.substr(0, 9) != "objcproto") { + db.names.back() = type + " " + db.names.back().move_full(); + } else { + auto proto = db.names.back().move_full(); + db.names.pop_back(); + t = parse_source_name(proto.data() + 9, + proto.data() + proto.size(), db); + if (t != proto.data() + 9) { + db.names.back() = + type + "<" + db.names.back().move_full() + ">"; + } else { + db.names.push_back(type + " " + proto); + } } - break; - case 's': - db.names.push_back("operator<<"); - first += 2; - break; - case 'S': - db.names.push_back("operator<<="); - first += 2; - break; - case 't': - db.names.push_back("operator<"); - first += 2; - break; + db.subs.push_back(typename C::sub_type( + 1, db.names.back(), db.names.get_allocator())); + first = t2; + } } - break; - case 'm': - switch (first[1]) - { - case 'i': - db.names.push_back("operator-"); - first += 2; - break; - case 'I': - db.names.push_back("operator-="); - first += 2; - break; - case 'l': - db.names.push_back("operator*"); - first += 2; - break; - case 'L': - db.names.push_back("operator*="); - first += 2; - break; - case 'm': - db.names.push_back("operator--"); - first += 2; - break; + } + break; + case 'S': + if (first + 1 != last && first[1] == 't') { + t = parse_name(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + first = t; } - break; - case 'n': - switch (first[1]) - { - case 'a': - db.names.push_back("operator new[]"); - first += 2; - break; - case 'e': - db.names.push_back("operator!="); - first += 2; - break; - case 'g': - db.names.push_back("operator-"); - first += 2; - break; - case 't': - db.names.push_back("operator!"); - first += 2; - break; - case 'w': - db.names.push_back("operator new"); - first += 2; - break; + } else { + t = parse_substitution(first, last, db); + if (t != first) { + first = t; + // Parsed a substitution. If the substitution is a + // it might be followed by . + t = parse_template_args(first, last, db); + if (t != first) { + if (db.names.size() < 2) + return first; + auto template_args = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first += template_args; + // Need to create substitution for + // + db.subs.push_back(typename C::sub_type( + 1, db.names.back(), db.names.get_allocator())); + first = t; + } } - break; - case 'o': - switch (first[1]) - { - case 'o': - db.names.push_back("operator||"); - first += 2; - break; - case 'r': - db.names.push_back("operator|"); - first += 2; - break; - case 'R': - db.names.push_back("operator|="); - first += 2; - break; + } + break; + case 'D': + if (first + 1 != last) { + switch (first[1]) { + case 'p': { + size_t k0 = db.names.size(); + t = parse_type(first + 2, last, db); + size_t k1 = db.names.size(); + if (t != first + 2) { + db.subs.emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) + db.subs.back().push_back(db.names[k]); + first = t; + return first; + } + break; } - break; - case 'p': - switch (first[1]) - { - case 'm': - db.names.push_back("operator->*"); - first += 2; - break; - case 'l': - db.names.push_back("operator+"); - first += 2; - break; - case 'L': - db.names.push_back("operator+="); - first += 2; - break; - case 'p': - db.names.push_back("operator++"); - first += 2; - break; - case 's': - db.names.push_back("operator+"); - first += 2; - break; case 't': - db.names.push_back("operator->"); - first += 2; - break; - } - break; - case 'q': - if (first[1] == 'u') - { - db.names.push_back("operator?"); - first += 2; - } - break; - case 'r': - switch (first[1]) - { - case 'm': - db.names.push_back("operator%"); - first += 2; - break; - case 'M': - db.names.push_back("operator%="); - first += 2; - break; - case 's': - db.names.push_back("operator>>"); - first += 2; - break; - case 'S': - db.names.push_back("operator>>="); - first += 2; - break; + case 'T': + t = parse_decltype(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.subs.push_back(typename C::sub_type( + 1, db.names.back(), db.names.get_allocator())); + first = t; + return first; + } + break; + case 'v': + t = parse_vector_type(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.subs.push_back(typename C::sub_type( + 1, db.names.back(), db.names.get_allocator())); + first = t; + return first; + } + break; } - break; - case 'v': - if (std::isdigit(first[1])) - { - const char* t = parse_source_name(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "operator "); - first = t; - } + } + LLVM_FALLTHROUGH; + default: + // must check for builtin-types before class-enum-types to avoid + // ambiguities with operator-names + t = parse_builtin_type(first, last, db); + if (t != first) { + first = t; + } else { + t = parse_name(first, last, db); + if (t != first) { + if (db.names.empty()) + return first; + db.subs.push_back(typename C::sub_type(1, db.names.back(), + db.names.get_allocator())); + first = t; } - break; + } + break; } + } + break; + } } - return first; + } + return first; } +// +// ::= aa # && +// ::= ad # & (unary) +// ::= an # & +// ::= aN # &= +// ::= aS # = +// ::= cl # () +// ::= cm # , +// ::= co # ~ +// ::= cv # (cast) +// ::= da # delete[] +// ::= de # * (unary) +// ::= dl # delete +// ::= dv # / +// ::= dV # /= +// ::= eo # ^ +// ::= eO # ^= +// ::= eq # == +// ::= ge # >= +// ::= gt # > +// ::= ix # [] +// ::= le # <= +// ::= li # operator "" +// ::= ls # << +// ::= lS # <<= +// ::= lt # < +// ::= mi # - +// ::= mI # -= +// ::= ml # * +// ::= mL # *= +// ::= mm # -- (postfix in context) +// ::= na # new[] +// ::= ne # != +// ::= ng # - (unary) +// ::= nt # ! +// ::= nw # new +// ::= oo # || +// ::= or # | +// ::= oR # |= +// ::= pm # ->* +// ::= pl # + +// ::= pL # += +// ::= pp # ++ (postfix in context) +// ::= ps # + (unary) +// ::= pt # -> +// ::= qu # ? +// ::= rm # % +// ::= rM # %= +// ::= rs # >> +// ::= rS # >>= +// ::= v # vendor extended +// operator + template -const char* -parse_integer_literal(const char* first, const char* last, const typename C::String& lit, C& db) -{ - const char* t = parse_number(first, last); - if (t != first && t != last && *t == 'E') - { - if (lit.size() > 3) - db.names.push_back("(" + lit + ")"); - else - db.names.emplace_back(); - if (*first == 'n') - { - db.names.back().first += '-'; - ++first; +const char *parse_operator_name(const char *first, const char *last, C &db) { + if (last - first >= 2) { + switch (first[0]) { + case 'a': + switch (first[1]) { + case 'a': + db.names.push_back("operator&&"); + first += 2; + break; + case 'd': + case 'n': + db.names.push_back("operator&"); + first += 2; + break; + case 'N': + db.names.push_back("operator&="); + first += 2; + break; + case 'S': + db.names.push_back("operator="); + first += 2; + break; + } + break; + case 'c': + switch (first[1]) { + case 'l': + db.names.push_back("operator()"); + first += 2; + break; + case 'm': + db.names.push_back("operator,"); + first += 2; + break; + case 'o': + db.names.push_back("operator~"); + first += 2; + break; + case 'v': { + bool try_to_parse_template_args = db.try_to_parse_template_args; + db.try_to_parse_template_args = false; + const char *t = parse_type(first + 2, last, db); + db.try_to_parse_template_args = try_to_parse_template_args; + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "operator "); + db.parsed_ctor_dtor_cv = true; + first = t; } - db.names.back().first.append(first, t); - if (lit.size() <= 3) - db.names.back().first += lit; - first = t+1; + } break; + } + break; + case 'd': + switch (first[1]) { + case 'a': + db.names.push_back("operator delete[]"); + first += 2; + break; + case 'e': + db.names.push_back("operator*"); + first += 2; + break; + case 'l': + db.names.push_back("operator delete"); + first += 2; + break; + case 'v': + db.names.push_back("operator/"); + first += 2; + break; + case 'V': + db.names.push_back("operator/="); + first += 2; + break; + } + break; + case 'e': + switch (first[1]) { + case 'o': + db.names.push_back("operator^"); + first += 2; + break; + case 'O': + db.names.push_back("operator^="); + first += 2; + break; + case 'q': + db.names.push_back("operator=="); + first += 2; + break; + } + break; + case 'g': + switch (first[1]) { + case 'e': + db.names.push_back("operator>="); + first += 2; + break; + case 't': + db.names.push_back("operator>"); + first += 2; + break; + } + break; + case 'i': + if (first[1] == 'x') { + db.names.push_back("operator[]"); + first += 2; + } + break; + case 'l': + switch (first[1]) { + case 'e': + db.names.push_back("operator<="); + first += 2; + break; + case 'i': { + const char *t = parse_source_name(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "operator\"\" "); + first = t; + } + } break; + case 's': + db.names.push_back("operator<<"); + first += 2; + break; + case 'S': + db.names.push_back("operator<<="); + first += 2; + break; + case 't': + db.names.push_back("operator<"); + first += 2; + break; + } + break; + case 'm': + switch (first[1]) { + case 'i': + db.names.push_back("operator-"); + first += 2; + break; + case 'I': + db.names.push_back("operator-="); + first += 2; + break; + case 'l': + db.names.push_back("operator*"); + first += 2; + break; + case 'L': + db.names.push_back("operator*="); + first += 2; + break; + case 'm': + db.names.push_back("operator--"); + first += 2; + break; + } + break; + case 'n': + switch (first[1]) { + case 'a': + db.names.push_back("operator new[]"); + first += 2; + break; + case 'e': + db.names.push_back("operator!="); + first += 2; + break; + case 'g': + db.names.push_back("operator-"); + first += 2; + break; + case 't': + db.names.push_back("operator!"); + first += 2; + break; + case 'w': + db.names.push_back("operator new"); + first += 2; + break; + } + break; + case 'o': + switch (first[1]) { + case 'o': + db.names.push_back("operator||"); + first += 2; + break; + case 'r': + db.names.push_back("operator|"); + first += 2; + break; + case 'R': + db.names.push_back("operator|="); + first += 2; + break; + } + break; + case 'p': + switch (first[1]) { + case 'm': + db.names.push_back("operator->*"); + first += 2; + break; + case 'l': + db.names.push_back("operator+"); + first += 2; + break; + case 'L': + db.names.push_back("operator+="); + first += 2; + break; + case 'p': + db.names.push_back("operator++"); + first += 2; + break; + case 's': + db.names.push_back("operator+"); + first += 2; + break; + case 't': + db.names.push_back("operator->"); + first += 2; + break; + } + break; + case 'q': + if (first[1] == 'u') { + db.names.push_back("operator?"); + first += 2; + } + break; + case 'r': + switch (first[1]) { + case 'm': + db.names.push_back("operator%"); + first += 2; + break; + case 'M': + db.names.push_back("operator%="); + first += 2; + break; + case 's': + db.names.push_back("operator>>"); + first += 2; + break; + case 'S': + db.names.push_back("operator>>="); + first += 2; + break; + } + break; + case 'v': + if (std::isdigit(first[1])) { + const char *t = parse_source_name(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "operator "); + first = t; + } + } + break; } - return first; + } + return first; } -// ::= L E # integer literal -// ::= L E # floating literal -// ::= L E # string literal -// ::= L E # nullptr literal (i.e., "LDnE") -// ::= L _ E # complex floating point literal (C 2000) -// ::= L E # external name - template -const char* -parse_expr_primary(const char* first, const char* last, C& db) -{ - if (last - first >= 4 && *first == 'L') - { - switch (first[1]) - { - case 'w': - { - const char* t = parse_integer_literal(first+2, last, "wchar_t", db); - if (t != first+2) - first = t; - } - break; - case 'b': - if (first[3] == 'E') - { - switch (first[2]) - { - case '0': - db.names.push_back("false"); - first += 4; - break; - case '1': - db.names.push_back("true"); - first += 4; - break; - } - } - break; - case 'c': - { - const char* t = parse_integer_literal(first+2, last, "char", db); - if (t != first+2) - first = t; - } - break; - case 'a': - { - const char* t = parse_integer_literal(first+2, last, "signed char", db); - if (t != first+2) - first = t; - } - break; - case 'h': - { - const char* t = parse_integer_literal(first+2, last, "unsigned char", db); - if (t != first+2) - first = t; - } - break; - case 's': - { - const char* t = parse_integer_literal(first+2, last, "short", db); - if (t != first+2) - first = t; - } - break; - case 't': - { - const char* t = parse_integer_literal(first+2, last, "unsigned short", db); - if (t != first+2) - first = t; - } - break; - case 'i': - { - const char* t = parse_integer_literal(first+2, last, "", db); - if (t != first+2) - first = t; - } - break; - case 'j': - { - const char* t = parse_integer_literal(first+2, last, "u", db); - if (t != first+2) - first = t; - } - break; - case 'l': - { - const char* t = parse_integer_literal(first+2, last, "l", db); - if (t != first+2) - first = t; - } - break; - case 'm': - { - const char* t = parse_integer_literal(first+2, last, "ul", db); - if (t != first+2) - first = t; - } - break; - case 'x': - { - const char* t = parse_integer_literal(first+2, last, "ll", db); - if (t != first+2) - first = t; - } - break; - case 'y': - { - const char* t = parse_integer_literal(first+2, last, "ull", db); - if (t != first+2) - first = t; - } - break; - case 'n': - { - const char* t = parse_integer_literal(first+2, last, "__int128", db); - if (t != first+2) - first = t; - } - break; - case 'o': - { - const char* t = parse_integer_literal(first+2, last, "unsigned __int128", db); - if (t != first+2) - first = t; - } - break; - case 'f': - { - const char* t = parse_floating_number(first+2, last, db); - if (t != first+2) - first = t; - } - break; - case 'd': - { - const char* t = parse_floating_number(first+2, last, db); - if (t != first+2) - first = t; - } - break; - case 'e': - { - const char* t = parse_floating_number(first+2, last, db); - if (t != first+2) - first = t; - } - break; - case '_': - if (first[2] == 'Z') - { - const char* t = parse_encoding(first+3, last, db); - if (t != first+3 && t != last && *t == 'E') - first = t+1; - } - break; - case 'T': - // Invalid mangled name per - // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html - break; - default: - { - // might be named type - const char* t = parse_type(first+1, last, db); - if (t != first+1 && t != last) - { - if (*t != 'E') - { - const char* n = t; - for (; n != last && isdigit(*n); ++n) - ; - if (n != t && n != last && *n == 'E') - { - if (db.names.empty()) - return first; - db.names.back() = "(" + db.names.back().move_full() + ")" + typename C::String(t, n); - first = n+1; - break; - } - } - else - { - first = t+1; - break; - } - } - } - } +const char *parse_integer_literal(const char *first, const char *last, + const typename C::String &lit, C &db) { + const char *t = parse_number(first, last); + if (t != first && t != last && *t == 'E') { + if (lit.size() > 3) + db.names.push_back("(" + lit + ")"); + else + db.names.emplace_back(); + if (*first == 'n') { + db.names.back().first += '-'; + ++first; } - return first; + db.names.back().first.append(first, t); + if (lit.size() <= 3) + db.names.back().first += lit; + first = t + 1; + } + return first; } -template -String -base_name(String& s) -{ - if (s.empty()) - return s; - if (s == "std::string") - { - s = "std::basic_string, std::allocator >"; - return "basic_string"; - } - if (s == "std::istream") - { - s = "std::basic_istream >"; - return "basic_istream"; - } - if (s == "std::ostream") - { - s = "std::basic_ostream >"; - return "basic_ostream"; +// ::= L E # +// integer literal +// ::= L E # +// floating literal +// ::= L E # +// string literal +// ::= L E # +// nullptr literal (i.e., "LDnE") +// ::= L _ E # +// complex floating point literal (C 2000) +// ::= L E # +// external name + +template +const char *parse_expr_primary(const char *first, const char *last, C &db) { + if (last - first >= 4 && *first == 'L') { + switch (first[1]) { + case 'w': { + const char *t = parse_integer_literal(first + 2, last, "wchar_t", db); + if (t != first + 2) + first = t; + } break; + case 'b': + if (first[3] == 'E') { + switch (first[2]) { + case '0': + db.names.push_back("false"); + first += 4; + break; + case '1': + db.names.push_back("true"); + first += 4; + break; + } + } + break; + case 'c': { + const char *t = parse_integer_literal(first + 2, last, "char", db); + if (t != first + 2) + first = t; + } break; + case 'a': { + const char *t = parse_integer_literal(first + 2, last, "signed char", db); + if (t != first + 2) + first = t; + } break; + case 'h': { + const char *t = + parse_integer_literal(first + 2, last, "unsigned char", db); + if (t != first + 2) + first = t; + } break; + case 's': { + const char *t = parse_integer_literal(first + 2, last, "short", db); + if (t != first + 2) + first = t; + } break; + case 't': { + const char *t = + parse_integer_literal(first + 2, last, "unsigned short", db); + if (t != first + 2) + first = t; + } break; + case 'i': { + const char *t = parse_integer_literal(first + 2, last, "", db); + if (t != first + 2) + first = t; + } break; + case 'j': { + const char *t = parse_integer_literal(first + 2, last, "u", db); + if (t != first + 2) + first = t; + } break; + case 'l': { + const char *t = parse_integer_literal(first + 2, last, "l", db); + if (t != first + 2) + first = t; + } break; + case 'm': { + const char *t = parse_integer_literal(first + 2, last, "ul", db); + if (t != first + 2) + first = t; + } break; + case 'x': { + const char *t = parse_integer_literal(first + 2, last, "ll", db); + if (t != first + 2) + first = t; + } break; + case 'y': { + const char *t = parse_integer_literal(first + 2, last, "ull", db); + if (t != first + 2) + first = t; + } break; + case 'n': { + const char *t = parse_integer_literal(first + 2, last, "__int128", db); + if (t != first + 2) + first = t; + } break; + case 'o': { + const char *t = + parse_integer_literal(first + 2, last, "unsigned __int128", db); + if (t != first + 2) + first = t; + } break; + case 'f': { + const char *t = parse_floating_number(first + 2, last, db); + if (t != first + 2) + first = t; + } break; + case 'd': { + const char *t = parse_floating_number(first + 2, last, db); + if (t != first + 2) + first = t; + } break; + case 'e': { + const char *t = parse_floating_number(first + 2, last, db); + if (t != first + 2) + first = t; + } break; + case '_': + if (first[2] == 'Z') { + const char *t = parse_encoding(first + 3, last, db); + if (t != first + 3 && t != last && *t == 'E') + first = t + 1; + } + break; + case 'T': + // Invalid mangled name per + // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html + break; + default: { + // might be named type + const char *t = parse_type(first + 1, last, db); + if (t != first + 1 && t != last) { + if (*t != 'E') { + const char *n = t; + for (; n != last && isdigit(*n); ++n) + ; + if (n != t && n != last && *n == 'E') { + if (db.names.empty()) + return first; + db.names.back() = "(" + db.names.back().move_full() + ")" + + typename C::String(t, n); + first = n + 1; + break; + } + } else { + first = t + 1; + break; + } + } } - if (s == "std::iostream") - { - s = "std::basic_iostream >"; - return "basic_iostream"; } - const char* const pf = s.data(); - const char* pe = pf + s.size(); - if (pe[-1] == '>') - { - unsigned c = 1; - while (true) - { - if (--pe == pf) - return String(); - if (pe[-1] == '<') - { - if (--c == 0) - { - --pe; - break; - } - } - else if (pe[-1] == '>') - ++c; + } + return first; +} + +template String base_name(String &s) { + if (s.empty()) + return s; + if (s == "std::string") { + s = "std::basic_string, std::allocator " + ">"; + return "basic_string"; + } + if (s == "std::istream") { + s = "std::basic_istream >"; + return "basic_istream"; + } + if (s == "std::ostream") { + s = "std::basic_ostream >"; + return "basic_ostream"; + } + if (s == "std::iostream") { + s = "std::basic_iostream >"; + return "basic_iostream"; + } + const char *const pf = s.data(); + const char *pe = pf + s.size(); + if (pe[-1] == '>') { + unsigned c = 1; + while (true) { + if (--pe == pf) + return String(); + if (pe[-1] == '<') { + if (--c == 0) { + --pe; + break; } + } else if (pe[-1] == '>') + ++c; } - const char* p0 = pe - 1; - for (; p0 != pf; --p0) - { - if (*p0 == ':') - { - ++p0; - break; - } + } + const char *p0 = pe - 1; + for (; p0 != pf; --p0) { + if (*p0 == ':') { + ++p0; + break; } - return String(p0, pe); + } + return String(p0, pe); } // ::= C1 # complete object constructor @@ -2931,209 +2568,180 @@ base_name(String& s) // extension ::= D5 # ? template -const char* -parse_ctor_dtor_name(const char* first, const char* last, C& db) -{ - if (last-first >= 2 && !db.names.empty()) - { - switch (first[0]) - { - case 'C': - switch (first[1]) - { - case '1': - case '2': - case '3': - case '5': - if (db.names.empty()) - return first; - db.names.push_back(base_name(db.names.back().first)); - first += 2; - db.parsed_ctor_dtor_cv = true; - break; - } - break; - case 'D': - switch (first[1]) - { - case '0': - case '1': - case '2': - case '5': - if (db.names.empty()) - return first; - db.names.push_back("~" + base_name(db.names.back().first)); - first += 2; - db.parsed_ctor_dtor_cv = true; - break; - } - break; - } +const char *parse_ctor_dtor_name(const char *first, const char *last, C &db) { + if (last - first >= 2 && !db.names.empty()) { + switch (first[0]) { + case 'C': + switch (first[1]) { + case '1': + case '2': + case '3': + case '5': + if (db.names.empty()) + return first; + db.names.push_back(base_name(db.names.back().first)); + first += 2; + db.parsed_ctor_dtor_cv = true; + break; + } + break; + case 'D': + switch (first[1]) { + case '0': + case '1': + case '2': + case '5': + if (db.names.empty()) + return first; + db.names.push_back("~" + base_name(db.names.back().first)); + first += 2; + db.parsed_ctor_dtor_cv = true; + break; + } + break; } - return first; + } + return first; } // ::= Ut [ ] _ // ::= -// -// ::= Ul E [ ] _ -// -// ::= + # Parameter types or "v" if the lambda has no parameters +// +// ::= Ul E [ ] _ +// +// ::= + # Parameter types or "v" if the lambda +// has no parameters template -const char* -parse_unnamed_type_name(const char* first, const char* last, C& db) -{ - if (last - first > 2 && first[0] == 'U') - { - char type = first[1]; - switch (type) - { - case 't': - { - db.names.push_back(typename C::String("'unnamed")); - const char* t0 = first+2; - if (t0 == last) - { - db.names.pop_back(); - return first; - } - if (std::isdigit(*t0)) - { - const char* t1 = t0 + 1; - while (t1 != last && std::isdigit(*t1)) - ++t1; - db.names.back().first.append(t0, t1); - t0 = t1; - } - db.names.back().first.push_back('\''); - if (t0 == last || *t0 != '_') - { - db.names.pop_back(); - return first; - } - first = t0 + 1; - } +const char *parse_unnamed_type_name(const char *first, const char *last, + C &db) { + if (last - first > 2 && first[0] == 'U') { + char type = first[1]; + switch (type) { + case 't': { + db.names.push_back(typename C::String("'unnamed")); + const char *t0 = first + 2; + if (t0 == last) { + db.names.pop_back(); + return first; + } + if (std::isdigit(*t0)) { + const char *t1 = t0 + 1; + while (t1 != last && std::isdigit(*t1)) + ++t1; + db.names.back().first.append(t0, t1); + t0 = t1; + } + db.names.back().first.push_back('\''); + if (t0 == last || *t0 != '_') { + db.names.pop_back(); + return first; + } + first = t0 + 1; + } break; + case 'l': { + db.names.push_back(typename C::String("'lambda'(")); + const char *t0 = first + 2; + if (first[2] == 'v') { + db.names.back().first += ')'; + ++t0; + } else { + const char *t1 = parse_type(t0, last, db); + if (t1 == t0) { + db.names.pop_back(); + return first; + } + if (db.names.size() < 2) + return first; + auto tmp = db.names.back().move_full(); + db.names.pop_back(); + db.names.back().first.append(tmp); + t0 = t1; + while (true) { + t1 = parse_type(t0, last, db); + if (t1 == t0) break; - case 'l': - { - db.names.push_back(typename C::String("'lambda'(")); - const char* t0 = first+2; - if (first[2] == 'v') - { - db.names.back().first += ')'; - ++t0; - } - else - { - const char* t1 = parse_type(t0, last, db); - if (t1 == t0) - { - db.names.pop_back(); - return first; - } - if (db.names.size() < 2) - return first; - auto tmp = db.names.back().move_full(); - db.names.pop_back(); - db.names.back().first.append(tmp); - t0 = t1; - while (true) - { - t1 = parse_type(t0, last, db); - if (t1 == t0) - break; - if (db.names.size() < 2) - return first; - tmp = db.names.back().move_full(); - db.names.pop_back(); - if (!tmp.empty()) - { - db.names.back().first.append(", "); - db.names.back().first.append(tmp); - } - t0 = t1; - } - db.names.back().first.append(")"); - } - if (t0 == last || *t0 != 'E') - { - db.names.pop_back(); - return first; - } - ++t0; - if (t0 == last) - { - db.names.pop_back(); - return first; - } - if (std::isdigit(*t0)) - { - const char* t1 = t0 + 1; - while (t1 != last && std::isdigit(*t1)) - ++t1; - db.names.back().first.insert(db.names.back().first.begin()+7, t0, t1); - t0 = t1; - } - if (t0 == last || *t0 != '_') - { - db.names.pop_back(); - return first; - } - first = t0 + 1; + if (db.names.size() < 2) + return first; + tmp = db.names.back().move_full(); + db.names.pop_back(); + if (!tmp.empty()) { + db.names.back().first.append(", "); + db.names.back().first.append(tmp); } - break; + t0 = t1; } + db.names.back().first.append(")"); + } + if (t0 == last || *t0 != 'E') { + db.names.pop_back(); + return first; + } + ++t0; + if (t0 == last) { + db.names.pop_back(); + return first; + } + if (std::isdigit(*t0)) { + const char *t1 = t0 + 1; + while (t1 != last && std::isdigit(*t1)) + ++t1; + db.names.back().first.insert(db.names.back().first.begin() + 7, t0, t1); + t0 = t1; + } + if (t0 == last || *t0 != '_') { + db.names.pop_back(); + return first; + } + first = t0 + 1; + } break; } - return first; + } + return first; } // ::= // ::= -// ::= +// ::= // ::= template -const char* -parse_unqualified_name(const char* first, const char* last, C& db) -{ - if (first != last) - { - const char* t; - switch (*first) - { - case 'C': - case 'D': - t = parse_ctor_dtor_name(first, last, db); - if (t != first) - first = t; - break; - case 'U': - t = parse_unnamed_type_name(first, last, db); - if (t != first) - first = t; - break; - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = parse_source_name(first, last, db); - if (t != first) - first = t; - break; - default: - t = parse_operator_name(first, last, db); - if (t != first) - first = t; - break; - }; - } - return first; +const char *parse_unqualified_name(const char *first, const char *last, C &db) { + if (first != last) { + const char *t; + switch (*first) { + case 'C': + case 'D': + t = parse_ctor_dtor_name(first, last, db); + if (t != first) + first = t; + break; + case 'U': + t = parse_unnamed_type_name(first, last, db); + if (t != first) + first = t; + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + t = parse_source_name(first, last, db); + if (t != first) + first = t; + break; + default: + t = parse_operator_name(first, last, db); + if (t != first) + first = t; + break; + }; + } + return first; } // ::= @@ -3141,775 +2749,743 @@ parse_unqualified_name(const char* first, const char* last, C& db) // extension ::= StL template -const char* -parse_unscoped_name(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - const char* t0 = first; - bool St = false; - if (first[0] == 'S' && first[1] == 't') - { - t0 += 2; - St = true; - if (t0 != last && *t0 == 'L') - ++t0; - } - const char* t1 = parse_unqualified_name(t0, last, db); - if (t1 != t0) - { - if (St) - { - if (db.names.empty()) - return first; - db.names.back().first.insert(0, "std::"); - } - first = t1; - } +const char *parse_unscoped_name(const char *first, const char *last, C &db) { + if (last - first >= 2) { + const char *t0 = first; + bool St = false; + if (first[0] == 'S' && first[1] == 't') { + t0 += 2; + St = true; + if (t0 != last && *t0 == 'L') + ++t0; + } + const char *t1 = parse_unqualified_name(t0, last, db); + if (t1 != t0) { + if (St) { + if (db.names.empty()) + return first; + db.names.back().first.insert(0, "std::"); + } + first = t1; } - return first; + } + return first; } // at # alignof (a type) template -const char* -parse_alignof_type(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'a' && first[1] == 't') - { - const char* t = parse_type(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first = "alignof (" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_alignof_type(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'a' && first[1] == 't') { + const char *t = parse_type(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back().first = "alignof (" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } -// az # alignof (a expression) +// az # alignof (a +// expression) template -const char* -parse_alignof_expr(const char* first, const char* last, C& db) -{ - if (last - first >= 3 && first[0] == 'a' && first[1] == 'z') - { - const char* t = parse_expression(first+2, last, db); - if (t != first+2) - { - if (db.names.empty()) - return first; - db.names.back().first = "alignof (" + db.names.back().move_full() + ")"; - first = t; - } +const char *parse_alignof_expr(const char *first, const char *last, C &db) { + if (last - first >= 3 && first[0] == 'a' && first[1] == 'z') { + const char *t = parse_expression(first + 2, last, db); + if (t != first + 2) { + if (db.names.empty()) + return first; + db.names.back().first = "alignof (" + db.names.back().move_full() + ")"; + first = t; } - return first; + } + return first; } template -const char* -parse_noexcept_expression(const char* first, const char* last, C& db) -{ - const char* t1 = parse_expression(first, last, db); - if (t1 != first) - { - if (db.names.empty()) - return first; - db.names.back().first = "noexcept (" + db.names.back().move_full() + ")"; - first = t1; - } - return first; +const char *parse_noexcept_expression(const char *first, const char *last, + C &db) { + const char *t1 = parse_expression(first, last, db); + if (t1 != first) { + if (db.names.empty()) + return first; + db.names.back().first = "noexcept (" + db.names.back().move_full() + ")"; + first = t1; + } + return first; } template -const char* -parse_prefix_expression(const char* first, const char* last, const typename C::String& op, C& db) -{ - const char* t1 = parse_expression(first, last, db); - if (t1 != first) - { - if (db.names.empty()) - return first; - db.names.back().first = op + "(" + db.names.back().move_full() + ")"; - first = t1; - } - return first; +const char *parse_prefix_expression(const char *first, const char *last, + const typename C::String &op, C &db) { + const char *t1 = parse_expression(first, last, db); + if (t1 != first) { + if (db.names.empty()) + return first; + db.names.back().first = op + "(" + db.names.back().move_full() + ")"; + first = t1; + } + return first; } template -const char* -parse_binary_expression(const char* first, const char* last, const typename C::String& op, C& db) -{ - const char* t1 = parse_expression(first, last, db); - if (t1 != first) - { - const char* t2 = parse_expression(t1, last, db); - if (t2 != t1) - { - if (db.names.size() < 2) - return first; - auto op2 = db.names.back().move_full(); - db.names.pop_back(); - auto op1 = db.names.back().move_full(); - auto& nm = db.names.back().first; - nm.clear(); - if (op == ">") - nm += '('; - nm += "(" + op1 + ") " + op + " (" + op2 + ")"; - if (op == ">") - nm += ')'; - first = t2; - } - else - db.names.pop_back(); - } - return first; +const char *parse_binary_expression(const char *first, const char *last, + const typename C::String &op, C &db) { + const char *t1 = parse_expression(first, last, db); + if (t1 != first) { + const char *t2 = parse_expression(t1, last, db); + if (t2 != t1) { + if (db.names.size() < 2) + return first; + auto op2 = db.names.back().move_full(); + db.names.pop_back(); + auto op1 = db.names.back().move_full(); + auto &nm = db.names.back().first; + nm.clear(); + if (op == ">") + nm += '('; + nm += "(" + op1 + ") " + op + " (" + op2 + ")"; + if (op == ">") + nm += ')'; + first = t2; + } else + db.names.pop_back(); + } + return first; } // ::= // ::= -// ::= +// ::= +// // ::= cl + E # call -// ::= cv # conversion with one argument -// ::= cv _ * E # conversion with a different number of arguments -// ::= [gs] nw * _ E # new (expr-list) type -// ::= [gs] nw * _ # new (expr-list) type (init) -// ::= [gs] na * _ E # new[] (expr-list) type -// ::= [gs] na * _ # new[] (expr-list) type (init) -// ::= [gs] dl # delete expression -// ::= [gs] da # delete[] expression -// ::= pp_ # prefix ++ -// ::= mm_ # prefix -- -// ::= ti # typeid (type) -// ::= te # typeid (expression) -// ::= dc # dynamic_cast (expression) -// ::= sc # static_cast (expression) -// ::= cc # const_cast (expression) -// ::= rc # reinterpret_cast (expression) -// ::= st # sizeof (a type) -// ::= sz # sizeof (an expression) -// ::= at # alignof (a type) -// ::= az # alignof (an expression) -// ::= nx # noexcept (expression) +// ::= cv # +// conversion with one argument +// ::= cv _ * E # +// conversion with a different number of arguments +// ::= [gs] nw * _ E # new +// (expr-list) type +// ::= [gs] nw * _ # new +// (expr-list) type (init) +// ::= [gs] na * _ E # new[] +// (expr-list) type +// ::= [gs] na * _ # new[] +// (expr-list) type (init) +// ::= [gs] dl # +// delete expression +// ::= [gs] da # +// delete[] expression +// ::= pp_ # +// prefix ++ +// ::= mm_ # +// prefix -- +// ::= ti # +// typeid (type) +// ::= te # +// typeid (expression) +// ::= dc # +// dynamic_cast (expression) +// ::= sc # +// static_cast (expression) +// ::= cc # +// const_cast (expression) +// ::= rc # +// reinterpret_cast (expression) +// ::= st # +// sizeof (a type) +// ::= sz # +// sizeof (an expression) +// ::= at # +// alignof (a type) +// ::= az # +// alignof (an expression) +// ::= nx # +// noexcept (expression) // ::= // ::= -// ::= dt # expr.name -// ::= pt # expr->name -// ::= ds # expr.*expr -// ::= sZ # size of a parameter pack -// ::= sZ # size of a function parameter pack -// ::= sp # pack expansion -// ::= tw # throw expression -// ::= tr # throw with no operand (rethrow) -// ::= # f(p), N::f(p), ::f(p), -// # freestanding dependent name (e.g., T::x), -// # objectless nonstatic member reference +// ::= dt # +// expr.name +// ::= pt # +// expr->name +// ::= ds # +// expr.*expr +// ::= sZ # size +// of a parameter pack +// ::= sZ # size +// of a function parameter pack +// ::= sp # pack +// expansion +// ::= tw # throw +// expression +// ::= tr # throw +// with no operand (rethrow) +// ::= # f(p), +// N::f(p), ::f(p), +// # +// freestanding +// dependent +// name +// (e.g., +// T::x), +// # +// objectless +// nonstatic +// member +// reference // ::= template -const char* -parse_expression(const char* first, const char* last, C& db) -{ - if (last - first >= 2) - { - const char* t = first; - bool parsed_gs = false; - if (last - first >= 4 && t[0] == 'g' && t[1] == 's') - { - t += 2; - parsed_gs = true; +const char *parse_expression(const char *first, const char *last, C &db) { + if (last - first >= 2) { + const char *t = first; + bool parsed_gs = false; + if (last - first >= 4 && t[0] == 'g' && t[1] == 's') { + t += 2; + parsed_gs = true; + } + switch (*t) { + case 'L': + first = parse_expr_primary(first, last, db); + break; + case 'T': + first = parse_template_param(first, last, db); + break; + case 'f': + first = parse_function_param(first, last, db); + break; + case 'a': + switch (t[1]) { + case 'a': + t = parse_binary_expression(first + 2, last, "&&", db); + if (t != first + 2) + first = t; + break; + case 'd': + t = parse_prefix_expression(first + 2, last, "&", db); + if (t != first + 2) + first = t; + break; + case 'n': + t = parse_binary_expression(first + 2, last, "&", db); + if (t != first + 2) + first = t; + break; + case 'N': + t = parse_binary_expression(first + 2, last, "&=", db); + if (t != first + 2) + first = t; + break; + case 'S': + t = parse_binary_expression(first + 2, last, "=", db); + if (t != first + 2) + first = t; + break; + case 't': + first = parse_alignof_type(first, last, db); + break; + case 'z': + first = parse_alignof_expr(first, last, db); + break; + } + break; + case 'c': + switch (t[1]) { + case 'c': + first = parse_const_cast_expr(first, last, db); + break; + case 'l': + first = parse_call_expr(first, last, db); + break; + case 'm': + t = parse_binary_expression(first + 2, last, ",", db); + if (t != first + 2) + first = t; + break; + case 'o': + t = parse_prefix_expression(first + 2, last, "~", db); + if (t != first + 2) + first = t; + break; + case 'v': + first = parse_conversion_expr(first, last, db); + break; + } + break; + case 'd': + switch (t[1]) { + case 'a': { + const char *t1 = parse_expression(t + 2, last, db); + if (t1 != t + 2) { + if (db.names.empty()) + return first; + db.names.back().first = + (parsed_gs ? typename C::String("::") : typename C::String()) + + "delete[] " + db.names.back().move_full(); + first = t1; } - switch (*t) - { - case 'L': - first = parse_expr_primary(first, last, db); - break; - case 'T': - first = parse_template_param(first, last, db); - break; - case 'f': - first = parse_function_param(first, last, db); - break; - case 'a': - switch (t[1]) - { - case 'a': - t = parse_binary_expression(first+2, last, "&&", db); - if (t != first+2) - first = t; - break; - case 'd': - t = parse_prefix_expression(first+2, last, "&", db); - if (t != first+2) - first = t; - break; - case 'n': - t = parse_binary_expression(first+2, last, "&", db); - if (t != first+2) - first = t; - break; - case 'N': - t = parse_binary_expression(first+2, last, "&=", db); - if (t != first+2) - first = t; - break; - case 'S': - t = parse_binary_expression(first+2, last, "=", db); - if (t != first+2) - first = t; - break; - case 't': - first = parse_alignof_type(first, last, db); - break; - case 'z': - first = parse_alignof_expr(first, last, db); - break; - } - break; - case 'c': - switch (t[1]) - { - case 'c': - first = parse_const_cast_expr(first, last, db); - break; - case 'l': - first = parse_call_expr(first, last, db); - break; - case 'm': - t = parse_binary_expression(first+2, last, ",", db); - if (t != first+2) - first = t; - break; - case 'o': - t = parse_prefix_expression(first+2, last, "~", db); - if (t != first+2) - first = t; - break; - case 'v': - first = parse_conversion_expr(first, last, db); - break; - } - break; - case 'd': - switch (t[1]) - { - case 'a': - { - const char* t1 = parse_expression(t+2, last, db); - if (t1 != t+2) - { - if (db.names.empty()) - return first; - db.names.back().first = (parsed_gs ? typename C::String("::") : typename C::String()) + - "delete[] " + db.names.back().move_full(); - first = t1; - } - } - break; - case 'c': - first = parse_dynamic_cast_expr(first, last, db); - break; - case 'e': - t = parse_prefix_expression(first+2, last, "*", db); - if (t != first+2) - first = t; - break; - case 'l': - { - const char* t1 = parse_expression(t+2, last, db); - if (t1 != t+2) - { - if (db.names.empty()) - return first; - db.names.back().first = (parsed_gs ? typename C::String("::") : typename C::String()) + - "delete " + db.names.back().move_full(); - first = t1; - } - } - break; - case 'n': - return parse_unresolved_name(first, last, db); - case 's': - first = parse_dot_star_expr(first, last, db); - break; - case 't': - first = parse_dot_expr(first, last, db); - break; - case 'v': - t = parse_binary_expression(first+2, last, "/", db); - if (t != first+2) - first = t; - break; - case 'V': - t = parse_binary_expression(first+2, last, "/=", db); - if (t != first+2) - first = t; - break; - } - break; - case 'e': - switch (t[1]) - { - case 'o': - t = parse_binary_expression(first+2, last, "^", db); - if (t != first+2) - first = t; - break; - case 'O': - t = parse_binary_expression(first+2, last, "^=", db); - if (t != first+2) - first = t; - break; - case 'q': - t = parse_binary_expression(first+2, last, "==", db); - if (t != first+2) - first = t; - break; - } - break; - case 'g': - switch (t[1]) - { - case 'e': - t = parse_binary_expression(first+2, last, ">=", db); - if (t != first+2) - first = t; - break; - case 't': - t = parse_binary_expression(first+2, last, ">", db); - if (t != first+2) - first = t; - break; - } - break; - case 'i': - if (t[1] == 'x') - { - const char* t1 = parse_expression(first+2, last, db); - if (t1 != first+2) - { - const char* t2 = parse_expression(t1, last, db); - if (t2 != t1) - { - if (db.names.size() < 2) - return first; - auto op2 = db.names.back().move_full(); - db.names.pop_back(); - auto op1 = db.names.back().move_full(); - db.names.back() = "(" + op1 + ")[" + op2 + "]"; - first = t2; - } - else - db.names.pop_back(); - } - } - break; - case 'l': - switch (t[1]) - { - case 'e': - t = parse_binary_expression(first+2, last, "<=", db); - if (t != first+2) - first = t; - break; - case 's': - t = parse_binary_expression(first+2, last, "<<", db); - if (t != first+2) - first = t; - break; - case 'S': - t = parse_binary_expression(first+2, last, "<<=", db); - if (t != first+2) - first = t; - break; - case 't': - t = parse_binary_expression(first+2, last, "<", db); - if (t != first+2) - first = t; - break; - } - break; - case 'm': - switch (t[1]) - { - case 'i': - t = parse_binary_expression(first+2, last, "-", db); - if (t != first+2) - first = t; - break; - case 'I': - t = parse_binary_expression(first+2, last, "-=", db); - if (t != first+2) - first = t; - break; - case 'l': - t = parse_binary_expression(first+2, last, "*", db); - if (t != first+2) - first = t; - break; - case 'L': - t = parse_binary_expression(first+2, last, "*=", db); - if (t != first+2) - first = t; - break; - case 'm': - if (first+2 != last && first[2] == '_') - { - t = parse_prefix_expression(first+3, last, "--", db); - if (t != first+3) - first = t; - } - else - { - const char* t1 = parse_expression(first+2, last, db); - if (t1 != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "(" + db.names.back().move_full() + ")--"; - first = t1; - } - } - break; - } - break; - case 'n': - switch (t[1]) - { - case 'a': - case 'w': - first = parse_new_expr(first, last, db); - break; - case 'e': - t = parse_binary_expression(first+2, last, "!=", db); - if (t != first+2) - first = t; - break; - case 'g': - t = parse_prefix_expression(first+2, last, "-", db); - if (t != first+2) - first = t; - break; - case 't': - t = parse_prefix_expression(first+2, last, "!", db); - if (t != first+2) - first = t; - break; - case 'x': - t = parse_noexcept_expression(first+2, last, db); - if (t != first+2) - first = t; - break; - } - break; - case 'o': - switch (t[1]) - { - case 'n': - return parse_unresolved_name(first, last, db); - case 'o': - t = parse_binary_expression(first+2, last, "||", db); - if (t != first+2) - first = t; - break; - case 'r': - t = parse_binary_expression(first+2, last, "|", db); - if (t != first+2) - first = t; - break; - case 'R': - t = parse_binary_expression(first+2, last, "|=", db); - if (t != first+2) - first = t; - break; - } - break; - case 'p': - switch (t[1]) - { - case 'm': - t = parse_binary_expression(first+2, last, "->*", db); - if (t != first+2) - first = t; - break; - case 'l': - t = parse_binary_expression(first+2, last, "+", db); - if (t != first+2) - first = t; - break; - case 'L': - t = parse_binary_expression(first+2, last, "+=", db); - if (t != first+2) - first = t; - break; - case 'p': - if (first+2 != last && first[2] == '_') - { - t = parse_prefix_expression(first+3, last, "++", db); - if (t != first+3) - first = t; - } - else - { - const char* t1 = parse_expression(first+2, last, db); - if (t1 != first+2) - { - if (db.names.empty()) - return first; - db.names.back() = "(" + db.names.back().move_full() + ")++"; - first = t1; - } - } - break; - case 's': - t = parse_prefix_expression(first+2, last, "+", db); - if (t != first+2) - first = t; - break; - case 't': - first = parse_arrow_expr(first, last, db); - break; - } - break; - case 'q': - if (t[1] == 'u') - { - const char* t1 = parse_expression(first+2, last, db); - if (t1 != first+2) - { - const char* t2 = parse_expression(t1, last, db); - if (t2 != t1) - { - const char* t3 = parse_expression(t2, last, db); - if (t3 != t2) - { - if (db.names.size() < 3) - return first; - auto op3 = db.names.back().move_full(); - db.names.pop_back(); - auto op2 = db.names.back().move_full(); - db.names.pop_back(); - auto op1 = db.names.back().move_full(); - db.names.back() = "(" + op1 + ") ? (" + op2 + ") : (" + op3 + ")"; - first = t3; - } - else - { - db.names.pop_back(); - db.names.pop_back(); - } - } - else - db.names.pop_back(); - } - } - break; - case 'r': - switch (t[1]) - { - case 'c': - first = parse_reinterpret_cast_expr(first, last, db); - break; - case 'm': - t = parse_binary_expression(first+2, last, "%", db); - if (t != first+2) - first = t; - break; - case 'M': - t = parse_binary_expression(first+2, last, "%=", db); - if (t != first+2) - first = t; - break; - case 's': - t = parse_binary_expression(first+2, last, ">>", db); - if (t != first+2) - first = t; - break; - case 'S': - t = parse_binary_expression(first+2, last, ">>=", db); - if (t != first+2) - first = t; - break; - } - break; - case 's': - switch (t[1]) - { - case 'c': - first = parse_static_cast_expr(first, last, db); - break; - case 'p': - first = parse_pack_expansion(first, last, db); - break; - case 'r': - return parse_unresolved_name(first, last, db); - case 't': - first = parse_sizeof_type_expr(first, last, db); - break; - case 'z': - first = parse_sizeof_expr_expr(first, last, db); - break; - case 'Z': - if (last - t >= 3) - { - switch (t[2]) - { - case 'T': - first = parse_sizeof_param_pack_expr(first, last, db); - break; - case 'f': - first = parse_sizeof_function_param_pack_expr(first, last, db); - break; - } - } - break; - } - break; - case 't': - switch (t[1]) - { - case 'e': - case 'i': - first = parse_typeid_expr(first, last, db); - break; - case 'r': - db.names.push_back("throw"); - first += 2; - break; - case 'w': - first = parse_throw_expr(first, last, db); - break; - } + } break; + case 'c': + first = parse_dynamic_cast_expr(first, last, db); + break; + case 'e': + t = parse_prefix_expression(first + 2, last, "*", db); + if (t != first + 2) + first = t; + break; + case 'l': { + const char *t1 = parse_expression(t + 2, last, db); + if (t1 != t + 2) { + if (db.names.empty()) + return first; + db.names.back().first = + (parsed_gs ? typename C::String("::") : typename C::String()) + + "delete " + db.names.back().move_full(); + first = t1; + } + } break; + case 'n': + return parse_unresolved_name(first, last, db); + case 's': + first = parse_dot_star_expr(first, last, db); + break; + case 't': + first = parse_dot_expr(first, last, db); + break; + case 'v': + t = parse_binary_expression(first + 2, last, "/", db); + if (t != first + 2) + first = t; + break; + case 'V': + t = parse_binary_expression(first + 2, last, "/=", db); + if (t != first + 2) + first = t; + break; + } + break; + case 'e': + switch (t[1]) { + case 'o': + t = parse_binary_expression(first + 2, last, "^", db); + if (t != first + 2) + first = t; + break; + case 'O': + t = parse_binary_expression(first + 2, last, "^=", db); + if (t != first + 2) + first = t; + break; + case 'q': + t = parse_binary_expression(first + 2, last, "==", db); + if (t != first + 2) + first = t; + break; + } + break; + case 'g': + switch (t[1]) { + case 'e': + t = parse_binary_expression(first + 2, last, ">=", db); + if (t != first + 2) + first = t; + break; + case 't': + t = parse_binary_expression(first + 2, last, ">", db); + if (t != first + 2) + first = t; + break; + } + break; + case 'i': + if (t[1] == 'x') { + const char *t1 = parse_expression(first + 2, last, db); + if (t1 != first + 2) { + const char *t2 = parse_expression(t1, last, db); + if (t2 != t1) { + if (db.names.size() < 2) + return first; + auto op2 = db.names.back().move_full(); + db.names.pop_back(); + auto op1 = db.names.back().move_full(); + db.names.back() = "(" + op1 + ")[" + op2 + "]"; + first = t2; + } else + db.names.pop_back(); + } + } + break; + case 'l': + switch (t[1]) { + case 'e': + t = parse_binary_expression(first + 2, last, "<=", db); + if (t != first + 2) + first = t; + break; + case 's': + t = parse_binary_expression(first + 2, last, "<<", db); + if (t != first + 2) + first = t; + break; + case 'S': + t = parse_binary_expression(first + 2, last, "<<=", db); + if (t != first + 2) + first = t; + break; + case 't': + t = parse_binary_expression(first + 2, last, "<", db); + if (t != first + 2) + first = t; + break; + } + break; + case 'm': + switch (t[1]) { + case 'i': + t = parse_binary_expression(first + 2, last, "-", db); + if (t != first + 2) + first = t; + break; + case 'I': + t = parse_binary_expression(first + 2, last, "-=", db); + if (t != first + 2) + first = t; + break; + case 'l': + t = parse_binary_expression(first + 2, last, "*", db); + if (t != first + 2) + first = t; + break; + case 'L': + t = parse_binary_expression(first + 2, last, "*=", db); + if (t != first + 2) + first = t; + break; + case 'm': + if (first + 2 != last && first[2] == '_') { + t = parse_prefix_expression(first + 3, last, "--", db); + if (t != first + 3) + first = t; + } else { + const char *t1 = parse_expression(first + 2, last, db); + if (t1 != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "(" + db.names.back().move_full() + ")--"; + first = t1; + } + } + break; + } + break; + case 'n': + switch (t[1]) { + case 'a': + case 'w': + first = parse_new_expr(first, last, db); + break; + case 'e': + t = parse_binary_expression(first + 2, last, "!=", db); + if (t != first + 2) + first = t; + break; + case 'g': + t = parse_prefix_expression(first + 2, last, "-", db); + if (t != first + 2) + first = t; + break; + case 't': + t = parse_prefix_expression(first + 2, last, "!", db); + if (t != first + 2) + first = t; + break; + case 'x': + t = parse_noexcept_expression(first + 2, last, db); + if (t != first + 2) + first = t; + break; + } + break; + case 'o': + switch (t[1]) { + case 'n': + return parse_unresolved_name(first, last, db); + case 'o': + t = parse_binary_expression(first + 2, last, "||", db); + if (t != first + 2) + first = t; + break; + case 'r': + t = parse_binary_expression(first + 2, last, "|", db); + if (t != first + 2) + first = t; + break; + case 'R': + t = parse_binary_expression(first + 2, last, "|=", db); + if (t != first + 2) + first = t; + break; + } + break; + case 'p': + switch (t[1]) { + case 'm': + t = parse_binary_expression(first + 2, last, "->*", db); + if (t != first + 2) + first = t; + break; + case 'l': + t = parse_binary_expression(first + 2, last, "+", db); + if (t != first + 2) + first = t; + break; + case 'L': + t = parse_binary_expression(first + 2, last, "+=", db); + if (t != first + 2) + first = t; + break; + case 'p': + if (first + 2 != last && first[2] == '_') { + t = parse_prefix_expression(first + 3, last, "++", db); + if (t != first + 3) + first = t; + } else { + const char *t1 = parse_expression(first + 2, last, db); + if (t1 != first + 2) { + if (db.names.empty()) + return first; + db.names.back() = "(" + db.names.back().move_full() + ")++"; + first = t1; + } + } + break; + case 's': + t = parse_prefix_expression(first + 2, last, "+", db); + if (t != first + 2) + first = t; + break; + case 't': + first = parse_arrow_expr(first, last, db); + break; + } + break; + case 'q': + if (t[1] == 'u') { + const char *t1 = parse_expression(first + 2, last, db); + if (t1 != first + 2) { + const char *t2 = parse_expression(t1, last, db); + if (t2 != t1) { + const char *t3 = parse_expression(t2, last, db); + if (t3 != t2) { + if (db.names.size() < 3) + return first; + auto op3 = db.names.back().move_full(); + db.names.pop_back(); + auto op2 = db.names.back().move_full(); + db.names.pop_back(); + auto op1 = db.names.back().move_full(); + db.names.back() = "(" + op1 + ") ? (" + op2 + ") : (" + op3 + ")"; + first = t3; + } else { + db.names.pop_back(); + db.names.pop_back(); + } + } else + db.names.pop_back(); + } + } + break; + case 'r': + switch (t[1]) { + case 'c': + first = parse_reinterpret_cast_expr(first, last, db); + break; + case 'm': + t = parse_binary_expression(first + 2, last, "%", db); + if (t != first + 2) + first = t; + break; + case 'M': + t = parse_binary_expression(first + 2, last, "%=", db); + if (t != first + 2) + first = t; + break; + case 's': + t = parse_binary_expression(first + 2, last, ">>", db); + if (t != first + 2) + first = t; + break; + case 'S': + t = parse_binary_expression(first + 2, last, ">>=", db); + if (t != first + 2) + first = t; + break; + } + break; + case 's': + switch (t[1]) { + case 'c': + first = parse_static_cast_expr(first, last, db); + break; + case 'p': + first = parse_pack_expansion(first, last, db); + break; + case 'r': + return parse_unresolved_name(first, last, db); + case 't': + first = parse_sizeof_type_expr(first, last, db); + break; + case 'z': + first = parse_sizeof_expr_expr(first, last, db); + break; + case 'Z': + if (last - t >= 3) { + switch (t[2]) { + case 'T': + first = parse_sizeof_param_pack_expr(first, last, db); break; - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return parse_unresolved_name(first, last, db); + case 'f': + first = parse_sizeof_function_param_pack_expr(first, last, db); + break; + } } + break; + } + break; + case 't': + switch (t[1]) { + case 'e': + case 'i': + first = parse_typeid_expr(first, last, db); + break; + case 'r': + db.names.push_back("throw"); + first += 2; + break; + case 'w': + first = parse_throw_expr(first, last, db); + break; + } + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return parse_unresolved_name(first, last, db); } - return first; + } + return first; } -// ::= # type or template -// ::= X E # expression -// ::= # simple expressions -// ::= J * E # argument pack -// ::= LZ E # extension +// ::= # type +// or template +// ::= X E # +// expression +// ::= # +// simple expressions +// ::= J * E # +// argument pack +// ::= LZ E # +// extension template -const char* -parse_template_arg(const char* first, const char* last, C& db) -{ - if (first != last) - { - const char* t; - switch (*first) - { - case 'X': - t = parse_expression(first+1, last, db); - if (t != first+1) - { - if (t != last && *t == 'E') - first = t+1; - } - break; - case 'J': - t = first+1; - if (t == last) - return first; - while (*t != 'E') - { - const char* t1 = parse_template_arg(t, last, db); - if (t1 == t) - return first; - t = t1; - } - first = t+1; - break; - case 'L': - // or LZ E - if (first+1 != last && first[1] == 'Z') - { - t = parse_encoding(first+2, last, db); - if (t != first+2 && t != last && *t == 'E') - first = t+1; - } - else - first = parse_expr_primary(first, last, db); - break; - default: - // - first = parse_type(first, last, db); - break; - } +const char *parse_template_arg(const char *first, const char *last, C &db) { + if (first != last) { + const char *t; + switch (*first) { + case 'X': + t = parse_expression(first + 1, last, db); + if (t != first + 1) { + if (t != last && *t == 'E') + first = t + 1; + } + break; + case 'J': + t = first + 1; + if (t == last) + return first; + while (*t != 'E') { + const char *t1 = parse_template_arg(t, last, db); + if (t1 == t) + return first; + t = t1; + } + first = t + 1; + break; + case 'L': + // or LZ E + if (first + 1 != last && first[1] == 'Z') { + t = parse_encoding(first + 2, last, db); + if (t != first + 2 && t != last && *t == 'E') + first = t + 1; + } else + first = parse_expr_primary(first, last, db); + break; + default: + // + first = parse_type(first, last, db); + break; } - return first; + } + return first; } // ::= I * E // extension, the abi says + template -const char* -parse_template_args(const char* first, const char* last, C& db) -{ - if (last - first >= 2 && *first == 'I') - { - if (db.tag_templates) - db.template_param.back().clear(); - const char* t = first+1; - typename C::String args("<"); - while (*t != 'E') - { - if (db.tag_templates) - db.template_param.emplace_back(db.names.get_allocator()); - size_t k0 = db.names.size(); - const char* t1 = parse_template_arg(t, last, db); - size_t k1 = db.names.size(); - if (db.tag_templates) - db.template_param.pop_back(); - if (t1 == t || t1 == last) - return first; - if (db.tag_templates) - { - db.template_param.back().emplace_back(db.names.get_allocator()); - for (size_t k = k0; k < k1; ++k) - db.template_param.back().back().push_back(db.names[k]); - } - for (size_t k = k0; k < k1; ++k) - { - if (args.size() > 1) - args += ", "; - args += db.names[k].move_full(); - } - for (; k1 != k0; --k1) - db.names.pop_back(); - t = t1; - } - first = t + 1; - if (args.back() != '>') - args += ">"; - else - args += " >"; - db.names.push_back(std::move(args)); - +const char *parse_template_args(const char *first, const char *last, C &db) { + if (last - first >= 2 && *first == 'I') { + if (db.tag_templates) + db.template_param.back().clear(); + const char *t = first + 1; + typename C::String args("<"); + while (*t != 'E') { + if (db.tag_templates) + db.template_param.emplace_back(db.names.get_allocator()); + size_t k0 = db.names.size(); + const char *t1 = parse_template_arg(t, last, db); + size_t k1 = db.names.size(); + if (db.tag_templates) + db.template_param.pop_back(); + if (t1 == t || t1 == last) + return first; + if (db.tag_templates) { + db.template_param.back().emplace_back(db.names.get_allocator()); + for (size_t k = k0; k < k1; ++k) + db.template_param.back().back().push_back(db.names[k]); + } + for (size_t k = k0; k < k1; ++k) { + if (args.size() > 1) + args += ", "; + args += db.names[k].move_full(); + } + for (; k1 != k0; --k1) + db.names.pop_back(); + t = t1; } - return first; + first = t + 1; + if (args.back() != '>') + args += ">"; + else + args += " >"; + db.names.push_back(std::move(args)); + } + return first; } -// ::= N [] [] E -// ::= N [] [] E -// +// ::= N [] [] +// E +// ::= N [] [] +// E +// // ::= // ::= // ::= @@ -3918,262 +3494,223 @@ parse_template_args(const char* first, const char* last, C& db) // ::= // ::= // extension ::= L -// +// // ::=