[Lldb-commits] [lldb] r280751 - *** This commit represents a complete reformatting of the LLDB source code
Kate Stone via lldb-commits
lldb-commits at lists.llvm.org
Tue Sep 6 13:58:36 PDT 2016
Modified: lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.cpp Tue Sep 6 15:57:50 2016
@@ -10,20 +10,20 @@
// In-house headers:
#include "MICmnMIValueTuple.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnMIValueTuple constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnMIValueTuple::CMICmnMIValueTuple()
- : m_bSpaceAfterComma(false)
-{
- m_strValue = "{}";
+CMICmnMIValueTuple::CMICmnMIValueTuple() : m_bSpaceAfterComma(false) {
+ m_strValue = "{}";
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnMIValueTuple constructor.
// Type: Method.
// Args: vResult - (R) MI result object.
@@ -31,180 +31,176 @@ CMICmnMIValueTuple::CMICmnMIValueTuple()
// Throws: None.
//--
CMICmnMIValueTuple::CMICmnMIValueTuple(const CMICmnMIValueResult &vResult)
- : m_bSpaceAfterComma(false)
-{
- m_strValue = vResult.GetString();
- BuildTuple();
- m_bJustConstructed = false;
+ : m_bSpaceAfterComma(false) {
+ m_strValue = vResult.GetString();
+ BuildTuple();
+ m_bJustConstructed = false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnMIValueTuple constructor.
// Type: Method.
// Args: vResult - (R) MI result object.
-// vbUseSpacing - (R) True = put space separators into the string, false = no spaces used.
+// vbUseSpacing - (R) True = put space separators into the string,
+// false = no spaces used.
// Return: None.
// Throws: None.
//--
-CMICmnMIValueTuple::CMICmnMIValueTuple(const CMICmnMIValueResult &vResult, const bool vbUseSpacing)
- : m_bSpaceAfterComma(vbUseSpacing)
-{
- m_strValue = vResult.GetString();
- BuildTuple();
- m_bJustConstructed = false;
+CMICmnMIValueTuple::CMICmnMIValueTuple(const CMICmnMIValueResult &vResult,
+ const bool vbUseSpacing)
+ : m_bSpaceAfterComma(vbUseSpacing) {
+ m_strValue = vResult.GetString();
+ BuildTuple();
+ m_bJustConstructed = false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnMIValueTuple destructor.
// Type: Overrideable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnMIValueTuple::~CMICmnMIValueTuple()
-{
-}
+CMICmnMIValueTuple::~CMICmnMIValueTuple() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Build the result value's mandatory data part, one tuple
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::BuildTuple()
-{
- const char *pFormat = "{%s}";
- m_strValue = CMIUtilString::Format(pFormat, m_strValue.c_str());
+void CMICmnMIValueTuple::BuildTuple() {
+ const char *pFormat = "{%s}";
+ m_strValue = CMIUtilString::Format(pFormat, m_strValue.c_str());
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Add another MI result object to the value's list of tuples.
// Type: Method.
// Args: vResult - (R) The MI result object.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::BuildTuple(const CMICmnMIValueResult &vResult)
-{
- // Clear out the default "<Invalid>" text
- if (m_bJustConstructed)
- {
- m_bJustConstructed = false;
- m_strValue = vResult.GetString();
- BuildTuple();
- return;
- }
-
- if (m_strValue[0] == '{')
- {
- m_strValue = m_strValue.substr(1, m_strValue.size() - 1);
- }
- if (m_strValue[m_strValue.size() - 1] == '}')
- {
- m_strValue = m_strValue.substr(0, m_strValue.size() - 1);
- }
+void CMICmnMIValueTuple::BuildTuple(const CMICmnMIValueResult &vResult) {
+ // Clear out the default "<Invalid>" text
+ if (m_bJustConstructed) {
+ m_bJustConstructed = false;
+ m_strValue = vResult.GetString();
+ BuildTuple();
+ return;
+ }
- const char *pFormat = m_bSpaceAfterComma ? "{%s, %s}" : "{%s,%s}";
- m_strValue = CMIUtilString::Format(pFormat, m_strValue.c_str(), vResult.GetString().c_str());
+ if (m_strValue[0] == '{') {
+ m_strValue = m_strValue.substr(1, m_strValue.size() - 1);
+ }
+ if (m_strValue[m_strValue.size() - 1] == '}') {
+ m_strValue = m_strValue.substr(0, m_strValue.size() - 1);
+ }
+
+ const char *pFormat = m_bSpaceAfterComma ? "{%s, %s}" : "{%s,%s}";
+ m_strValue = CMIUtilString::Format(pFormat, m_strValue.c_str(),
+ vResult.GetString().c_str());
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Add string value to the value's list of tuples.
// Type: Method.
// Args: vValue - (R) The string object.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::BuildTuple(const CMIUtilString &vValue)
-{
- // Clear out the default "<Invalid>" text
- if (m_bJustConstructed)
- {
- m_bJustConstructed = false;
- m_strValue = vValue;
- BuildTuple();
- return;
- }
-
- const CMIUtilString data(ExtractContentNoBrackets());
- const char *pFormat = m_bSpaceAfterComma ? "{%s, %s}" : "{%s,%s}";
- m_strValue = CMIUtilString::Format(pFormat, data.c_str(), vValue.c_str());
+void CMICmnMIValueTuple::BuildTuple(const CMIUtilString &vValue) {
+ // Clear out the default "<Invalid>" text
+ if (m_bJustConstructed) {
+ m_bJustConstructed = false;
+ m_strValue = vValue;
+ BuildTuple();
+ return;
+ }
+
+ const CMIUtilString data(ExtractContentNoBrackets());
+ const char *pFormat = m_bSpaceAfterComma ? "{%s, %s}" : "{%s,%s}";
+ m_strValue = CMIUtilString::Format(pFormat, data.c_str(), vValue.c_str());
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Add another MI value object to the value list's of list is values.
-// Only values objects can be added to a list of values otherwise this function
+// Only values objects can be added to a list of values otherwise this
+// function
// will return MIstatus::failure.
// Type: Method.
// Args: vValue - (R) The MI value object.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::Add(const CMICmnMIValueResult &vResult)
-{
- BuildTuple(vResult);
+void CMICmnMIValueTuple::Add(const CMICmnMIValueResult &vResult) {
+ BuildTuple(vResult);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Add another MI value object to the value list's of list is values.
-// Only values objects can be added to a list of values otherwise this function
+// Only values objects can be added to a list of values otherwise this
+// function
// will return MIstatus::failure.
// Type: Method.
// Args: vValue - (R) The MI value object.
-// vbUseSpacing - (R) True = put space separators into the string, false = no spaces used.
+// vbUseSpacing - (R) True = put space separators into the string,
+// false = no spaces used.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::Add(const CMICmnMIValueResult &vResult, const bool vbUseSpacing)
-{
- m_bSpaceAfterComma = vbUseSpacing;
- BuildTuple(vResult);
+void CMICmnMIValueTuple::Add(const CMICmnMIValueResult &vResult,
+ const bool vbUseSpacing) {
+ m_bSpaceAfterComma = vbUseSpacing;
+ BuildTuple(vResult);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Add another MI value object to the value list's of list is values.
-// Only values objects can be added to a list of values otherwise this function
+// Only values objects can be added to a list of values otherwise this
+// function
// will return MIstatus::failure.
// Type: Method.
// Args: vValue - (R) The MI value object.
-// vbUseSpacing - (R) True = put space separators into the string, false = no spaces used.
+// vbUseSpacing - (R) True = put space separators into the string,
+// false = no spaces used.
// Return: None.
// Throws: None.
//--
-void
-CMICmnMIValueTuple::Add(const CMICmnMIValueConst &vValue, const bool vbUseSpacing)
-{
- m_bSpaceAfterComma = vbUseSpacing;
- BuildTuple(vValue.GetString());
+void CMICmnMIValueTuple::Add(const CMICmnMIValueConst &vValue,
+ const bool vbUseSpacing) {
+ m_bSpaceAfterComma = vbUseSpacing;
+ BuildTuple(vValue.GetString());
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve the contents of *this value object but without the outer most
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve the contents of *this value object but without the outer
+// most
// brackets.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Data within the object.
// Throws: None.
//--
-CMIUtilString
-CMICmnMIValueTuple::ExtractContentNoBrackets() const
-{
- CMIUtilString data(m_strValue);
-
- if (data[0] == '{')
- {
- data = data.substr(1, data.length() - 1);
- }
- if (data[data.size() - 1] == '}')
- {
- data = data.substr(0, data.length() - 1);
- }
+CMIUtilString CMICmnMIValueTuple::ExtractContentNoBrackets() const {
+ CMIUtilString data(m_strValue);
+
+ if (data[0] == '{') {
+ data = data.substr(1, data.length() - 1);
+ }
+ if (data[data.size() - 1] == '}') {
+ data = data.substr(0, data.length() - 1);
+ }
- return data;
+ return data;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnMIValueTuple.h Tue Sep 6 15:57:50 2016
@@ -11,10 +11,11 @@
// In-house headers:
#include "MICmnMIValue.h"
-#include "MICmnMIValueResult.h"
#include "MICmnMIValueConst.h"
+#include "MICmnMIValueResult.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code MI Result class. Part of the CMICmnMIValueTupleRecord
// set of objects.
// The syntax is as follows:
@@ -27,35 +28,37 @@
// value ==> const | tuple | list
// const ==> c-string (7 bit iso c string content)
// tuple ==> "{}" | "{" result ( "," result )* "}"
-// list ==> "[]" | "[" value ( "," value )* "]" | "[" result ( "," result )* "]"
+// list ==> "[]" | "[" value ( "," value )* "]" | "[" result ( ","
+// result )* "]"
// More information see:
// http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_chapter/gdb_22.html
//--
-class CMICmnMIValueTuple : public CMICmnMIValue
-{
- // Methods:
- public:
- /* ctor */ CMICmnMIValueTuple();
- /* ctor */ CMICmnMIValueTuple(const CMICmnMIValueResult &vResult);
- /* ctor */ CMICmnMIValueTuple(const CMICmnMIValueResult &vResult, const bool vbUseSpacing);
- //
- void Add(const CMICmnMIValueResult &vResult);
- void Add(const CMICmnMIValueResult &vResult, const bool vbUseSpacing);
- void Add(const CMICmnMIValueConst &vValue, const bool vbUseSpacing);
- CMIUtilString ExtractContentNoBrackets() const;
+class CMICmnMIValueTuple : public CMICmnMIValue {
+ // Methods:
+public:
+ /* ctor */ CMICmnMIValueTuple();
+ /* ctor */ CMICmnMIValueTuple(const CMICmnMIValueResult &vResult);
+ /* ctor */ CMICmnMIValueTuple(const CMICmnMIValueResult &vResult,
+ const bool vbUseSpacing);
+ //
+ void Add(const CMICmnMIValueResult &vResult);
+ void Add(const CMICmnMIValueResult &vResult, const bool vbUseSpacing);
+ void Add(const CMICmnMIValueConst &vValue, const bool vbUseSpacing);
+ CMIUtilString ExtractContentNoBrackets() const;
- // Overridden:
- public:
- // From CMICmnBase
- /* dtor */ ~CMICmnMIValueTuple() override;
+ // Overridden:
+public:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnMIValueTuple() override;
- // Methods:
- private:
- void BuildTuple();
- void BuildTuple(const CMICmnMIValueResult &vResult);
- void BuildTuple(const CMIUtilString &vValue);
+ // Methods:
+private:
+ void BuildTuple();
+ void BuildTuple(const CMICmnMIValueResult &vResult);
+ void BuildTuple(const CMIUtilString &vValue);
- // Attributes:
- private:
- bool m_bSpaceAfterComma; // True = put space separators into the string, false = no spaces used
+ // Attributes:
+private:
+ bool m_bSpaceAfterComma; // True = put space separators into the string, false
+ // = no spaces used
};
Modified: lldb/trunk/tools/lldb-mi/MICmnResources.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnResources.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnResources.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnResources.cpp Tue Sep 6 15:57:50 2016
@@ -8,279 +8,477 @@
//===----------------------------------------------------------------------===//
// Third party headers
-#include <inttypes.h> // For PRIx64
#include "assert.h"
+#include <inttypes.h> // For PRIx64
// In-house headers:
#include "MICmnResources.h"
// Instantiations:
-const CMICmnResources::SRsrcTextData CMICmnResources::ms_pResourceId2TextData[] = {
- {IDS_PROJNAME, "LLDB Machine Interface Driver (MI) All rights reserved"},
- {IDS_MI_VERSION_DESCRIPTION_DEBUG, "Version: 1.0.0.9 (Debug)"}, // See version history in MIDriverMain.cpp
- {IDS_MI_VERSION_DESCRIPTION, "Version: 1.0.0.9"},
- {IDS_MI_APPNAME_SHORT, "MI"},
- {IDS_MI_APPNAME_LONG, "Machine Interface Driver"},
- {IDS_MI_APP_FILEPATHNAME, "Application: %s"},
- {IDS_MI_APP_ARGS, "Command line args: "},
- {IDE_MI_VERSION_GDB,
- "Version: GNU gdb (GDB) 7.4 \n(This is a MI stub on top of LLDB and not GDB)\nAll rights reserved.\n"}, // *** Eclipse needs this
- // exactly!!
- {IDS_UTIL_FILE_ERR_INVALID_PATHNAME, "File Handler. Invalid file name path"},
- {IDS_UTIL_FILE_ERR_OPENING_FILE, "File Handler. Error %s opening '%s'"},
- {IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN, "File Handler. Unknown error opening '%s'"},
- {IDE_UTIL_FILE_ERR_WRITING_FILE, "File Handler. Error %s writing '%s'"},
- {IDE_UTIL_FILE_ERR_WRITING_NOTOPEN, "File Handler. File '%s' not open for write"},
- {IDS_RESOURCES_ERR_STRING_NOT_FOUND, "Resources. String (%d) not found in resources"},
- {IDS_RESOURCES_ERR_STRING_TABLE_INVALID, "Resources. String resource table is not set up"},
- {IDS_MI_CLIENT_MSG, "Client message: \"%s\""},
- {IDS_LOG_MSG_CREATION_DATE, "Creation date %s time %s%s"},
- {IDS_LOG_MSG_FILE_LOGGER_PATH, "File logger path: %s%s"},
- {IDS_LOG_MSG_VERSION, "Version: %s%s"},
- {IDS_LOG_ERR_FILE_LOGGER_DISABLED, "Log. File logger temporarily disabled due to file error '%s'"},
- {IDS_LOG_MEDIUM_ERR_INIT, "Log. Medium '%s' initialise failed. %s"},
- {IDS_LOG_MEDIUM_ERR_WRITE_ANY, "Log. Failed to write log data to any medium."},
- {IDS_LOG_MEDIUM_ERR_WRITE_MEDIUMFAIL, "Log. One or mediums failed writing log data."},
- {IDS_MEDIUMFILE_NAME, "File"},
- {IDS_MEDIUMFILE_ERR_INVALID_PATH, "<Invalid - not set>"},
- {IDS_MEDIUMFILE_ERR_FILE_HEADER, "<Invalid - header not set>"},
- {IDS_MEDIUMFILE_NAME_LOG, "File medium. %s"},
- {IDE_OS_ERR_UNKNOWN, "Unknown OS error"},
- {IDE_OS_ERR_RETRIEVING, "Unabled to retrieve OS error message"},
- {IDS_DRIVERMGR_DRIVER_ERR_INIT, "Driver Manager. Driver '%s' (ID:'%s') initialise failed. %s"},
- {IDE_MEDIUMSTDERR_NAME, "Stderr"},
- {IDE_MEDIUMSTDOUT_NAME, "Stdout"},
- {IDE_MI_APP_DESCRIPTION, "Description:\nThe Machine Interface Driver (MI Driver) is a stand alone executable\nthat either be used via "
- "a client i.e. Eclipse or directly from the command\nline. It processes MI commands, actions those commands "
- "using the internal\ndebugger then forms MI response formatted text which is returned to the\nclient."},
- {IDE_MI_APP_INFORMATION, "Information:\nCurrent limitations. The MI Driver currently only handles remote target\ndebugging. Local "
- "debugging has not been implemented. The MI Driver has\nbeen designed primarily to be used with Eclipse Juno "
- "and a custom plugin.\nThe custom plugin is not necessary to operate the MI Driver."},
- {IDE_MI_APP_ARG_USAGE, "\nMI driver usage:\n\n\tlldb-mi [--longOption] [-s hortOption] [executeable]\n\n[] = optional argument."},
- {IDE_MI_APP_ARG_HELP, "-h\n--help\n\tPrints out usage information for the MI debugger. Exit the MI\n\tDriver immediately."},
- {IDE_MI_APP_ARG_VERSION, "--version\n\tPrints out GNU (gdb) version information. Exit the MI Driver\n\timmediately."},
- {IDE_MI_APP_ARG_VERSION_LONG, "--versionLong\n\tPrints out MI Driver version information. Exit the MI Driver\n\timmediately."},
- {IDE_MI_APP_ARG_INTERPRETER, "--interpreter\n\t This option is kept for backward compatibility. This executable always run in MI mode"},
- {IDE_MI_APP_ARG_EXECUTEABLE, "--executable\n\tUse the MI Driver in MI mode for the debugging the specified executable." },
- {IDE_MI_APP_ARG_SOURCE, "-s <filename>\n--source <filename>\n\t"
- "Tells the debugger to read in and execute the lldb commands in the\n\t"
- "given file, after any file provided on the command line has been\n\tloaded."},
- {IDE_MI_APP_ARG_APP_LOG, "--log\n\tUse this argument to tell the MI Driver to update it's log\n\tfile '%s'."},
- {IDE_MI_APP_ARG_APP_LOG_DIR, "--log-dir\n\tUse this argument to specify the directory the MI Driver\n\twill place the log file in, i.e --log-dir=/tmp." },
- {IDE_MI_APP_ARG_EXAMPLE, "Example MI command:\n\t3-info-gdb-mi-command gdb-set\n\t3^done,command={exists=\"true\"}"},
- {IDE_MI_APP_ARG_EXECUTABLE, "executable (NOT IMPLEMENTED)\n\tThe file path to the executable i.e. '\"C:\\My Dev\\foo.exe\"'."},
- {IDS_STDIN_ERR_INVALID_PROMPT, "Stdin. Invalid prompt description '%s'"},
- {IDS_STDIN_ERR_THREAD_CREATION_FAILED, "Stdin. Thread creation failed '%s'"},
- {IDS_STDIN_ERR_THREAD_DELETE, "Stdin. Thread failed to delete '%s'"},
- {IDS_STDIN_ERR_CHKING_BYTE_AVAILABLE, "Stdin. Peeking on stdin stream '%s'"},
- {IDS_STDIN_INPUT_CTRL_CHARS, "Stdin. Receive characters not handled as a command: "},
- {IDS_CMD_QUIT_HELP, "MI Driver Command: quit\n\tExit the MI Driver application."},
- {IDS_THREADMGR_ERR_THREAD_ID_INVALID, "Thread Mgr. Thread ID '%s' is not valid"},
- {IDS_THREADMGR_ERR_THREAD_FAIL_CREATE, "Thread Mgr: Failed to create thread '%s'"},
- {IDS_THREADMGR_ERR_THREAD_ID_NOT_FOUND, "Thread Mgr: Thread with ID '%s' not found"},
- {IDS_THREADMGR_ERR_THREAD_STILL_ALIVE, "Thread Mgr: The thread(s) are still alive at Thread Mgr shutdown: %s"},
- {IDS_FALLTHRU_DRIVER_CMD_RECEIVED, "Fall Thru Driver. Received command '%s'. Is was %shandled"},
- {IDS_CMDFACTORY_ERR_INVALID_CMD_NAME, "Command factory. MI command name '%s' is invalid"},
- {IDS_CMDFACTORY_ERR_INVALID_CMD_CR8FN,
- "Command factory. Command creation function invalid for command '%s'. Does function exist? Pointer assigned to it?"},
- {IDS_CMDFACTORY_ERR_CMD_NOT_REGISTERED, "Command factory. Command '%s' not registered"},
- {IDS_CMDFACTORY_ERR_CMD_ALREADY_REGED, "Command factory. Command '%s' by that name already registered"},
- {IDS_CMDMGR_ERR_CMD_FAILED_CREATE, "Command manager. Command creation failed. %s"},
- {IDS_CMDMGR_ERR_CMD_INVOKER, "Command manager. %s "},
- {IDS_MI_INIT_ERR_LOG, "Log. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_RESOURCES, "Resources. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_INIT, "Driver. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_STREAMSTDIN, "Stdin. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_STREAMSTDIN_OSHANDLER, "Stdin. The OS specific stdin stream handler has not been specified for this OS"},
- {IDS_MI_INIT_ERR_OS_STDIN_HANDLER, "Stdin handler. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_STREAMSTDOUT, "Stdout. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_STREAMSTDERR, "Stderr. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_FALLTHRUDRIVER, "Fall Through Driver. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_THREADMGR, "Thread Mgr. Error occurred during initialisation %s"},
- {IDS_MI_INIT_ERR_CMDINTERPRETER, "Command interpreter. %s"},
- {IDS_MI_INIT_ERR_CMDMGR, "Command manager. %s"},
- {IDS_MI_INIT_ERR_CMDFACTORY, "Command factory. %s"},
- {IDS_MI_INIT_ERR_CMDINVOKER, "Command invoker. %s"},
- {IDS_MI_INIT_ERR_CMDMONITOR, "Command monitor. %s"},
- {IDS_MI_INIT_ERR_LLDBDEBUGGER, "LLDB Debugger. %s"},
- {IDS_MI_INIT_ERR_DRIVERMGR, "Driver manager. %s"},
- {IDS_MI_INIT_ERR_DRIVER, "Driver. %s"},
- {IDS_MI_INIT_ERR_OUTOFBANDHANDLER, "Out-of-band handler. %s "},
- {IDS_MI_INIT_ERR_DEBUGSESSIONINFO, "LLDB debug session info. %s "},
- {IDS_MI_INIT_ERR_THREADMANAGER, "Unable to init thread manager."},
- {IDS_MI_INIT_ERR_CLIENT_USING_DRIVER, "Initialising the client to this driver failed."},
- {IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION, "Initialising a local debug session failed."},
- {IDS_CODE_ERR_INVALID_PARAMETER_VALUE, "Code. Invalid parameter passed to function '%s'"},
- {IDS_CODE_ERR_INVALID_PARAM_NULL_POINTER, "Code. NULL pointer passes as a parameter to function '%s'"},
- {IDS_CODE_ERR_INVALID_ENUMERATION_VALUE, "Code. Invalid enumeration value encountered in function '%s'"},
- {
- IDS_LLDBDEBUGGER_ERR_INVALIDLISTENER, "LLDB Debugger. LLDB Listener is not valid",
- },
- {
- IDS_LLDBDEBUGGER_ERR_INVALIDDEBUGGER, "LLDB Debugger. LLDB Debugger is not valid",
- },
- {IDS_LLDBDEBUGGER_ERR_CLIENTDRIVER,
- "LLDB Debugger. CMIDriverBase derived driver needs to be set prior to CMICmnLLDBDDebugger initialisation"},
- {IDS_LLDBDEBUGGER_ERR_STARTLISTENER, "LLDB Debugger. Starting listening events for '%s' failed"},
- {IDS_LLDBDEBUGGER_ERR_THREADCREATIONFAIL, "LLDB Debugger. Thread creation failed '%s'"},
- {IDS_LLDBDEBUGGER_ERR_THREAD_DELETE, "LLDB Debugger. Thread failed to delete '%s'"},
- {IDS_LLDBDEBUGGER_ERR_INVALIDBROADCASTER, "LLDB Debugger. Invalid SB broadcaster class name '%s' "},
- {IDS_LLDBDEBUGGER_ERR_INVALIDCLIENTNAME, "LLDB Debugger. Invalid client name '%s' "},
- {IDS_LLDBDEBUGGER_ERR_CLIENTNOTREGISTERED, "LLDB Debugger. Client name '%s' not registered for listening events"},
- {IDS_LLDBDEBUGGER_ERR_STOPLISTENER, "LLDB Debugger. Failure occurred stopping event for client '%s' SBBroadcaster '%s'"},
- {IDS_LLDBDEBUGGER_ERR_BROADCASTER_NAME, "LLDB Debugger. Broadcaster's name '%s' is not valid"},
- {IDS_LLDBDEBUGGER_WRN_UNKNOWN_EVENT, "LLDB Debugger. Unhandled event '%s'"},
- {IDS_LLDBOUTOFBAND_ERR_UNKNOWN_EVENT, "LLDB Out-of-band. Handling event for '%s', an event enumeration '%d' not recognised"},
- {IDS_LLDBOUTOFBAND_ERR_PROCESS_INVALID, "LLDB Out-of-band. Invalid '%s' in '%s'"},
- {IDS_LLDBOUTOFBAND_ERR_BRKPT_NOTFOUND, "LLDB Out-of-band. %s. Breakpoint information for breakpoint ID %d not found"},
- {IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_GET, "LLDB Out-of-band. %s. Failed to retrieve breakpoint information for for breakpoint ID %d"},
- {IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_SET, "LLDB Out-of-band. %s. Failed to set breakpoint information for for breakpoint ID %d"},
- {IDS_LLDBOUTOFBAND_ERR_FORM_MI_RESPONSE, "LLDB Out-of-band. %s. Failed to form the MI Out-of-band response"},
- {IDS_LLDBOUTOFBAND_ERR_FRAME_INFO_GET, "LLDB Out-of-band. %s. Failed to retrieve frame information"},
- {IDS_LLDBOUTOFBAND_ERR_SETNEWDRIVERSTATE,
- "LLDB Out-of-band. %s. Event handler tried to set new MI Driver running state and failed. %s"},
- {IDS_LLDBOUTOFBAND_ERR_BRKPT_CNT_EXCEEDED,
- "LLDB Out-of-band. '%s'. Number of valid breakpoint exceeded %d. Cannot create new breakpoint with ID %d"},
- {IDS_DBGSESSION_ERR_SHARED_DATA_ADD, "LLDB debug session info. Failed to add '%s' data to the shared data command container"},
- {IDS_MI_SHTDWN_ERR_LOG, "Log. Error occurred during shutdown. %s"},
- {IDS_MI_SHUTDOWN_ERR, "Server shutdown failure. %s"},
- {IDE_MI_SHTDWN_ERR_RESOURCES, "Resources. Error occurred during shutdown. %s"},
- {IDE_MI_SHTDWN_ERR_STREAMSTDIN, "Stdin. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_OS_STDIN_HANDLER, "Stdin handler. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_STREAMSTDOUT, "Stdout. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_STREAMSTDERR, "Stderr. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_THREADMGR, "Thread Mgr. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_CMDINTERPRETER, "Command interpreter. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_CMDMGR, "Command manager. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_CMDFACTORY, "Command factory. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_CMDMONITOR, "Command invoker. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_CMDINVOKER, "Command monitor. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_LLDBDEBUGGER, "LLDB Debugger. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_DRIVERMGR, "Driver manager. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_DRIVER, "Driver. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_OUTOFBANDHANDLER, "Out-of-band handler. Error occurred during shutdown. %s"},
- {IDS_MI_SHTDWN_ERR_DEBUGSESSIONINFO, "LLDB debug session info. Error occurred during shutdown. %s"},
- {IDE_MI_SHTDWN_ERR_THREADMANAGER, "Unable to shutdown thread manager"},
- {IDS_DRIVER_ERR_PARSE_ARGS, "Driver. Driver '%s'. Parse args error '%s'"},
- {IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN, "Driver. Driver '%s'. Parse args error unknown"},
- {IDS_DRIVER_ERR_CURRENT_NOT_SET, "Driver. Current working driver has not been set. Call CMIDriverMgr::SetUseThisDriverToDoWork()"},
- {IDS_DRIVER_ERR_NON_REGISTERED, "Driver. No suitable drivers registered with the CMIDriverMgr to do work"},
- {IDS_DRIVER_SAY_DRIVER_USING, "Driver. Using driver '%s' internally"},
- {IDS_DRIVER_ERR_ID_INVALID, "Driver. Driver '%s' invalid ID '%s'"},
- {IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR, "Driver. Fall through driver '%s' (ID:'%s') error '%s'"},
- {IDS_DRIVER_CMD_RECEIVED, "Driver. Received command '%s'. It was %shandled%s"},
- {IDS_DRIVER_CMD_NOT_IN_FACTORY, ". Command '%s' not in Command Factory"},
- {
- IDS_DRIVER_ERR_DRIVER_STATE_ERROR, "Driver. Driver running state error. Cannot go to next state from present state as not allowed",
- },
- {IDS_DRIVER_WAITING_STDIN_DATA, "Driver. Main thread suspended waiting on Stdin Monitor to resume main thread"},
- {IDS_DRIVER_ERR_MAINLOOP, "Driver. Error in do main loop. %s"},
- {IDS_DRIVER_ERR_LOCAL_DEBUG_NOT_IMPL, "Driver. --executable argument given. Local debugging is not implemented."},
- {IDS_DRIVER_ERR_LOCAL_DEBUG_INIT, "Driver. --executable argument given. Initialising local debugging failed."},
- {IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN, "Stderr. Not all data was written to stream. The data '%s'"},
- {IDS_CMD_ARGS_ERR_OPTION_NOT_FOUND, "Command Args. Option '%s' not found"},
- {IDS_CMD_ARGS_ERR_VALIDATION_MANDATORY, "Mandatory args not found: %s"},
- {IDS_CMD_ARGS_ERR_VALIDATION_INVALID, "Invalid args: %s"},
- {IDS_CMD_ARGS_ERR_VALIDATION_MAN_INVALID, "Mandatory args not found: %s. Invalid args: %s"},
- {IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF, "Args missing additional information: %s"},
- {IDS_CMD_ARGS_ERR_CONTEXT_NOT_ALL_EATTEN, "Not all arguments or options were recognised: %s"},
- {IDS_CMD_ARGS_ERR_PREFIX_MSG, "Command Args. Validation failed. "},
- {IDS_VARIANT_ERR_USED_BASECLASS, "Variant container: Variant object used the base class. See CMIUtilVariant"},
- {IDS_VARIANT_ERR_MAP_KEY_INVALID, "Variant container: Invalid ID '%s'"},
- {IDS_WORD_INVALIDBRKTS, "<Invalid>"},
- {IDS_WORD_NONE, "None"},
- {IDS_WORD_NOT, "not"},
- {IDS_WORD_INVALIDEMPTY, "<empty>"},
- {IDS_WORD_INVALIDNULLPTR, "<NULL ptr>"},
- {IDS_WORD_UNKNOWNBRKTS, "<unknown>"},
- {IDS_WORD_NOT_IMPLEMENTED, "Not implemented"},
- {IDS_WORD_NOT_IMPLEMENTED_BRKTS, "<not implemented>"},
- {IDS_WORD_UNKNOWNTYPE_BRKTS, "<unknowntype>"},
- {IDS_WORD_ERR_MSG_NOT_IMPLEMENTED_BRKTS, "<error message not implemented>"},
- {IDS_CMD_ERR_N_OPTIONS_REQUIRED, "Command '%s'. Missing options, %d required"},
- {IDS_CMD_ERR_OPTION_NOT_FOUND, "Command '%s'. Option '%s' not found"},
- {IDS_CMD_ERR_ARGS, "Command '%s'. %s"},
- {IDS_CMD_WRN_ARGS_NOT_HANDLED, "Command '%s'. Warning the following options not handled by the command: %s"},
- {IDS_CMD_ERR_FNFAILED, "Command '%s'. Fn '%s' failed"},
- {IDS_CMD_ERR_SHARED_DATA_NOT_FOUND, "Command '%s'. Shared data '%s' not found"},
- {IDS_CMD_ERR_LLDBPROCESS_DETACH, "Command '%s'. Process detach failed. '%s'"},
- {IDS_CMD_ERR_LLDBPROCESS_DESTROY, "Command '%s'. Process destroy failed. '%s'"},
- {IDS_CMD_ERR_SETWKDIR, "Command '%s'. Failed to set working directory '%s'"},
- {IDS_CMD_ERR_INVALID_TARGET, "Command '%s'. Target binary '%s' is invalid. %s"},
- {IDS_CMD_ERR_INVALID_TARGET_CURRENT, "Command '%s'. Current SBTarget is invalid"},
- {IDS_CMD_ERR_INVALID_TARGET_TYPE, "Command '%s'. Target type '%s' is not recognised"},
- {IDS_CMD_ERR_INVALID_TARGET_PLUGIN, "Command '%s'. Target plugin is invalid. %s"},
- {IDS_CMD_ERR_CONNECT_TO_TARGET, "Command '%s'. Error connecting to target: '%s'"},
- {IDS_CMD_ERR_INVALID_TARGETPLUGINCURRENT, "Command '%s'. Current target plugin is invalid"},
- {IDS_CMD_ERR_NOT_IMPLEMENTED, "Command '%s'. Command not implemented"},
- {IDS_CMD_ERR_NOT_IMPLEMENTED_DEPRECATED, "Command '%s'. Command not implemented as it has been deprecated"},
- {IDS_CMD_ERR_CREATE_TARGET, "Command '%s'. Create target failed: %s"},
- {IDS_CMD_ERR_BRKPT_LOCATION_FORMAT, "Command '%s'. Incorrect format for breakpoint location '%s'"},
- {IDS_CMD_ERR_BRKPT_LOCATION_NOT_FOUND, "Command '%s'. Breakpoint location '%s' not found"},
- {IDS_CMD_ERR_BRKPT_INVALID, "Command '%s'. Breakpoint '%s' invalid"},
- {IDS_CMD_ERR_BRKPT_CNT_EXCEEDED, "Command '%s'. Number of valid breakpoint exceeded %d. Cannot create new breakpoint '%s'"},
- {IDS_CMD_ERR_SOME_ERROR, "Command '%s'. Error: %s"},
- {IDS_CMD_ERR_THREAD_INVALID, "Command '%s'. Thread ID invalid"},
- {IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID, "Command '%s'. Thread frame range invalid"},
- {IDS_CMD_ERR_FRAME_INVALID, "Command '%s'. Frame ID invalid"},
- {IDS_CMD_ERR_VARIABLE_DOESNOTEXIST, "Command '%s'. Variable '%s' does not exist"},
- {IDS_CMD_ERR_VARIABLE_ENUM_INVALID, "Command '%s'. Invalid enumeration for variable '%s' formatted string '%s'"},
- {IDS_CMD_ERR_VARIABLE_EXPRESSIONPATH, "Command '%s'. Failed to get expression for variable '%s'"},
- {IDS_CMD_ERR_VARIABLE_CREATION_FAILED, "Failed to create variable object for '%s'"},
- {IDS_CMD_ERR_VARIABLE_CHILD_RANGE_INVALID, "Command '%s'. Variable children range invalid"},
- {IDS_CMD_ERR_CMD_RUN_BUT_NO_ACTION, "<Error: Command run but command did not do anything useful. No MI response formed>"},
- {IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION, "<Error: Command run and event caught, did nothing useful. No MI Out-of-Bound formed>"},
- {IDS_CMD_ERR_DISASM_ADDR_START_INVALID, "Command '%s'. Invalid start value '%s'"},
- {IDS_CMD_ERR_DISASM_ADDR_END_INVALID, "Command '%s'. Invalid end value '%s'"},
- {IDS_CMD_ERR_MEMORY_ALLOC_FAILURE, "Command '%s'. Failed to allocate memory %d bytes"},
- {IDS_CMD_ERR_LLDB_ERR_NOT_READ_WHOLE_BLK, "Command '%s'. LLDB unable to read entire memory block of %u bytes at address 0x%016" PRIx64 },
- {IDS_CMD_ERR_LLDB_ERR_READ_MEM_BYTES, "Command '%s'. Unable to read memory block of %u bytes at address 0x%016" PRIx64 ": %s "},
- {IDS_CMD_ERR_INVALID_PROCESS, "Command '%s'. Invalid process during debug session"},
- {IDS_CMD_ERR_INVALID_PRINT_VALUES, "Command '%s'. Unknown value for PRINT_VALUES: must be: 0 or \"--no-values\", 1 or \"--all-values\", 2 or \"--simple-values\""},
- {IDS_CMD_ERR_INVALID_LOCATION_FORMAT, "Command '%s'. Invalid location format '%s'"},
- {IDS_CMD_ERR_INVALID_FORMAT_TYPE, "Command '%s'. Invalid var format type '%s'"},
- {IDS_CMD_ERR_BRKPT_INFO_OBJ_NOT_FOUND, "Command '%s'. Breakpoint information for breakpoint ID %d not found"},
- {IDS_CMD_ERR_LLDB_ERR_WRITE_MEM_BYTES, "Command '%s'. Unable to write memory block of %u bytes at address 0x%016" PRIx64 ": %s "},
- {IDS_CMD_ERR_LLDB_ERR_NOT_WRITE_WHOLEBLK, "Command '%s'. LLDB unable to write entire memory block of %u bytes at address 0x%016" PRIX64},
- {IDS_CMD_ERR_SET_NEW_DRIVER_STATE, "Command '%s'. Command tried to set new MI Driver running state and failed. %s"},
- {IDS_CMD_ERR_INFO_PRINTFN_NOT_FOUND, "The request '%s' was not recognised, not implemented"},
- {IDS_CMD_ERR_INFO_PRINTFN_FAILED, "The request '%s' failed."},
- {IDS_CMD_ERR_GDBSET_OPT_TARGETASYNC, "'target-async' expects \"on\" or \"off\""},
- {IDS_CMD_ERR_GDBSET_OPT_SOLIBSEARCHPATH, "'solib-search-path' requires at least one argument"},
- {IDS_CMD_ERR_GDBSET_OPT_PRINT_BAD_ARGS, "'print' expects option-name and \"on\" or \"off\""},
- {IDS_CMD_ERR_GDBSET_OPT_PRINT_UNKNOWN_OPTION, "'print' error. The option '%s' not found"},
- {IDS_CMD_ERR_GDBSHOW_OPT_PRINT_BAD_ARGS, "'print' expects option-name and \"on\" or \"off\""},
- {IDS_CMD_ERR_GDBSHOW_OPT_PRINT_UNKNOWN_OPTION, "'print' error. The option '%s' not found"},
- {IDS_CMD_ERR_EXPR_INVALID, "Failed to evaluate expression: %s"},
- {IDS_CMD_ERR_ATTACH_FAILED, "Command '%s'. Attach to processs failed: %s"},
- {IDS_CMD_ERR_ATTACH_BAD_ARGS, "Command '%s'. Must specify either a PID or a Name"}};
+const CMICmnResources::SRsrcTextData
+ CMICmnResources::ms_pResourceId2TextData[] = {
+ {IDS_PROJNAME,
+ "LLDB Machine Interface Driver (MI) All rights reserved"},
+ {IDS_MI_VERSION_DESCRIPTION_DEBUG,
+ "Version: 1.0.0.9 (Debug)"}, // See version history in MIDriverMain.cpp
+ {IDS_MI_VERSION_DESCRIPTION, "Version: 1.0.0.9"},
+ {IDS_MI_APPNAME_SHORT, "MI"},
+ {IDS_MI_APPNAME_LONG, "Machine Interface Driver"},
+ {IDS_MI_APP_FILEPATHNAME, "Application: %s"},
+ {IDS_MI_APP_ARGS, "Command line args: "},
+ {IDE_MI_VERSION_GDB, "Version: GNU gdb (GDB) 7.4 \n(This is a MI stub "
+ "on top of LLDB and not GDB)\nAll rights "
+ "reserved.\n"}, // *** Eclipse needs this
+ // exactly!!
+ {IDS_UTIL_FILE_ERR_INVALID_PATHNAME,
+ "File Handler. Invalid file name path"},
+ {IDS_UTIL_FILE_ERR_OPENING_FILE, "File Handler. Error %s opening '%s'"},
+ {IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN,
+ "File Handler. Unknown error opening '%s'"},
+ {IDE_UTIL_FILE_ERR_WRITING_FILE, "File Handler. Error %s writing '%s'"},
+ {IDE_UTIL_FILE_ERR_WRITING_NOTOPEN,
+ "File Handler. File '%s' not open for write"},
+ {IDS_RESOURCES_ERR_STRING_NOT_FOUND,
+ "Resources. String (%d) not found in resources"},
+ {IDS_RESOURCES_ERR_STRING_TABLE_INVALID,
+ "Resources. String resource table is not set up"},
+ {IDS_MI_CLIENT_MSG, "Client message: \"%s\""},
+ {IDS_LOG_MSG_CREATION_DATE, "Creation date %s time %s%s"},
+ {IDS_LOG_MSG_FILE_LOGGER_PATH, "File logger path: %s%s"},
+ {IDS_LOG_MSG_VERSION, "Version: %s%s"},
+ {IDS_LOG_ERR_FILE_LOGGER_DISABLED,
+ "Log. File logger temporarily disabled due to file error '%s'"},
+ {IDS_LOG_MEDIUM_ERR_INIT, "Log. Medium '%s' initialise failed. %s"},
+ {IDS_LOG_MEDIUM_ERR_WRITE_ANY,
+ "Log. Failed to write log data to any medium."},
+ {IDS_LOG_MEDIUM_ERR_WRITE_MEDIUMFAIL,
+ "Log. One or mediums failed writing log data."},
+ {IDS_MEDIUMFILE_NAME, "File"},
+ {IDS_MEDIUMFILE_ERR_INVALID_PATH, "<Invalid - not set>"},
+ {IDS_MEDIUMFILE_ERR_FILE_HEADER, "<Invalid - header not set>"},
+ {IDS_MEDIUMFILE_NAME_LOG, "File medium. %s"},
+ {IDE_OS_ERR_UNKNOWN, "Unknown OS error"},
+ {IDE_OS_ERR_RETRIEVING, "Unabled to retrieve OS error message"},
+ {IDS_DRIVERMGR_DRIVER_ERR_INIT,
+ "Driver Manager. Driver '%s' (ID:'%s') initialise failed. %s"},
+ {IDE_MEDIUMSTDERR_NAME, "Stderr"},
+ {IDE_MEDIUMSTDOUT_NAME, "Stdout"},
+ {IDE_MI_APP_DESCRIPTION,
+ "Description:\nThe Machine Interface Driver (MI Driver) is a stand "
+ "alone executable\nthat either be used via "
+ "a client i.e. Eclipse or directly from the command\nline. It "
+ "processes MI commands, actions those commands "
+ "using the internal\ndebugger then forms MI response formatted text "
+ "which is returned to the\nclient."},
+ {IDE_MI_APP_INFORMATION,
+ "Information:\nCurrent limitations. The MI Driver currently only "
+ "handles remote target\ndebugging. Local "
+ "debugging has not been implemented. The MI Driver has\nbeen designed "
+ "primarily to be used with Eclipse Juno "
+ "and a custom plugin.\nThe custom plugin is not necessary to operate "
+ "the MI Driver."},
+ {IDE_MI_APP_ARG_USAGE, "\nMI driver usage:\n\n\tlldb-mi [--longOption] "
+ "[-s hortOption] [executeable]\n\n[] = optional "
+ "argument."},
+ {IDE_MI_APP_ARG_HELP, "-h\n--help\n\tPrints out usage information for "
+ "the MI debugger. Exit the MI\n\tDriver "
+ "immediately."},
+ {IDE_MI_APP_ARG_VERSION, "--version\n\tPrints out GNU (gdb) version "
+ "information. Exit the MI "
+ "Driver\n\timmediately."},
+ {IDE_MI_APP_ARG_VERSION_LONG, "--versionLong\n\tPrints out MI Driver "
+ "version information. Exit the MI "
+ "Driver\n\timmediately."},
+ {IDE_MI_APP_ARG_INTERPRETER, "--interpreter\n\t This option is kept "
+ "for backward compatibility. This "
+ "executable always run in MI mode"},
+ {IDE_MI_APP_ARG_EXECUTEABLE, "--executable\n\tUse the MI Driver in MI "
+ "mode for the debugging the specified "
+ "executable."},
+ {IDE_MI_APP_ARG_SOURCE, "-s <filename>\n--source <filename>\n\t"
+ "Tells the debugger to read in and execute the "
+ "lldb commands in the\n\t"
+ "given file, after any file provided on the "
+ "command line has been\n\tloaded."},
+ {IDE_MI_APP_ARG_APP_LOG, "--log\n\tUse this argument to tell the MI "
+ "Driver to update it's log\n\tfile '%s'."},
+ {IDE_MI_APP_ARG_APP_LOG_DIR,
+ "--log-dir\n\tUse this argument to specify the directory the MI "
+ "Driver\n\twill place the log file in, i.e --log-dir=/tmp."},
+ {IDE_MI_APP_ARG_EXAMPLE, "Example MI command:\n\t3-info-gdb-mi-command "
+ "gdb-set\n\t3^done,command={exists=\"true\"}"},
+ {IDE_MI_APP_ARG_EXECUTABLE, "executable (NOT IMPLEMENTED)\n\tThe file "
+ "path to the executable i.e. '\"C:\\My "
+ "Dev\\foo.exe\"'."},
+ {IDS_STDIN_ERR_INVALID_PROMPT,
+ "Stdin. Invalid prompt description '%s'"},
+ {IDS_STDIN_ERR_THREAD_CREATION_FAILED,
+ "Stdin. Thread creation failed '%s'"},
+ {IDS_STDIN_ERR_THREAD_DELETE, "Stdin. Thread failed to delete '%s'"},
+ {IDS_STDIN_ERR_CHKING_BYTE_AVAILABLE,
+ "Stdin. Peeking on stdin stream '%s'"},
+ {IDS_STDIN_INPUT_CTRL_CHARS,
+ "Stdin. Receive characters not handled as a command: "},
+ {IDS_CMD_QUIT_HELP,
+ "MI Driver Command: quit\n\tExit the MI Driver application."},
+ {IDS_THREADMGR_ERR_THREAD_ID_INVALID,
+ "Thread Mgr. Thread ID '%s' is not valid"},
+ {IDS_THREADMGR_ERR_THREAD_FAIL_CREATE,
+ "Thread Mgr: Failed to create thread '%s'"},
+ {IDS_THREADMGR_ERR_THREAD_ID_NOT_FOUND,
+ "Thread Mgr: Thread with ID '%s' not found"},
+ {IDS_THREADMGR_ERR_THREAD_STILL_ALIVE, "Thread Mgr: The thread(s) are "
+ "still alive at Thread Mgr "
+ "shutdown: %s"},
+ {IDS_FALLTHRU_DRIVER_CMD_RECEIVED,
+ "Fall Thru Driver. Received command '%s'. Is was %shandled"},
+ {IDS_CMDFACTORY_ERR_INVALID_CMD_NAME,
+ "Command factory. MI command name '%s' is invalid"},
+ {IDS_CMDFACTORY_ERR_INVALID_CMD_CR8FN,
+ "Command factory. Command creation function invalid for command '%s'. "
+ "Does function exist? Pointer assigned to it?"},
+ {IDS_CMDFACTORY_ERR_CMD_NOT_REGISTERED,
+ "Command factory. Command '%s' not registered"},
+ {IDS_CMDFACTORY_ERR_CMD_ALREADY_REGED,
+ "Command factory. Command '%s' by that name already registered"},
+ {IDS_CMDMGR_ERR_CMD_FAILED_CREATE,
+ "Command manager. Command creation failed. %s"},
+ {IDS_CMDMGR_ERR_CMD_INVOKER, "Command manager. %s "},
+ {IDS_MI_INIT_ERR_LOG, "Log. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_RESOURCES,
+ "Resources. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_INIT,
+ "Driver. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_STREAMSTDIN,
+ "Stdin. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_STREAMSTDIN_OSHANDLER, "Stdin. The OS specific stdin "
+ "stream handler has not been "
+ "specified for this OS"},
+ {IDS_MI_INIT_ERR_OS_STDIN_HANDLER,
+ "Stdin handler. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_STREAMSTDOUT,
+ "Stdout. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_STREAMSTDERR,
+ "Stderr. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_FALLTHRUDRIVER,
+ "Fall Through Driver. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_THREADMGR,
+ "Thread Mgr. Error occurred during initialisation %s"},
+ {IDS_MI_INIT_ERR_CMDINTERPRETER, "Command interpreter. %s"},
+ {IDS_MI_INIT_ERR_CMDMGR, "Command manager. %s"},
+ {IDS_MI_INIT_ERR_CMDFACTORY, "Command factory. %s"},
+ {IDS_MI_INIT_ERR_CMDINVOKER, "Command invoker. %s"},
+ {IDS_MI_INIT_ERR_CMDMONITOR, "Command monitor. %s"},
+ {IDS_MI_INIT_ERR_LLDBDEBUGGER, "LLDB Debugger. %s"},
+ {IDS_MI_INIT_ERR_DRIVERMGR, "Driver manager. %s"},
+ {IDS_MI_INIT_ERR_DRIVER, "Driver. %s"},
+ {IDS_MI_INIT_ERR_OUTOFBANDHANDLER, "Out-of-band handler. %s "},
+ {IDS_MI_INIT_ERR_DEBUGSESSIONINFO, "LLDB debug session info. %s "},
+ {IDS_MI_INIT_ERR_THREADMANAGER, "Unable to init thread manager."},
+ {IDS_MI_INIT_ERR_CLIENT_USING_DRIVER,
+ "Initialising the client to this driver failed."},
+ {IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION,
+ "Initialising a local debug session failed."},
+ {IDS_CODE_ERR_INVALID_PARAMETER_VALUE,
+ "Code. Invalid parameter passed to function '%s'"},
+ {IDS_CODE_ERR_INVALID_PARAM_NULL_POINTER,
+ "Code. NULL pointer passes as a parameter to function '%s'"},
+ {IDS_CODE_ERR_INVALID_ENUMERATION_VALUE,
+ "Code. Invalid enumeration value encountered in function '%s'"},
+ {
+ IDS_LLDBDEBUGGER_ERR_INVALIDLISTENER,
+ "LLDB Debugger. LLDB Listener is not valid",
+ },
+ {
+ IDS_LLDBDEBUGGER_ERR_INVALIDDEBUGGER,
+ "LLDB Debugger. LLDB Debugger is not valid",
+ },
+ {IDS_LLDBDEBUGGER_ERR_CLIENTDRIVER,
+ "LLDB Debugger. CMIDriverBase derived driver needs to be set prior to "
+ "CMICmnLLDBDDebugger initialisation"},
+ {IDS_LLDBDEBUGGER_ERR_STARTLISTENER,
+ "LLDB Debugger. Starting listening events for '%s' failed"},
+ {IDS_LLDBDEBUGGER_ERR_THREADCREATIONFAIL,
+ "LLDB Debugger. Thread creation failed '%s'"},
+ {IDS_LLDBDEBUGGER_ERR_THREAD_DELETE,
+ "LLDB Debugger. Thread failed to delete '%s'"},
+ {IDS_LLDBDEBUGGER_ERR_INVALIDBROADCASTER,
+ "LLDB Debugger. Invalid SB broadcaster class name '%s' "},
+ {IDS_LLDBDEBUGGER_ERR_INVALIDCLIENTNAME,
+ "LLDB Debugger. Invalid client name '%s' "},
+ {IDS_LLDBDEBUGGER_ERR_CLIENTNOTREGISTERED,
+ "LLDB Debugger. Client name '%s' not registered for listening events"},
+ {IDS_LLDBDEBUGGER_ERR_STOPLISTENER, "LLDB Debugger. Failure occurred "
+ "stopping event for client '%s' "
+ "SBBroadcaster '%s'"},
+ {IDS_LLDBDEBUGGER_ERR_BROADCASTER_NAME,
+ "LLDB Debugger. Broadcaster's name '%s' is not valid"},
+ {IDS_LLDBDEBUGGER_WRN_UNKNOWN_EVENT,
+ "LLDB Debugger. Unhandled event '%s'"},
+ {IDS_LLDBOUTOFBAND_ERR_UNKNOWN_EVENT,
+ "LLDB Out-of-band. Handling event for '%s', an event enumeration '%d' "
+ "not recognised"},
+ {IDS_LLDBOUTOFBAND_ERR_PROCESS_INVALID,
+ "LLDB Out-of-band. Invalid '%s' in '%s'"},
+ {IDS_LLDBOUTOFBAND_ERR_BRKPT_NOTFOUND, "LLDB Out-of-band. %s. "
+ "Breakpoint information for "
+ "breakpoint ID %d not found"},
+ {IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_GET,
+ "LLDB Out-of-band. %s. Failed to retrieve breakpoint information for "
+ "for breakpoint ID %d"},
+ {IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_SET, "LLDB Out-of-band. %s. Failed "
+ "to set breakpoint information "
+ "for for breakpoint ID %d"},
+ {IDS_LLDBOUTOFBAND_ERR_FORM_MI_RESPONSE,
+ "LLDB Out-of-band. %s. Failed to form the MI Out-of-band response"},
+ {IDS_LLDBOUTOFBAND_ERR_FRAME_INFO_GET,
+ "LLDB Out-of-band. %s. Failed to retrieve frame information"},
+ {IDS_LLDBOUTOFBAND_ERR_SETNEWDRIVERSTATE,
+ "LLDB Out-of-band. %s. Event handler tried to set new MI Driver "
+ "running state and failed. %s"},
+ {IDS_LLDBOUTOFBAND_ERR_BRKPT_CNT_EXCEEDED,
+ "LLDB Out-of-band. '%s'. Number of valid breakpoint exceeded %d. "
+ "Cannot create new breakpoint with ID %d"},
+ {IDS_DBGSESSION_ERR_SHARED_DATA_ADD, "LLDB debug session info. Failed "
+ "to add '%s' data to the shared "
+ "data command container"},
+ {IDS_MI_SHTDWN_ERR_LOG, "Log. Error occurred during shutdown. %s"},
+ {IDS_MI_SHUTDOWN_ERR, "Server shutdown failure. %s"},
+ {IDE_MI_SHTDWN_ERR_RESOURCES,
+ "Resources. Error occurred during shutdown. %s"},
+ {IDE_MI_SHTDWN_ERR_STREAMSTDIN,
+ "Stdin. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_OS_STDIN_HANDLER,
+ "Stdin handler. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_STREAMSTDOUT,
+ "Stdout. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_STREAMSTDERR,
+ "Stderr. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_THREADMGR,
+ "Thread Mgr. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_CMDINTERPRETER,
+ "Command interpreter. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_CMDMGR,
+ "Command manager. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_CMDFACTORY,
+ "Command factory. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_CMDMONITOR,
+ "Command invoker. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_CMDINVOKER,
+ "Command monitor. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_LLDBDEBUGGER,
+ "LLDB Debugger. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_DRIVERMGR,
+ "Driver manager. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_DRIVER,
+ "Driver. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_OUTOFBANDHANDLER,
+ "Out-of-band handler. Error occurred during shutdown. %s"},
+ {IDS_MI_SHTDWN_ERR_DEBUGSESSIONINFO,
+ "LLDB debug session info. Error occurred during shutdown. %s"},
+ {IDE_MI_SHTDWN_ERR_THREADMANAGER, "Unable to shutdown thread manager"},
+ {IDS_DRIVER_ERR_PARSE_ARGS,
+ "Driver. Driver '%s'. Parse args error '%s'"},
+ {IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN,
+ "Driver. Driver '%s'. Parse args error unknown"},
+ {IDS_DRIVER_ERR_CURRENT_NOT_SET,
+ "Driver. Current working driver has not been set. Call "
+ "CMIDriverMgr::SetUseThisDriverToDoWork()"},
+ {IDS_DRIVER_ERR_NON_REGISTERED, "Driver. No suitable drivers "
+ "registered with the CMIDriverMgr to "
+ "do work"},
+ {IDS_DRIVER_SAY_DRIVER_USING, "Driver. Using driver '%s' internally"},
+ {IDS_DRIVER_ERR_ID_INVALID, "Driver. Driver '%s' invalid ID '%s'"},
+ {IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR,
+ "Driver. Fall through driver '%s' (ID:'%s') error '%s'"},
+ {IDS_DRIVER_CMD_RECEIVED,
+ "Driver. Received command '%s'. It was %shandled%s"},
+ {IDS_DRIVER_CMD_NOT_IN_FACTORY,
+ ". Command '%s' not in Command Factory"},
+ {
+ IDS_DRIVER_ERR_DRIVER_STATE_ERROR,
+ "Driver. Driver running state error. Cannot go to next state from "
+ "present state as not allowed",
+ },
+ {IDS_DRIVER_WAITING_STDIN_DATA, "Driver. Main thread suspended waiting "
+ "on Stdin Monitor to resume main "
+ "thread"},
+ {IDS_DRIVER_ERR_MAINLOOP, "Driver. Error in do main loop. %s"},
+ {IDS_DRIVER_ERR_LOCAL_DEBUG_NOT_IMPL, "Driver. --executable argument "
+ "given. Local debugging is not "
+ "implemented."},
+ {IDS_DRIVER_ERR_LOCAL_DEBUG_INIT, "Driver. --executable argument "
+ "given. Initialising local debugging "
+ "failed."},
+ {IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN,
+ "Stderr. Not all data was written to stream. The data '%s'"},
+ {IDS_CMD_ARGS_ERR_OPTION_NOT_FOUND,
+ "Command Args. Option '%s' not found"},
+ {IDS_CMD_ARGS_ERR_VALIDATION_MANDATORY, "Mandatory args not found: %s"},
+ {IDS_CMD_ARGS_ERR_VALIDATION_INVALID, "Invalid args: %s"},
+ {IDS_CMD_ARGS_ERR_VALIDATION_MAN_INVALID,
+ "Mandatory args not found: %s. Invalid args: %s"},
+ {IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF,
+ "Args missing additional information: %s"},
+ {IDS_CMD_ARGS_ERR_CONTEXT_NOT_ALL_EATTEN,
+ "Not all arguments or options were recognised: %s"},
+ {IDS_CMD_ARGS_ERR_PREFIX_MSG, "Command Args. Validation failed. "},
+ {IDS_VARIANT_ERR_USED_BASECLASS, "Variant container: Variant object "
+ "used the base class. See "
+ "CMIUtilVariant"},
+ {IDS_VARIANT_ERR_MAP_KEY_INVALID, "Variant container: Invalid ID '%s'"},
+ {IDS_WORD_INVALIDBRKTS, "<Invalid>"},
+ {IDS_WORD_NONE, "None"},
+ {IDS_WORD_NOT, "not"},
+ {IDS_WORD_INVALIDEMPTY, "<empty>"},
+ {IDS_WORD_INVALIDNULLPTR, "<NULL ptr>"},
+ {IDS_WORD_UNKNOWNBRKTS, "<unknown>"},
+ {IDS_WORD_NOT_IMPLEMENTED, "Not implemented"},
+ {IDS_WORD_NOT_IMPLEMENTED_BRKTS, "<not implemented>"},
+ {IDS_WORD_UNKNOWNTYPE_BRKTS, "<unknowntype>"},
+ {IDS_WORD_ERR_MSG_NOT_IMPLEMENTED_BRKTS,
+ "<error message not implemented>"},
+ {IDS_CMD_ERR_N_OPTIONS_REQUIRED,
+ "Command '%s'. Missing options, %d required"},
+ {IDS_CMD_ERR_OPTION_NOT_FOUND, "Command '%s'. Option '%s' not found"},
+ {IDS_CMD_ERR_ARGS, "Command '%s'. %s"},
+ {IDS_CMD_WRN_ARGS_NOT_HANDLED, "Command '%s'. Warning the following "
+ "options not handled by the command: "
+ "%s"},
+ {IDS_CMD_ERR_FNFAILED, "Command '%s'. Fn '%s' failed"},
+ {IDS_CMD_ERR_SHARED_DATA_NOT_FOUND,
+ "Command '%s'. Shared data '%s' not found"},
+ {IDS_CMD_ERR_LLDBPROCESS_DETACH,
+ "Command '%s'. Process detach failed. '%s'"},
+ {IDS_CMD_ERR_LLDBPROCESS_DESTROY,
+ "Command '%s'. Process destroy failed. '%s'"},
+ {IDS_CMD_ERR_SETWKDIR,
+ "Command '%s'. Failed to set working directory '%s'"},
+ {IDS_CMD_ERR_INVALID_TARGET,
+ "Command '%s'. Target binary '%s' is invalid. %s"},
+ {IDS_CMD_ERR_INVALID_TARGET_CURRENT,
+ "Command '%s'. Current SBTarget is invalid"},
+ {IDS_CMD_ERR_INVALID_TARGET_TYPE,
+ "Command '%s'. Target type '%s' is not recognised"},
+ {IDS_CMD_ERR_INVALID_TARGET_PLUGIN,
+ "Command '%s'. Target plugin is invalid. %s"},
+ {IDS_CMD_ERR_CONNECT_TO_TARGET,
+ "Command '%s'. Error connecting to target: '%s'"},
+ {IDS_CMD_ERR_INVALID_TARGETPLUGINCURRENT,
+ "Command '%s'. Current target plugin is invalid"},
+ {IDS_CMD_ERR_NOT_IMPLEMENTED, "Command '%s'. Command not implemented"},
+ {IDS_CMD_ERR_NOT_IMPLEMENTED_DEPRECATED,
+ "Command '%s'. Command not implemented as it has been deprecated"},
+ {IDS_CMD_ERR_CREATE_TARGET, "Command '%s'. Create target failed: %s"},
+ {IDS_CMD_ERR_BRKPT_LOCATION_FORMAT,
+ "Command '%s'. Incorrect format for breakpoint location '%s'"},
+ {IDS_CMD_ERR_BRKPT_LOCATION_NOT_FOUND,
+ "Command '%s'. Breakpoint location '%s' not found"},
+ {IDS_CMD_ERR_BRKPT_INVALID, "Command '%s'. Breakpoint '%s' invalid"},
+ {IDS_CMD_ERR_BRKPT_CNT_EXCEEDED, "Command '%s'. Number of valid "
+ "breakpoint exceeded %d. Cannot "
+ "create new breakpoint '%s'"},
+ {IDS_CMD_ERR_SOME_ERROR, "Command '%s'. Error: %s"},
+ {IDS_CMD_ERR_THREAD_INVALID, "Command '%s'. Thread ID invalid"},
+ {IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID,
+ "Command '%s'. Thread frame range invalid"},
+ {IDS_CMD_ERR_FRAME_INVALID, "Command '%s'. Frame ID invalid"},
+ {IDS_CMD_ERR_VARIABLE_DOESNOTEXIST,
+ "Command '%s'. Variable '%s' does not exist"},
+ {IDS_CMD_ERR_VARIABLE_ENUM_INVALID, "Command '%s'. Invalid enumeration "
+ "for variable '%s' formatted "
+ "string '%s'"},
+ {IDS_CMD_ERR_VARIABLE_EXPRESSIONPATH,
+ "Command '%s'. Failed to get expression for variable '%s'"},
+ {IDS_CMD_ERR_VARIABLE_CREATION_FAILED,
+ "Failed to create variable object for '%s'"},
+ {IDS_CMD_ERR_VARIABLE_CHILD_RANGE_INVALID,
+ "Command '%s'. Variable children range invalid"},
+ {IDS_CMD_ERR_CMD_RUN_BUT_NO_ACTION, "<Error: Command run but command "
+ "did not do anything useful. No MI "
+ "response formed>"},
+ {IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION,
+ "<Error: Command run and event caught, did nothing useful. No MI "
+ "Out-of-Bound formed>"},
+ {IDS_CMD_ERR_DISASM_ADDR_START_INVALID,
+ "Command '%s'. Invalid start value '%s'"},
+ {IDS_CMD_ERR_DISASM_ADDR_END_INVALID,
+ "Command '%s'. Invalid end value '%s'"},
+ {IDS_CMD_ERR_MEMORY_ALLOC_FAILURE,
+ "Command '%s'. Failed to allocate memory %d bytes"},
+ {IDS_CMD_ERR_LLDB_ERR_NOT_READ_WHOLE_BLK,
+ "Command '%s'. LLDB unable to read entire memory block of %u bytes at "
+ "address 0x%016" PRIx64},
+ {IDS_CMD_ERR_LLDB_ERR_READ_MEM_BYTES, "Command '%s'. Unable to read "
+ "memory block of %u bytes at "
+ "address 0x%016" PRIx64 ": %s "},
+ {IDS_CMD_ERR_INVALID_PROCESS,
+ "Command '%s'. Invalid process during debug session"},
+ {IDS_CMD_ERR_INVALID_PRINT_VALUES,
+ "Command '%s'. Unknown value for PRINT_VALUES: must be: 0 or "
+ "\"--no-values\", 1 or \"--all-values\", 2 or \"--simple-values\""},
+ {IDS_CMD_ERR_INVALID_LOCATION_FORMAT,
+ "Command '%s'. Invalid location format '%s'"},
+ {IDS_CMD_ERR_INVALID_FORMAT_TYPE,
+ "Command '%s'. Invalid var format type '%s'"},
+ {IDS_CMD_ERR_BRKPT_INFO_OBJ_NOT_FOUND,
+ "Command '%s'. Breakpoint information for breakpoint ID %d not found"},
+ {IDS_CMD_ERR_LLDB_ERR_WRITE_MEM_BYTES, "Command '%s'. Unable to write "
+ "memory block of %u bytes at "
+ "address 0x%016" PRIx64 ": %s "},
+ {IDS_CMD_ERR_LLDB_ERR_NOT_WRITE_WHOLEBLK,
+ "Command '%s'. LLDB unable to write entire memory block of %u bytes "
+ "at address 0x%016" PRIX64},
+ {IDS_CMD_ERR_SET_NEW_DRIVER_STATE, "Command '%s'. Command tried to set "
+ "new MI Driver running state and "
+ "failed. %s"},
+ {IDS_CMD_ERR_INFO_PRINTFN_NOT_FOUND,
+ "The request '%s' was not recognised, not implemented"},
+ {IDS_CMD_ERR_INFO_PRINTFN_FAILED, "The request '%s' failed."},
+ {IDS_CMD_ERR_GDBSET_OPT_TARGETASYNC,
+ "'target-async' expects \"on\" or \"off\""},
+ {IDS_CMD_ERR_GDBSET_OPT_SOLIBSEARCHPATH,
+ "'solib-search-path' requires at least one argument"},
+ {IDS_CMD_ERR_GDBSET_OPT_PRINT_BAD_ARGS,
+ "'print' expects option-name and \"on\" or \"off\""},
+ {IDS_CMD_ERR_GDBSET_OPT_PRINT_UNKNOWN_OPTION,
+ "'print' error. The option '%s' not found"},
+ {IDS_CMD_ERR_GDBSHOW_OPT_PRINT_BAD_ARGS,
+ "'print' expects option-name and \"on\" or \"off\""},
+ {IDS_CMD_ERR_GDBSHOW_OPT_PRINT_UNKNOWN_OPTION,
+ "'print' error. The option '%s' not found"},
+ {IDS_CMD_ERR_EXPR_INVALID, "Failed to evaluate expression: %s"},
+ {IDS_CMD_ERR_ATTACH_FAILED,
+ "Command '%s'. Attach to processs failed: %s"},
+ {IDS_CMD_ERR_ATTACH_BAD_ARGS,
+ "Command '%s'. Must specify either a PID or a Name"}};
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnResources constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnResources::CMICmnResources()
- : m_nResourceId2TextDataSize(0)
-{
- // Do not use this constructor, use Initialize()
+CMICmnResources::CMICmnResources() : m_nResourceId2TextDataSize(0) {
+ // Do not use this constructor, use Initialize()
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnResources destructor.
// Type: Overridden.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnResources::~CMICmnResources()
-{
- // Do not use this destructor, use Shutdown()
+CMICmnResources::~CMICmnResources() {
+ // Do not use this destructor, use Shutdown()
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize the resources and set locality for the server.
// Type: Method.
// Args: None.
@@ -288,20 +486,19 @@ CMICmnResources::~CMICmnResources()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnResources::Initialize()
-{
- m_clientUsageRefCnt++;
+bool CMICmnResources::Initialize() {
+ m_clientUsageRefCnt++;
- if (m_bInitialized)
- return MIstatus::success;
+ if (m_bInitialized)
+ return MIstatus::success;
- m_bInitialized = ReadResourceStringData();
+ m_bInitialized = ReadResourceStringData();
- return m_bInitialized;
+ return m_bInitialized;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resources for *this object.
// Type: Method.
// Args: None.
@@ -309,24 +506,23 @@ CMICmnResources::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnResources::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
+bool CMICmnResources::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- if (!m_bInitialized)
- return MIstatus::success;
+ if (!m_bInitialized)
+ return MIstatus::success;
- // Tear down resource explicitly
- m_mapRscrIdToTextData.clear();
+ // Tear down resource explicitly
+ m_mapRscrIdToTextData.clear();
- m_bInitialized = false;
+ m_bInitialized = false;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize the resources and set locality for the server.
// Type: Method.
// Args: None.
@@ -334,39 +530,37 @@ CMICmnResources::Shutdown()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnResources::ReadResourceStringData()
-{
- m_nResourceId2TextDataSize = sizeof ms_pResourceId2TextData / sizeof ms_pResourceId2TextData[0];
- for (MIuint i = 0; i < m_nResourceId2TextDataSize; i++)
- {
- const SRsrcTextData *pRscrData = &ms_pResourceId2TextData[i];
- MapPairRscrIdToTextData_t pr(pRscrData->id, pRscrData->pTextData);
- m_mapRscrIdToTextData.insert(pr);
- }
+bool CMICmnResources::ReadResourceStringData() {
+ m_nResourceId2TextDataSize =
+ sizeof ms_pResourceId2TextData / sizeof ms_pResourceId2TextData[0];
+ for (MIuint i = 0; i < m_nResourceId2TextDataSize; i++) {
+ const SRsrcTextData *pRscrData = &ms_pResourceId2TextData[i];
+ MapPairRscrIdToTextData_t pr(pRscrData->id, pRscrData->pTextData);
+ m_mapRscrIdToTextData.insert(pr);
+ }
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the corresponding text assigned to the resource ID.
// Type: Method.
// Args: vResourceId - (R) MI resource ID.
// Return: CMIUtilString - Resource text.
// Throws: None.
//--
-CMIUtilString
-CMICmnResources::GetString(const MIuint vResourceId) const
-{
- CMIUtilString str;
- const bool bFound = GetStringFromResource(vResourceId, str);
- MIunused(bFound);
- assert(bFound);
+CMIUtilString CMICmnResources::GetString(const MIuint vResourceId) const {
+ CMIUtilString str;
+ const bool bFound = GetStringFromResource(vResourceId, str);
+ MIunused(bFound);
+ assert(bFound);
- return str;
+ return str;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Determine the MI resource ID existings.
// Type: Method.
// Args: vResourceId - (R) MI resource ID.
@@ -374,16 +568,17 @@ CMICmnResources::GetString(const MIuint
// False - Not found.
// Throws: None.
//--
-bool
-CMICmnResources::HasString(const MIuint vResourceId) const
-{
- CMIUtilString str;
- return GetStringFromResource(vResourceId, str);
+bool CMICmnResources::HasString(const MIuint vResourceId) const {
+ CMIUtilString str;
+ return GetStringFromResource(vResourceId, str);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve the resource text data for the given resource ID. If a resource ID
-// cannot be found and error is given returning the ID of the resource that
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve the resource text data for the given resource ID. If a
+// resource ID
+// cannot be found and error is given returning the ID of the resource
+// that
// cannot be located.
// Type: Method.
// Args: vResourceId - (R) MI resource ID.
@@ -392,37 +587,34 @@ CMICmnResources::HasString(const MIuint
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnResources::GetStringFromResource(const MIuint vResourceId, CMIUtilString &vrwResourceString) const
-{
- MapRscrIdToTextData_t::const_iterator it = m_mapRscrIdToTextData.find(vResourceId);
- if (it == m_mapRscrIdToTextData.end())
- {
- // Check this is a static variable init that needs this before we are ready
- if (!m_bInitialized)
- {
- (const_cast<CMICmnResources *>(this))->Initialize();
- it = m_mapRscrIdToTextData.find(vResourceId);
- if (it == m_mapRscrIdToTextData.end())
- {
- vrwResourceString = MIRSRC(IDS_RESOURCES_ERR_STRING_TABLE_INVALID);
- return MIstatus::failure;
- }
- }
+bool CMICmnResources::GetStringFromResource(
+ const MIuint vResourceId, CMIUtilString &vrwResourceString) const {
+ MapRscrIdToTextData_t::const_iterator it =
+ m_mapRscrIdToTextData.find(vResourceId);
+ if (it == m_mapRscrIdToTextData.end()) {
+ // Check this is a static variable init that needs this before we are ready
+ if (!m_bInitialized) {
+ (const_cast<CMICmnResources *>(this))->Initialize();
+ it = m_mapRscrIdToTextData.find(vResourceId);
+ if (it == m_mapRscrIdToTextData.end()) {
+ vrwResourceString = MIRSRC(IDS_RESOURCES_ERR_STRING_TABLE_INVALID);
+ return MIstatus::failure;
+ }
+ }
- if (it == m_mapRscrIdToTextData.end())
- {
- vrwResourceString = CMIUtilString::Format(MIRSRC(IDS_RESOURCES_ERR_STRING_NOT_FOUND), vResourceId);
- return MIstatus::failure;
- }
+ if (it == m_mapRscrIdToTextData.end()) {
+ vrwResourceString = CMIUtilString::Format(
+ MIRSRC(IDS_RESOURCES_ERR_STRING_NOT_FOUND), vResourceId);
+ return MIstatus::failure;
}
+ }
- const MIuint nRsrcId((*it).first);
- MIunused(nRsrcId);
- const char *pRsrcData((*it).second);
+ const MIuint nRsrcId((*it).first);
+ MIunused(nRsrcId);
+ const char *pRsrcData((*it).second);
- // Return result
- vrwResourceString = pRsrcData;
+ // Return result
+ vrwResourceString = pRsrcData;
- return MIstatus::success;
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnResources.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnResources.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnResources.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnResources.h Tue Sep 6 15:57:50 2016
@@ -13,323 +13,321 @@
#include <map>
// In-house headers:
+#include "MICmnBase.h"
#include "MIUtilSingletonBase.h"
#include "MIUtilString.h"
-#include "MICmnBase.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI string test data resource definitions. These IDs match up with
// actual string data in a map internal to CMICmnResources.
// *** Be sure to update ms_pResourceId2TextData[] array ****
-enum
-{
- IDS_PROJNAME = 1,
- IDS_MI_VERSION_DESCRIPTION_DEBUG,
- IDS_MI_VERSION_DESCRIPTION,
- IDS_MI_APPNAME_SHORT,
- IDS_MI_APPNAME_LONG,
- IDS_MI_APP_FILEPATHNAME,
- IDS_MI_APP_ARGS,
- IDE_MI_VERSION_GDB,
-
- IDS_UTIL_FILE_ERR_INVALID_PATHNAME,
- IDS_UTIL_FILE_ERR_OPENING_FILE,
- IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN,
- IDE_UTIL_FILE_ERR_WRITING_FILE,
- IDE_UTIL_FILE_ERR_WRITING_NOTOPEN,
-
- IDS_RESOURCES_ERR_STRING_NOT_FOUND,
- IDS_RESOURCES_ERR_STRING_TABLE_INVALID,
-
- IDS_MI_CLIENT_MSG,
-
- IDS_LOG_MSG_CREATION_DATE,
- IDS_LOG_MSG_FILE_LOGGER_PATH,
- IDS_LOG_MSG_VERSION,
- IDS_LOG_ERR_FILE_LOGGER_DISABLED,
- IDS_LOG_MEDIUM_ERR_INIT,
- IDS_LOG_MEDIUM_ERR_WRITE_ANY,
- IDS_LOG_MEDIUM_ERR_WRITE_MEDIUMFAIL,
-
- IDS_MEDIUMFILE_NAME,
- IDS_MEDIUMFILE_ERR_INVALID_PATH,
- IDS_MEDIUMFILE_ERR_FILE_HEADER,
- IDS_MEDIUMFILE_NAME_LOG,
-
- IDE_OS_ERR_UNKNOWN,
- IDE_OS_ERR_RETRIEVING,
-
- IDS_DRIVERMGR_DRIVER_ERR_INIT,
-
- IDE_MEDIUMSTDERR_NAME,
- IDE_MEDIUMSTDOUT_NAME,
-
- IDE_MI_APP_DESCRIPTION,
- IDE_MI_APP_INFORMATION,
- IDE_MI_APP_ARG_USAGE,
- IDE_MI_APP_ARG_HELP,
- IDE_MI_APP_ARG_VERSION,
- IDE_MI_APP_ARG_VERSION_LONG,
- IDE_MI_APP_ARG_INTERPRETER,
- IDE_MI_APP_ARG_EXECUTEABLE,
- IDE_MI_APP_ARG_SOURCE,
- IDE_MI_APP_ARG_APP_LOG,
- IDE_MI_APP_ARG_APP_LOG_DIR,
- IDE_MI_APP_ARG_EXAMPLE,
- IDE_MI_APP_ARG_EXECUTABLE,
-
- IDS_STDIN_ERR_INVALID_PROMPT,
- IDS_STDIN_ERR_THREAD_CREATION_FAILED,
- IDS_STDIN_ERR_THREAD_DELETE,
- IDS_STDIN_ERR_CHKING_BYTE_AVAILABLE,
- IDS_STDIN_INPUT_CTRL_CHARS,
-
- IDS_CMD_QUIT_HELP,
-
- IDS_THREADMGR_ERR_THREAD_ID_INVALID,
- IDS_THREADMGR_ERR_THREAD_FAIL_CREATE,
- IDS_THREADMGR_ERR_THREAD_ID_NOT_FOUND,
- IDS_THREADMGR_ERR_THREAD_STILL_ALIVE,
-
- IDS_FALLTHRU_DRIVER_CMD_RECEIVED,
-
- IDS_CMDFACTORY_ERR_INVALID_CMD_NAME,
- IDS_CMDFACTORY_ERR_INVALID_CMD_CR8FN,
- IDS_CMDFACTORY_ERR_CMD_NOT_REGISTERED,
- IDS_CMDFACTORY_ERR_CMD_ALREADY_REGED,
-
- IDS_CMDMGR_ERR_CMD_FAILED_CREATE,
- IDS_CMDMGR_ERR_CMD_INVOKER,
-
- IDS_MI_INIT_ERR_LOG,
- IDS_MI_INIT_ERR_RESOURCES,
- IDS_MI_INIT_ERR_INIT,
- IDS_MI_INIT_ERR_STREAMSTDIN,
- IDS_MI_INIT_ERR_STREAMSTDIN_OSHANDLER,
- IDS_MI_INIT_ERR_OS_STDIN_HANDLER,
- IDS_MI_INIT_ERR_STREAMSTDOUT,
- IDS_MI_INIT_ERR_STREAMSTDERR,
- IDS_MI_INIT_ERR_FALLTHRUDRIVER,
- IDS_MI_INIT_ERR_THREADMGR,
- IDS_MI_INIT_ERR_CMDINTERPRETER,
- IDS_MI_INIT_ERR_CMDMGR,
- IDS_MI_INIT_ERR_CMDFACTORY,
- IDS_MI_INIT_ERR_CMDINVOKER,
- IDS_MI_INIT_ERR_CMDMONITOR,
- IDS_MI_INIT_ERR_LLDBDEBUGGER,
- IDS_MI_INIT_ERR_DRIVERMGR,
- IDS_MI_INIT_ERR_DRIVER,
- IDS_MI_INIT_ERR_OUTOFBANDHANDLER,
- IDS_MI_INIT_ERR_DEBUGSESSIONINFO,
- IDS_MI_INIT_ERR_THREADMANAGER,
- IDS_MI_INIT_ERR_CLIENT_USING_DRIVER,
- IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION,
-
- IDS_CODE_ERR_INVALID_PARAMETER_VALUE,
- IDS_CODE_ERR_INVALID_PARAM_NULL_POINTER,
- IDS_CODE_ERR_INVALID_ENUMERATION_VALUE,
-
- IDS_LLDBDEBUGGER_ERR_INVALIDLISTENER,
- IDS_LLDBDEBUGGER_ERR_INVALIDDEBUGGER,
- IDS_LLDBDEBUGGER_ERR_CLIENTDRIVER,
- IDS_LLDBDEBUGGER_ERR_STARTLISTENER,
- IDS_LLDBDEBUGGER_ERR_THREADCREATIONFAIL,
- IDS_LLDBDEBUGGER_ERR_THREAD_DELETE,
- IDS_LLDBDEBUGGER_ERR_INVALIDBROADCASTER,
- IDS_LLDBDEBUGGER_ERR_INVALIDCLIENTNAME,
- IDS_LLDBDEBUGGER_ERR_CLIENTNOTREGISTERED,
- IDS_LLDBDEBUGGER_ERR_STOPLISTENER,
- IDS_LLDBDEBUGGER_ERR_BROADCASTER_NAME,
- IDS_LLDBDEBUGGER_WRN_UNKNOWN_EVENT,
-
- IDS_LLDBOUTOFBAND_ERR_UNKNOWN_EVENT,
- IDS_LLDBOUTOFBAND_ERR_PROCESS_INVALID,
- IDS_LLDBOUTOFBAND_ERR_BRKPT_NOTFOUND,
- IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_GET,
- IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_SET,
- IDS_LLDBOUTOFBAND_ERR_FORM_MI_RESPONSE,
- IDS_LLDBOUTOFBAND_ERR_FRAME_INFO_GET,
- IDS_LLDBOUTOFBAND_ERR_SETNEWDRIVERSTATE,
- IDS_LLDBOUTOFBAND_ERR_BRKPT_CNT_EXCEEDED,
-
- IDS_DBGSESSION_ERR_SHARED_DATA_ADD,
-
- IDS_MI_SHTDWN_ERR_LOG,
- IDS_MI_SHUTDOWN_ERR,
- IDE_MI_SHTDWN_ERR_RESOURCES,
- IDE_MI_SHTDWN_ERR_STREAMSTDIN,
- IDS_MI_SHTDWN_ERR_OS_STDIN_HANDLER,
- IDS_MI_SHTDWN_ERR_STREAMSTDOUT,
- IDS_MI_SHTDWN_ERR_STREAMSTDERR,
- IDS_MI_SHTDWN_ERR_THREADMGR,
- IDS_MI_SHTDWN_ERR_CMDINTERPRETER,
- IDS_MI_SHTDWN_ERR_CMDMGR,
- IDS_MI_SHTDWN_ERR_CMDFACTORY,
- IDS_MI_SHTDWN_ERR_CMDINVOKER,
- IDS_MI_SHTDWN_ERR_CMDMONITOR,
- IDS_MI_SHTDWN_ERR_LLDBDEBUGGER,
- IDS_MI_SHTDWN_ERR_DRIVERMGR,
- IDS_MI_SHTDWN_ERR_DRIVER,
- IDS_MI_SHTDWN_ERR_OUTOFBANDHANDLER,
- IDS_MI_SHTDWN_ERR_DEBUGSESSIONINFO,
- IDE_MI_SHTDWN_ERR_THREADMANAGER,
-
- IDS_DRIVER_ERR_PARSE_ARGS,
- IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN,
- IDS_DRIVER_ERR_CURRENT_NOT_SET,
- IDS_DRIVER_ERR_NON_REGISTERED,
- IDS_DRIVER_SAY_DRIVER_USING,
- IDS_DRIVER_ERR_ID_INVALID,
- IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR,
- IDS_DRIVER_CMD_RECEIVED,
- IDS_DRIVER_CMD_NOT_IN_FACTORY,
- IDS_DRIVER_ERR_DRIVER_STATE_ERROR,
- IDS_DRIVER_ERR_MAINLOOP,
- IDS_DRIVER_ERR_LOCAL_DEBUG_NOT_IMPL,
- IDS_DRIVER_ERR_LOCAL_DEBUG_INIT,
-
- IDS_DRIVER_WAITING_STDIN_DATA,
-
- IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN,
-
- IDS_CMD_ARGS_ERR_OPTION_NOT_FOUND,
- IDS_CMD_ARGS_ERR_VALIDATION_MANDATORY,
- IDS_CMD_ARGS_ERR_VALIDATION_INVALID,
- IDS_CMD_ARGS_ERR_VALIDATION_MAN_INVALID,
- IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF,
- IDS_CMD_ARGS_ERR_CONTEXT_NOT_ALL_EATTEN,
- IDS_CMD_ARGS_ERR_PREFIX_MSG,
-
- IDS_VARIANT_ERR_USED_BASECLASS,
- IDS_VARIANT_ERR_MAP_KEY_INVALID,
-
- IDS_WORD_INVALIDBRKTS,
- IDS_WORD_NONE,
- IDS_WORD_NOT,
- IDS_WORD_INVALIDEMPTY,
- IDS_WORD_INVALIDNULLPTR,
- IDS_WORD_UNKNOWNBRKTS,
- IDS_WORD_NOT_IMPLEMENTED,
- IDS_WORD_NOT_IMPLEMENTED_BRKTS,
- IDS_WORD_UNKNOWNTYPE_BRKTS,
- IDS_WORD_ERR_MSG_NOT_IMPLEMENTED_BRKTS,
-
- IDS_CMD_ERR_N_OPTIONS_REQUIRED,
- IDS_CMD_ERR_OPTION_NOT_FOUND,
- IDS_CMD_ERR_ARGS,
- IDS_CMD_WRN_ARGS_NOT_HANDLED,
- IDS_CMD_ERR_FNFAILED,
- IDS_CMD_ERR_SHARED_DATA_NOT_FOUND,
- IDS_CMD_ERR_LLDBPROCESS_DETACH,
- IDS_CMD_ERR_LLDBPROCESS_DESTROY,
- IDS_CMD_ERR_SETWKDIR,
- IDS_CMD_ERR_INVALID_TARGET,
- IDS_CMD_ERR_INVALID_TARGET_CURRENT,
- IDS_CMD_ERR_INVALID_TARGET_TYPE,
- IDS_CMD_ERR_INVALID_TARGET_PLUGIN,
- IDS_CMD_ERR_CONNECT_TO_TARGET,
- IDS_CMD_ERR_INVALID_TARGETPLUGINCURRENT,
- IDS_CMD_ERR_NOT_IMPLEMENTED,
- IDS_CMD_ERR_NOT_IMPLEMENTED_DEPRECATED,
- IDS_CMD_ERR_CREATE_TARGET,
- IDS_CMD_ERR_BRKPT_LOCATION_FORMAT,
- IDS_CMD_ERR_BRKPT_LOCATION_NOT_FOUND,
- IDS_CMD_ERR_BRKPT_INVALID,
- IDS_CMD_ERR_BRKPT_CNT_EXCEEDED,
- IDS_CMD_ERR_SOME_ERROR,
- IDS_CMD_ERR_THREAD_INVALID,
- IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID,
- IDS_CMD_ERR_FRAME_INVALID,
- IDS_CMD_ERR_VARIABLE_DOESNOTEXIST,
- IDS_CMD_ERR_VARIABLE_ENUM_INVALID,
- IDS_CMD_ERR_VARIABLE_EXPRESSIONPATH,
- IDS_CMD_ERR_VARIABLE_CREATION_FAILED,
- IDS_CMD_ERR_VARIABLE_CHILD_RANGE_INVALID,
- IDS_CMD_ERR_CMD_RUN_BUT_NO_ACTION,
- IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION,
- IDS_CMD_ERR_DISASM_ADDR_START_INVALID,
- IDS_CMD_ERR_DISASM_ADDR_END_INVALID,
- IDS_CMD_ERR_MEMORY_ALLOC_FAILURE,
- IDS_CMD_ERR_LLDB_ERR_NOT_READ_WHOLE_BLK,
- IDS_CMD_ERR_LLDB_ERR_READ_MEM_BYTES,
- IDS_CMD_ERR_INVALID_PROCESS,
- IDS_CMD_ERR_INVALID_PRINT_VALUES,
- IDS_CMD_ERR_INVALID_LOCATION_FORMAT,
- IDS_CMD_ERR_INVALID_FORMAT_TYPE,
- IDS_CMD_ERR_BRKPT_INFO_OBJ_NOT_FOUND,
- IDS_CMD_ERR_LLDB_ERR_WRITE_MEM_BYTES,
- IDS_CMD_ERR_LLDB_ERR_NOT_WRITE_WHOLEBLK,
- IDS_CMD_ERR_SET_NEW_DRIVER_STATE,
- IDS_CMD_ERR_INFO_PRINTFN_NOT_FOUND,
- IDS_CMD_ERR_INFO_PRINTFN_FAILED,
- IDS_CMD_ERR_GDBSET_OPT_TARGETASYNC,
- IDS_CMD_ERR_GDBSET_OPT_SOLIBSEARCHPATH,
- IDS_CMD_ERR_GDBSET_OPT_PRINT_BAD_ARGS,
- IDS_CMD_ERR_GDBSET_OPT_PRINT_UNKNOWN_OPTION,
- IDS_CMD_ERR_GDBSHOW_OPT_PRINT_BAD_ARGS,
- IDS_CMD_ERR_GDBSHOW_OPT_PRINT_UNKNOWN_OPTION,
- IDS_CMD_ERR_EXPR_INVALID,
- IDS_CMD_ERR_ATTACH_FAILED,
- IDS_CMD_ERR_ATTACH_BAD_ARGS
+enum {
+ IDS_PROJNAME = 1,
+ IDS_MI_VERSION_DESCRIPTION_DEBUG,
+ IDS_MI_VERSION_DESCRIPTION,
+ IDS_MI_APPNAME_SHORT,
+ IDS_MI_APPNAME_LONG,
+ IDS_MI_APP_FILEPATHNAME,
+ IDS_MI_APP_ARGS,
+ IDE_MI_VERSION_GDB,
+
+ IDS_UTIL_FILE_ERR_INVALID_PATHNAME,
+ IDS_UTIL_FILE_ERR_OPENING_FILE,
+ IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN,
+ IDE_UTIL_FILE_ERR_WRITING_FILE,
+ IDE_UTIL_FILE_ERR_WRITING_NOTOPEN,
+
+ IDS_RESOURCES_ERR_STRING_NOT_FOUND,
+ IDS_RESOURCES_ERR_STRING_TABLE_INVALID,
+
+ IDS_MI_CLIENT_MSG,
+
+ IDS_LOG_MSG_CREATION_DATE,
+ IDS_LOG_MSG_FILE_LOGGER_PATH,
+ IDS_LOG_MSG_VERSION,
+ IDS_LOG_ERR_FILE_LOGGER_DISABLED,
+ IDS_LOG_MEDIUM_ERR_INIT,
+ IDS_LOG_MEDIUM_ERR_WRITE_ANY,
+ IDS_LOG_MEDIUM_ERR_WRITE_MEDIUMFAIL,
+
+ IDS_MEDIUMFILE_NAME,
+ IDS_MEDIUMFILE_ERR_INVALID_PATH,
+ IDS_MEDIUMFILE_ERR_FILE_HEADER,
+ IDS_MEDIUMFILE_NAME_LOG,
+
+ IDE_OS_ERR_UNKNOWN,
+ IDE_OS_ERR_RETRIEVING,
+
+ IDS_DRIVERMGR_DRIVER_ERR_INIT,
+
+ IDE_MEDIUMSTDERR_NAME,
+ IDE_MEDIUMSTDOUT_NAME,
+
+ IDE_MI_APP_DESCRIPTION,
+ IDE_MI_APP_INFORMATION,
+ IDE_MI_APP_ARG_USAGE,
+ IDE_MI_APP_ARG_HELP,
+ IDE_MI_APP_ARG_VERSION,
+ IDE_MI_APP_ARG_VERSION_LONG,
+ IDE_MI_APP_ARG_INTERPRETER,
+ IDE_MI_APP_ARG_EXECUTEABLE,
+ IDE_MI_APP_ARG_SOURCE,
+ IDE_MI_APP_ARG_APP_LOG,
+ IDE_MI_APP_ARG_APP_LOG_DIR,
+ IDE_MI_APP_ARG_EXAMPLE,
+ IDE_MI_APP_ARG_EXECUTABLE,
+
+ IDS_STDIN_ERR_INVALID_PROMPT,
+ IDS_STDIN_ERR_THREAD_CREATION_FAILED,
+ IDS_STDIN_ERR_THREAD_DELETE,
+ IDS_STDIN_ERR_CHKING_BYTE_AVAILABLE,
+ IDS_STDIN_INPUT_CTRL_CHARS,
+
+ IDS_CMD_QUIT_HELP,
+
+ IDS_THREADMGR_ERR_THREAD_ID_INVALID,
+ IDS_THREADMGR_ERR_THREAD_FAIL_CREATE,
+ IDS_THREADMGR_ERR_THREAD_ID_NOT_FOUND,
+ IDS_THREADMGR_ERR_THREAD_STILL_ALIVE,
+
+ IDS_FALLTHRU_DRIVER_CMD_RECEIVED,
+
+ IDS_CMDFACTORY_ERR_INVALID_CMD_NAME,
+ IDS_CMDFACTORY_ERR_INVALID_CMD_CR8FN,
+ IDS_CMDFACTORY_ERR_CMD_NOT_REGISTERED,
+ IDS_CMDFACTORY_ERR_CMD_ALREADY_REGED,
+
+ IDS_CMDMGR_ERR_CMD_FAILED_CREATE,
+ IDS_CMDMGR_ERR_CMD_INVOKER,
+
+ IDS_MI_INIT_ERR_LOG,
+ IDS_MI_INIT_ERR_RESOURCES,
+ IDS_MI_INIT_ERR_INIT,
+ IDS_MI_INIT_ERR_STREAMSTDIN,
+ IDS_MI_INIT_ERR_STREAMSTDIN_OSHANDLER,
+ IDS_MI_INIT_ERR_OS_STDIN_HANDLER,
+ IDS_MI_INIT_ERR_STREAMSTDOUT,
+ IDS_MI_INIT_ERR_STREAMSTDERR,
+ IDS_MI_INIT_ERR_FALLTHRUDRIVER,
+ IDS_MI_INIT_ERR_THREADMGR,
+ IDS_MI_INIT_ERR_CMDINTERPRETER,
+ IDS_MI_INIT_ERR_CMDMGR,
+ IDS_MI_INIT_ERR_CMDFACTORY,
+ IDS_MI_INIT_ERR_CMDINVOKER,
+ IDS_MI_INIT_ERR_CMDMONITOR,
+ IDS_MI_INIT_ERR_LLDBDEBUGGER,
+ IDS_MI_INIT_ERR_DRIVERMGR,
+ IDS_MI_INIT_ERR_DRIVER,
+ IDS_MI_INIT_ERR_OUTOFBANDHANDLER,
+ IDS_MI_INIT_ERR_DEBUGSESSIONINFO,
+ IDS_MI_INIT_ERR_THREADMANAGER,
+ IDS_MI_INIT_ERR_CLIENT_USING_DRIVER,
+ IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION,
+
+ IDS_CODE_ERR_INVALID_PARAMETER_VALUE,
+ IDS_CODE_ERR_INVALID_PARAM_NULL_POINTER,
+ IDS_CODE_ERR_INVALID_ENUMERATION_VALUE,
+
+ IDS_LLDBDEBUGGER_ERR_INVALIDLISTENER,
+ IDS_LLDBDEBUGGER_ERR_INVALIDDEBUGGER,
+ IDS_LLDBDEBUGGER_ERR_CLIENTDRIVER,
+ IDS_LLDBDEBUGGER_ERR_STARTLISTENER,
+ IDS_LLDBDEBUGGER_ERR_THREADCREATIONFAIL,
+ IDS_LLDBDEBUGGER_ERR_THREAD_DELETE,
+ IDS_LLDBDEBUGGER_ERR_INVALIDBROADCASTER,
+ IDS_LLDBDEBUGGER_ERR_INVALIDCLIENTNAME,
+ IDS_LLDBDEBUGGER_ERR_CLIENTNOTREGISTERED,
+ IDS_LLDBDEBUGGER_ERR_STOPLISTENER,
+ IDS_LLDBDEBUGGER_ERR_BROADCASTER_NAME,
+ IDS_LLDBDEBUGGER_WRN_UNKNOWN_EVENT,
+
+ IDS_LLDBOUTOFBAND_ERR_UNKNOWN_EVENT,
+ IDS_LLDBOUTOFBAND_ERR_PROCESS_INVALID,
+ IDS_LLDBOUTOFBAND_ERR_BRKPT_NOTFOUND,
+ IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_GET,
+ IDS_LLDBOUTOFBAND_ERR_BRKPT_INFO_SET,
+ IDS_LLDBOUTOFBAND_ERR_FORM_MI_RESPONSE,
+ IDS_LLDBOUTOFBAND_ERR_FRAME_INFO_GET,
+ IDS_LLDBOUTOFBAND_ERR_SETNEWDRIVERSTATE,
+ IDS_LLDBOUTOFBAND_ERR_BRKPT_CNT_EXCEEDED,
+
+ IDS_DBGSESSION_ERR_SHARED_DATA_ADD,
+
+ IDS_MI_SHTDWN_ERR_LOG,
+ IDS_MI_SHUTDOWN_ERR,
+ IDE_MI_SHTDWN_ERR_RESOURCES,
+ IDE_MI_SHTDWN_ERR_STREAMSTDIN,
+ IDS_MI_SHTDWN_ERR_OS_STDIN_HANDLER,
+ IDS_MI_SHTDWN_ERR_STREAMSTDOUT,
+ IDS_MI_SHTDWN_ERR_STREAMSTDERR,
+ IDS_MI_SHTDWN_ERR_THREADMGR,
+ IDS_MI_SHTDWN_ERR_CMDINTERPRETER,
+ IDS_MI_SHTDWN_ERR_CMDMGR,
+ IDS_MI_SHTDWN_ERR_CMDFACTORY,
+ IDS_MI_SHTDWN_ERR_CMDINVOKER,
+ IDS_MI_SHTDWN_ERR_CMDMONITOR,
+ IDS_MI_SHTDWN_ERR_LLDBDEBUGGER,
+ IDS_MI_SHTDWN_ERR_DRIVERMGR,
+ IDS_MI_SHTDWN_ERR_DRIVER,
+ IDS_MI_SHTDWN_ERR_OUTOFBANDHANDLER,
+ IDS_MI_SHTDWN_ERR_DEBUGSESSIONINFO,
+ IDE_MI_SHTDWN_ERR_THREADMANAGER,
+
+ IDS_DRIVER_ERR_PARSE_ARGS,
+ IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN,
+ IDS_DRIVER_ERR_CURRENT_NOT_SET,
+ IDS_DRIVER_ERR_NON_REGISTERED,
+ IDS_DRIVER_SAY_DRIVER_USING,
+ IDS_DRIVER_ERR_ID_INVALID,
+ IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR,
+ IDS_DRIVER_CMD_RECEIVED,
+ IDS_DRIVER_CMD_NOT_IN_FACTORY,
+ IDS_DRIVER_ERR_DRIVER_STATE_ERROR,
+ IDS_DRIVER_ERR_MAINLOOP,
+ IDS_DRIVER_ERR_LOCAL_DEBUG_NOT_IMPL,
+ IDS_DRIVER_ERR_LOCAL_DEBUG_INIT,
+
+ IDS_DRIVER_WAITING_STDIN_DATA,
+
+ IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN,
+
+ IDS_CMD_ARGS_ERR_OPTION_NOT_FOUND,
+ IDS_CMD_ARGS_ERR_VALIDATION_MANDATORY,
+ IDS_CMD_ARGS_ERR_VALIDATION_INVALID,
+ IDS_CMD_ARGS_ERR_VALIDATION_MAN_INVALID,
+ IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF,
+ IDS_CMD_ARGS_ERR_CONTEXT_NOT_ALL_EATTEN,
+ IDS_CMD_ARGS_ERR_PREFIX_MSG,
+
+ IDS_VARIANT_ERR_USED_BASECLASS,
+ IDS_VARIANT_ERR_MAP_KEY_INVALID,
+
+ IDS_WORD_INVALIDBRKTS,
+ IDS_WORD_NONE,
+ IDS_WORD_NOT,
+ IDS_WORD_INVALIDEMPTY,
+ IDS_WORD_INVALIDNULLPTR,
+ IDS_WORD_UNKNOWNBRKTS,
+ IDS_WORD_NOT_IMPLEMENTED,
+ IDS_WORD_NOT_IMPLEMENTED_BRKTS,
+ IDS_WORD_UNKNOWNTYPE_BRKTS,
+ IDS_WORD_ERR_MSG_NOT_IMPLEMENTED_BRKTS,
+
+ IDS_CMD_ERR_N_OPTIONS_REQUIRED,
+ IDS_CMD_ERR_OPTION_NOT_FOUND,
+ IDS_CMD_ERR_ARGS,
+ IDS_CMD_WRN_ARGS_NOT_HANDLED,
+ IDS_CMD_ERR_FNFAILED,
+ IDS_CMD_ERR_SHARED_DATA_NOT_FOUND,
+ IDS_CMD_ERR_LLDBPROCESS_DETACH,
+ IDS_CMD_ERR_LLDBPROCESS_DESTROY,
+ IDS_CMD_ERR_SETWKDIR,
+ IDS_CMD_ERR_INVALID_TARGET,
+ IDS_CMD_ERR_INVALID_TARGET_CURRENT,
+ IDS_CMD_ERR_INVALID_TARGET_TYPE,
+ IDS_CMD_ERR_INVALID_TARGET_PLUGIN,
+ IDS_CMD_ERR_CONNECT_TO_TARGET,
+ IDS_CMD_ERR_INVALID_TARGETPLUGINCURRENT,
+ IDS_CMD_ERR_NOT_IMPLEMENTED,
+ IDS_CMD_ERR_NOT_IMPLEMENTED_DEPRECATED,
+ IDS_CMD_ERR_CREATE_TARGET,
+ IDS_CMD_ERR_BRKPT_LOCATION_FORMAT,
+ IDS_CMD_ERR_BRKPT_LOCATION_NOT_FOUND,
+ IDS_CMD_ERR_BRKPT_INVALID,
+ IDS_CMD_ERR_BRKPT_CNT_EXCEEDED,
+ IDS_CMD_ERR_SOME_ERROR,
+ IDS_CMD_ERR_THREAD_INVALID,
+ IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID,
+ IDS_CMD_ERR_FRAME_INVALID,
+ IDS_CMD_ERR_VARIABLE_DOESNOTEXIST,
+ IDS_CMD_ERR_VARIABLE_ENUM_INVALID,
+ IDS_CMD_ERR_VARIABLE_EXPRESSIONPATH,
+ IDS_CMD_ERR_VARIABLE_CREATION_FAILED,
+ IDS_CMD_ERR_VARIABLE_CHILD_RANGE_INVALID,
+ IDS_CMD_ERR_CMD_RUN_BUT_NO_ACTION,
+ IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION,
+ IDS_CMD_ERR_DISASM_ADDR_START_INVALID,
+ IDS_CMD_ERR_DISASM_ADDR_END_INVALID,
+ IDS_CMD_ERR_MEMORY_ALLOC_FAILURE,
+ IDS_CMD_ERR_LLDB_ERR_NOT_READ_WHOLE_BLK,
+ IDS_CMD_ERR_LLDB_ERR_READ_MEM_BYTES,
+ IDS_CMD_ERR_INVALID_PROCESS,
+ IDS_CMD_ERR_INVALID_PRINT_VALUES,
+ IDS_CMD_ERR_INVALID_LOCATION_FORMAT,
+ IDS_CMD_ERR_INVALID_FORMAT_TYPE,
+ IDS_CMD_ERR_BRKPT_INFO_OBJ_NOT_FOUND,
+ IDS_CMD_ERR_LLDB_ERR_WRITE_MEM_BYTES,
+ IDS_CMD_ERR_LLDB_ERR_NOT_WRITE_WHOLEBLK,
+ IDS_CMD_ERR_SET_NEW_DRIVER_STATE,
+ IDS_CMD_ERR_INFO_PRINTFN_NOT_FOUND,
+ IDS_CMD_ERR_INFO_PRINTFN_FAILED,
+ IDS_CMD_ERR_GDBSET_OPT_TARGETASYNC,
+ IDS_CMD_ERR_GDBSET_OPT_SOLIBSEARCHPATH,
+ IDS_CMD_ERR_GDBSET_OPT_PRINT_BAD_ARGS,
+ IDS_CMD_ERR_GDBSET_OPT_PRINT_UNKNOWN_OPTION,
+ IDS_CMD_ERR_GDBSHOW_OPT_PRINT_BAD_ARGS,
+ IDS_CMD_ERR_GDBSHOW_OPT_PRINT_UNKNOWN_OPTION,
+ IDS_CMD_ERR_EXPR_INVALID,
+ IDS_CMD_ERR_ATTACH_FAILED,
+ IDS_CMD_ERR_ATTACH_BAD_ARGS
};
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code implementation class. Handle application resources
// and locality.
// Singleton class.
//--
-class CMICmnResources : public CMICmnBase, public MI::ISingleton<CMICmnResources>
-{
- friend class MI::ISingleton<CMICmnResources>;
-
- // Methods:
- public:
- bool Initialize() override;
- bool Shutdown() override;
-
- CMIUtilString GetString(const MIuint vResourceId) const;
- bool HasString(const MIuint vResourceId) const;
-
- // Typedef:
- private:
- typedef std::map<MIuint, const char *> MapRscrIdToTextData_t;
- typedef std::pair<MIuint, const char *> MapPairRscrIdToTextData_t;
-
- // Enumerations:
- private:
- enum Buffer_e
- {
- eBufferSize = 2048
- };
-
- // Structs:
- private:
- struct SRsrcTextData
- {
- MIuint id;
- const char *pTextData;
- };
-
- // Methods:
- private:
- /* ctor */ CMICmnResources();
- /* ctor */ CMICmnResources(const CMICmnResources &);
- void operator=(const CMICmnResources &);
-
- bool GetStringFromResource(const MIuint vResourceId, CMIUtilString &vrwResourceString) const;
- bool ReadResourceStringData();
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMICmnResources() override;
-
- // Attributes:
- private:
- static const SRsrcTextData ms_pResourceId2TextData[];
- //
- MIuint m_nResourceId2TextDataSize;
- MapRscrIdToTextData_t m_mapRscrIdToTextData;
+class CMICmnResources : public CMICmnBase,
+ public MI::ISingleton<CMICmnResources> {
+ friend class MI::ISingleton<CMICmnResources>;
+
+ // Methods:
+public:
+ bool Initialize() override;
+ bool Shutdown() override;
+
+ CMIUtilString GetString(const MIuint vResourceId) const;
+ bool HasString(const MIuint vResourceId) const;
+
+ // Typedef:
+private:
+ typedef std::map<MIuint, const char *> MapRscrIdToTextData_t;
+ typedef std::pair<MIuint, const char *> MapPairRscrIdToTextData_t;
+
+ // Enumerations:
+private:
+ enum Buffer_e { eBufferSize = 2048 };
+
+ // Structs:
+private:
+ struct SRsrcTextData {
+ MIuint id;
+ const char *pTextData;
+ };
+
+ // Methods:
+private:
+ /* ctor */ CMICmnResources();
+ /* ctor */ CMICmnResources(const CMICmnResources &);
+ void operator=(const CMICmnResources &);
+
+ bool GetStringFromResource(const MIuint vResourceId,
+ CMIUtilString &vrwResourceString) const;
+ bool ReadResourceStringData();
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnResources() override;
+
+ // Attributes:
+private:
+ static const SRsrcTextData ms_pResourceId2TextData[];
+ //
+ MIuint m_nResourceId2TextDataSize;
+ MapRscrIdToTextData_t m_mapRscrIdToTextData;
};
//++ =========================================================================
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStderr.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStderr.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStderr.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStderr.cpp Tue Sep 6 15:57:50 2016
@@ -1,4 +1,5 @@
-//===-- MICmnStreamStderr.cpp ------------------------------------*- C++ -*-===//
+//===-- MICmnStreamStderr.cpp ------------------------------------*- C++
+//-*-===//
//
// The LLVM Compiler Infrastructure
//
@@ -13,30 +14,28 @@
#include "MICmnResources.h"
#include "MIDriver.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStderr constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnStreamStderr::CMICmnStreamStderr()
-{
-}
+CMICmnStreamStderr::CMICmnStreamStderr() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStderr destructor.
// Type: Overridable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnStreamStderr::~CMICmnStreamStderr()
-{
- Shutdown();
-}
+CMICmnStreamStderr::~CMICmnStreamStderr() { Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize resources for *this stderr stream.
// Type: Method.
// Args: None.
@@ -44,15 +43,13 @@ CMICmnStreamStderr::~CMICmnStreamStderr(
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::Initialize()
-{
- m_clientUsageRefCnt++;
+bool CMICmnStreamStderr::Initialize() {
+ m_clientUsageRefCnt++;
- if (m_bInitialized)
- return MIstatus::success;
+ if (m_bInitialized)
+ return MIstatus::success;
- bool bOk = MIstatus::success;
+ bool bOk = MIstatus::success;
#ifdef _MSC_VER
// Debugging / I/O issues with client.
@@ -62,12 +59,13 @@ CMICmnStreamStderr::Initialize()
//::setbuf( stderr, NULL );
#endif // _MSC_VER
- m_bInitialized = bOk;
+ m_bInitialized = bOk;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resources for *this stderr stream.
// Type: Method.
// Args: None.
@@ -75,114 +73,125 @@ CMICmnStreamStderr::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
+bool CMICmnStreamStderr::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- if (!m_bInitialized)
- return MIstatus::success;
+ if (!m_bInitialized)
+ return MIstatus::success;
- ClrErrorDescription();
+ ClrErrorDescription();
- m_bInitialized = false;
+ m_bInitialized = false;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Write text data to stderr. Prefix the message with "MI:". The text data does
-// not need to include a carriage line return as this is added to the text. The
+//++
+//------------------------------------------------------------------------------------
+// Details: Write text data to stderr. Prefix the message with "MI:". The text
+// data does
+// not need to include a carriage line return as this is added to the
+// text. The
// function also then passes the text data into the CMICmnLog logger.
// Type: Method.
// Args: vText - (R) Text data.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false = do
+// not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::Write(const CMIUtilString &vText, const bool vbSendToLog /* = true */)
-{
- if (vText.length() == 0)
- return MIstatus::failure;
+bool CMICmnStreamStderr::Write(const CMIUtilString &vText,
+ const bool vbSendToLog /* = true */) {
+ if (vText.length() == 0)
+ return MIstatus::failure;
- const CMIUtilString strPrefixed(CMIUtilString::Format("%s: %s", CMIDriver::Instance().GetAppNameShort().c_str(), vText.c_str()));
+ const CMIUtilString strPrefixed(CMIUtilString::Format(
+ "%s: %s", CMIDriver::Instance().GetAppNameShort().c_str(),
+ vText.c_str()));
- return WritePriv(strPrefixed, vText, vbSendToLog);
+ return WritePriv(strPrefixed, vText, vbSendToLog);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write an LLDB text message to stderr.
-// The text data does not need to include a carriage line return as this is added
-// to the text. The function also then passes the text data into the CMICmnLog
+// The text data does not need to include a carriage line return as
+// this is added
+// to the text. The function also then passes the text data into the
+// CMICmnLog
// logger.
// Type: Method.
// Args: vText - (R) Text data.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false = do
+// not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::WriteLLDBMsg(const CMIUtilString &vText, const bool vbSendToLog /* = true */)
-{
- if (vText.length() == 0)
- return MIstatus::failure;
+bool CMICmnStreamStderr::WriteLLDBMsg(const CMIUtilString &vText,
+ const bool vbSendToLog /* = true */) {
+ if (vText.length() == 0)
+ return MIstatus::failure;
- const CMIUtilString strPrefixed(CMIUtilString::Format("LLDB: %s", vText.c_str()));
+ const CMIUtilString strPrefixed(
+ CMIUtilString::Format("LLDB: %s", vText.c_str()));
- return WritePriv(vText, strPrefixed, vbSendToLog);
+ return WritePriv(vText, strPrefixed, vbSendToLog);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write text data to stderr. The text data does not need to
-// include a carriage line return as this is added to the text. The function also
+// include a carriage line return as this is added to the text. The
+// function also
// then passes the text data into the CMICmnLog logger.
// Type: Method.
-// Args: vText - (R) Text data. May be prefixed with MI app's short name.
+// Args: vText - (R) Text data. May be prefixed with MI app's short
+// name.
// vTxtForLogFile - (R) Text data.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false =
+// do not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::WritePriv(const CMIUtilString &vText, const CMIUtilString &vTxtForLogFile, const bool vbSendToLog /* = true */)
-{
- if (vText.length() == 0)
- return MIstatus::failure;
-
- bool bOk = MIstatus::success;
- {
- // Grab the stderr thread lock while we print
- CMIUtilThreadLock _lock(m_mutex);
-
- // Send this text to stderr
- const MIint status = ::fputs(vText.c_str(), stderr);
- if (status == EOF)
- {
- const CMIUtilString errMsg(CMIUtilString::Format(MIRSRC(IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN), vText.c_str()));
- SetErrorDescription(errMsg);
- bOk = MIstatus::failure;
- }
- else
- {
- ::fprintf(stderr, "\n");
- ::fflush(stderr);
- }
-
- // Send this text to the log
- if (bOk && vbSendToLog)
- bOk &= m_pLog->WriteLog(vTxtForLogFile);
+bool CMICmnStreamStderr::WritePriv(const CMIUtilString &vText,
+ const CMIUtilString &vTxtForLogFile,
+ const bool vbSendToLog /* = true */) {
+ if (vText.length() == 0)
+ return MIstatus::failure;
+
+ bool bOk = MIstatus::success;
+ {
+ // Grab the stderr thread lock while we print
+ CMIUtilThreadLock _lock(m_mutex);
+
+ // Send this text to stderr
+ const MIint status = ::fputs(vText.c_str(), stderr);
+ if (status == EOF) {
+ const CMIUtilString errMsg(CMIUtilString::Format(
+ MIRSRC(IDS_STDERR_ERR_NOT_ALL_DATA_WRITTEN), vText.c_str()));
+ SetErrorDescription(errMsg);
+ bOk = MIstatus::failure;
+ } else {
+ ::fprintf(stderr, "\n");
+ ::fflush(stderr);
}
- return bOk;
+ // Send this text to the log
+ if (bOk && vbSendToLog)
+ bOk &= m_pLog->WriteLog(vTxtForLogFile);
+ }
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Lock the availability of the stream stderr. Other users of *this stream will
+//++
+//------------------------------------------------------------------------------------
+// Details: Lock the availability of the stream stderr. Other users of *this
+// stream will
// be stalled until it is available (Unlock()).
// Type: Method.
// Args: None.
@@ -190,14 +199,13 @@ CMICmnStreamStderr::WritePriv(const CMIU
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::Lock()
-{
- m_mutex.Lock();
- return MIstatus::success;
+bool CMICmnStreamStderr::Lock() {
+ m_mutex.Lock();
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release a previously locked stderr.
// Type: Method.
// Args: None.
@@ -205,15 +213,15 @@ CMICmnStreamStderr::Lock()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::Unlock()
-{
- m_mutex.Unlock();
- return MIstatus::success;
+bool CMICmnStreamStderr::Unlock() {
+ m_mutex.Unlock();
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Take MI Driver text message and send to the stderr stream. Also output to the
+//++
+//------------------------------------------------------------------------------------
+// Details: Take MI Driver text message and send to the stderr stream. Also
+// output to the
// MI Log file.
// Type: Static method.
// Args: vrTxt - (R) Text.
@@ -221,20 +229,22 @@ CMICmnStreamStderr::Unlock()
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::TextToStderr(const CMIUtilString &vrTxt)
-{
- const bool bLock = CMICmnStreamStderr::Instance().Lock();
- const bool bOk = bLock && CMICmnStreamStderr::Instance().Write(vrTxt);
- bLock &&CMICmnStreamStderr::Instance().Unlock();
-
- return bOk;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Take an LLDB message and send to the stderr stream. The message is not always
-// an error message. The user has typed a command in to the Eclipse console (by-
-// passing Eclipse) and this is the result message from LLDB back to the user.
+bool CMICmnStreamStderr::TextToStderr(const CMIUtilString &vrTxt) {
+ const bool bLock = CMICmnStreamStderr::Instance().Lock();
+ const bool bOk = bLock && CMICmnStreamStderr::Instance().Write(vrTxt);
+ bLock &&CMICmnStreamStderr::Instance().Unlock();
+
+ return bOk;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Take an LLDB message and send to the stderr stream. The message is
+// not always
+// an error message. The user has typed a command in to the Eclipse
+// console (by-
+// passing Eclipse) and this is the result message from LLDB back to
+// the user.
// Also output to the MI Log file.
// Type: Static method.
// Args: vrTxt - (R) Text.
@@ -242,12 +252,10 @@ CMICmnStreamStderr::TextToStderr(const C
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMICmnStreamStderr::LLDBMsgToConsole(const CMIUtilString &vrTxt)
-{
- const bool bLock = CMICmnStreamStderr::Instance().Lock();
- const bool bOk = bLock && CMICmnStreamStderr::Instance().WriteLLDBMsg(vrTxt);
- bLock &&CMICmnStreamStderr::Instance().Unlock();
+bool CMICmnStreamStderr::LLDBMsgToConsole(const CMIUtilString &vrTxt) {
+ const bool bLock = CMICmnStreamStderr::Instance().Lock();
+ const bool bOk = bLock && CMICmnStreamStderr::Instance().WriteLLDBMsg(vrTxt);
+ bLock &&CMICmnStreamStderr::Instance().Unlock();
- return bOk;
+ return bOk;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStderr.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStderr.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStderr.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStderr.h Tue Sep 6 15:57:50 2016
@@ -10,50 +10,53 @@
#pragma once
// In-house headers:
-#include "MIUtilString.h"
#include "MICmnBase.h"
#include "MIUtilSingletonBase.h"
+#include "MIUtilString.h"
#include "MIUtilThreadBaseStd.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code class. The MI driver requires this object.
// CMICmnStreamStderr sets up and tears downs stderr for the driver.
//
// Singleton class.
//--
-class CMICmnStreamStderr : public CMICmnBase, public MI::ISingleton<CMICmnStreamStderr>
-{
- friend class MI::ISingleton<CMICmnStreamStderr>;
-
- // Statics:
- public:
- static bool TextToStderr(const CMIUtilString &vrTxt);
- static bool LLDBMsgToConsole(const CMIUtilString &vrTxt);
-
- // Methods:
- public:
- bool Initialize() override;
- bool Shutdown() override;
- //
- bool Lock();
- bool Unlock();
- bool Write(const CMIUtilString &vText, const bool vbSendToLog = true);
- bool WriteLLDBMsg(const CMIUtilString &vText, const bool vbSendToLog = true);
-
- // Methods:
- private:
- /* ctor */ CMICmnStreamStderr();
- /* ctor */ CMICmnStreamStderr(const CMICmnStreamStderr &);
- void operator=(const CMICmnStreamStderr &);
- //
- bool WritePriv(const CMIUtilString &vText, const CMIUtilString &vTxtForLogFile, const bool vbSendToLog = true);
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMICmnStreamStderr() override;
-
- // Attributes:
- private:
- CMIUtilThreadMutex m_mutex; // Mutex object for sync during Write()
+class CMICmnStreamStderr : public CMICmnBase,
+ public MI::ISingleton<CMICmnStreamStderr> {
+ friend class MI::ISingleton<CMICmnStreamStderr>;
+
+ // Statics:
+public:
+ static bool TextToStderr(const CMIUtilString &vrTxt);
+ static bool LLDBMsgToConsole(const CMIUtilString &vrTxt);
+
+ // Methods:
+public:
+ bool Initialize() override;
+ bool Shutdown() override;
+ //
+ bool Lock();
+ bool Unlock();
+ bool Write(const CMIUtilString &vText, const bool vbSendToLog = true);
+ bool WriteLLDBMsg(const CMIUtilString &vText, const bool vbSendToLog = true);
+
+ // Methods:
+private:
+ /* ctor */ CMICmnStreamStderr();
+ /* ctor */ CMICmnStreamStderr(const CMICmnStreamStderr &);
+ void operator=(const CMICmnStreamStderr &);
+ //
+ bool WritePriv(const CMIUtilString &vText,
+ const CMIUtilString &vTxtForLogFile,
+ const bool vbSendToLog = true);
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnStreamStderr() override;
+
+ // Attributes:
+private:
+ CMIUtilThreadMutex m_mutex; // Mutex object for sync during Write()
};
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStdin.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStdin.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStdin.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStdin.cpp Tue Sep 6 15:57:50 2016
@@ -14,14 +14,15 @@
#include <string.h> // For std::strerror()
// In-house headers:
+#include "MICmnLog.h"
+#include "MICmnResources.h"
#include "MICmnStreamStdin.h"
#include "MICmnStreamStdout.h"
-#include "MICmnResources.h"
-#include "MICmnLog.h"
#include "MIDriver.h"
#include "MIUtilSingletonHelper.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStdin constructor.
// Type: Method.
// Args: None.
@@ -29,25 +30,20 @@
// Throws: None.
//--
CMICmnStreamStdin::CMICmnStreamStdin()
- : m_strPromptCurrent("(gdb)")
- , m_bShowPrompt(true)
- , m_pCmdBuffer(nullptr)
-{
-}
+ : m_strPromptCurrent("(gdb)"), m_bShowPrompt(true), m_pCmdBuffer(nullptr) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStdin destructor.
// Type: Overridable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnStreamStdin::~CMICmnStreamStdin()
-{
- Shutdown();
-}
+CMICmnStreamStdin::~CMICmnStreamStdin() { Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize resources for *this Stdin stream.
// Type: Method.
// Args: None.
@@ -55,38 +51,36 @@ CMICmnStreamStdin::~CMICmnStreamStdin()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdin::Initialize()
-{
- m_clientUsageRefCnt++;
-
- if (m_bInitialized)
- return MIstatus::success;
-
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
-
- // Note initialisation order is important here as some resources depend on previous
- MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
- MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
-
- if (bOk)
- {
- m_pCmdBuffer = new char[m_constBufferSize];
- }
- else
- {
- CMIUtilString strInitError(CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_STREAMSTDIN), errMsg.c_str()));
- SetErrorDescription(strInitError);
-
- return MIstatus::failure;
- }
- m_bInitialized = bOk;
+bool CMICmnStreamStdin::Initialize() {
+ m_clientUsageRefCnt++;
+ if (m_bInitialized)
return MIstatus::success;
+
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
+
+ // Note initialisation order is important here as some resources depend on
+ // previous
+ MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
+ MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
+
+ if (bOk) {
+ m_pCmdBuffer = new char[m_constBufferSize];
+ } else {
+ CMIUtilString strInitError(CMIUtilString::Format(
+ MIRSRC(IDS_MI_INIT_ERR_STREAMSTDIN), errMsg.c_str()));
+ SetErrorDescription(strInitError);
+
+ return MIstatus::failure;
+ }
+ m_bInitialized = bOk;
+
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resources for *this Stdin stream.
// Type: Method.
// Args: None.
@@ -94,40 +88,37 @@ CMICmnStreamStdin::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdin::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
-
- if (!m_bInitialized)
- return MIstatus::success;
-
- m_bInitialized = false;
-
- ClrErrorDescription();
-
- if (m_pCmdBuffer != nullptr)
- {
- delete[] m_pCmdBuffer;
- m_pCmdBuffer = nullptr;
- }
+bool CMICmnStreamStdin::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
+ if (!m_bInitialized)
+ return MIstatus::success;
- MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
- MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
+ m_bInitialized = false;
- if (!bOk)
- {
- SetErrorDescriptionn(MIRSRC(IDE_MI_SHTDWN_ERR_STREAMSTDIN), errMsg.c_str());
- }
+ ClrErrorDescription();
- return MIstatus::success;
+ if (m_pCmdBuffer != nullptr) {
+ delete[] m_pCmdBuffer;
+ m_pCmdBuffer = nullptr;
+ }
+
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
+
+ MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
+ MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
+
+ if (!bOk) {
+ SetErrorDescriptionn(MIRSRC(IDE_MI_SHTDWN_ERR_STREAMSTDIN), errMsg.c_str());
+ }
+
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Validate and set the text that forms the prompt on the command line.
// Type: Method.
// Args: vNewPrompt - (R) Text description.
@@ -135,107 +126,103 @@ CMICmnStreamStdin::Shutdown()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdin::SetPrompt(const CMIUtilString &vNewPrompt)
-{
- if (vNewPrompt.empty())
- {
- const CMIUtilString msg(CMIUtilString::Format(MIRSRC(IDS_STDIN_ERR_INVALID_PROMPT), vNewPrompt.c_str()));
- CMICmnStreamStdout::Instance().Write(msg);
- return MIstatus::failure;
- }
+bool CMICmnStreamStdin::SetPrompt(const CMIUtilString &vNewPrompt) {
+ if (vNewPrompt.empty()) {
+ const CMIUtilString msg(CMIUtilString::Format(
+ MIRSRC(IDS_STDIN_ERR_INVALID_PROMPT), vNewPrompt.c_str()));
+ CMICmnStreamStdout::Instance().Write(msg);
+ return MIstatus::failure;
+ }
- m_strPromptCurrent = vNewPrompt;
+ m_strPromptCurrent = vNewPrompt;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the command line prompt text currently being used.
// Type: Method.
// Args: None.
// Return: const CMIUtilString & - Functional failed.
// Throws: None.
//--
-const CMIUtilString &
-CMICmnStreamStdin::GetPrompt() const
-{
- return m_strPromptCurrent;
+const CMIUtilString &CMICmnStreamStdin::GetPrompt() const {
+ return m_strPromptCurrent;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set whether to display optional command line prompt. The prompt is output to
-// stdout. Disable it when this may interfere with the client reading stdout as
+//++
+//------------------------------------------------------------------------------------
+// Details: Set whether to display optional command line prompt. The prompt is
+// output to
+// stdout. Disable it when this may interfere with the client reading
+// stdout as
// input and it tries to interpret the prompt text to.
// Type: Method.
-// Args: vbYes - (R) True = Yes prompt is shown/output to the user (stdout), false = no prompt.
+// Args: vbYes - (R) True = Yes prompt is shown/output to the user
+// (stdout), false = no prompt.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-void
-CMICmnStreamStdin::SetEnablePrompt(const bool vbYes)
-{
- m_bShowPrompt = vbYes;
+void CMICmnStreamStdin::SetEnablePrompt(const bool vbYes) {
+ m_bShowPrompt = vbYes;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Get whether to display optional command line prompt. The prompt is output to
-// stdout. Disable it when this may interfere with the client reading stdout as
+//++
+//------------------------------------------------------------------------------------
+// Details: Get whether to display optional command line prompt. The prompt is
+// output to
+// stdout. Disable it when this may interfere with the client reading
+// stdout as
// input and it tries to interpret the prompt text to.
// Type: Method.
// Args: None.
-// Return: bool - True = Yes prompt is shown/output to the user (stdout), false = no prompt.
+// Return: bool - True = Yes prompt is shown/output to the user (stdout), false
+// = no prompt.
// Throws: None.
//--
-bool
-CMICmnStreamStdin::GetEnablePrompt() const
-{
- return m_bShowPrompt;
-}
+bool CMICmnStreamStdin::GetEnablePrompt() const { return m_bShowPrompt; }
-//++ ------------------------------------------------------------------------------------
-// Details: Wait on new line of data from stdin stream (completed by '\n' or '\r').
+//++
+//------------------------------------------------------------------------------------
+// Details: Wait on new line of data from stdin stream (completed by '\n' or
+// '\r').
// Type: Method.
// Args: vwErrMsg - (W) Empty string ok or error description.
// Return: char * - text buffer pointer or NULL on failure.
// Throws: None.
//--
-const char *
-CMICmnStreamStdin::ReadLine(CMIUtilString &vwErrMsg)
-{
- vwErrMsg.clear();
-
- // Read user input
- const char *pText = ::fgets(&m_pCmdBuffer[0], m_constBufferSize, stdin);
- if (pText == nullptr)
- {
+const char *CMICmnStreamStdin::ReadLine(CMIUtilString &vwErrMsg) {
+ vwErrMsg.clear();
+
+ // Read user input
+ const char *pText = ::fgets(&m_pCmdBuffer[0], m_constBufferSize, stdin);
+ if (pText == nullptr) {
#ifdef _MSC_VER
- // Was Ctrl-C hit?
- // On Windows, Ctrl-C gives an ERROR_OPERATION_ABORTED as error on the command-line.
- // The end-of-file indicator is also set, so without this check we will exit next if statement.
- if (::GetLastError() == ERROR_OPERATION_ABORTED)
- return nullptr;
+ // Was Ctrl-C hit?
+ // On Windows, Ctrl-C gives an ERROR_OPERATION_ABORTED as error on the
+ // command-line.
+ // The end-of-file indicator is also set, so without this check we will exit
+ // next if statement.
+ if (::GetLastError() == ERROR_OPERATION_ABORTED)
+ return nullptr;
#endif
- if (::feof(stdin))
- {
- const bool bForceExit = true;
- CMIDriver::Instance().SetExitApplicationFlag(bForceExit);
- }
- else if (::ferror(stdin) != 0)
- vwErrMsg = ::strerror(errno);
- return nullptr;
- }
-
- // Strip off new line characters
- for (char *pI = m_pCmdBuffer; *pI != '\0'; pI++)
- {
- if ((*pI == '\n') || (*pI == '\r'))
- {
- *pI = '\0';
- break;
- }
+ if (::feof(stdin)) {
+ const bool bForceExit = true;
+ CMIDriver::Instance().SetExitApplicationFlag(bForceExit);
+ } else if (::ferror(stdin) != 0)
+ vwErrMsg = ::strerror(errno);
+ return nullptr;
+ }
+
+ // Strip off new line characters
+ for (char *pI = m_pCmdBuffer; *pI != '\0'; pI++) {
+ if ((*pI == '\n') || (*pI == '\r')) {
+ *pI = '\0';
+ break;
}
+ }
- return pText;
+ return pText;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStdin.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStdin.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStdin.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStdin.h Tue Sep 6 15:57:50 2016
@@ -10,49 +10,52 @@
#pragma once
// In-house headers:
-#include "MIUtilString.h"
-#include "MIUtilThreadBaseStd.h"
#include "MICmnBase.h"
#include "MIUtilSingletonBase.h"
+#include "MIUtilString.h"
+#include "MIUtilThreadBaseStd.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code class. Used to handle stream data from Stdin.
-// Singleton class using the Visitor pattern. A driver using the interface
+// Singleton class using the Visitor pattern. A driver using the
+// interface
// provide can receive callbacks when a new line of data is received.
// Each line is determined by a carriage return.
// A singleton class.
//--
-class CMICmnStreamStdin : public CMICmnBase, public MI::ISingleton<CMICmnStreamStdin>
-{
- // Give singleton access to private constructors
- friend MI::ISingleton<CMICmnStreamStdin>;
-
- // Methods:
- public:
- bool Initialize() override;
- bool Shutdown() override;
- //
- const CMIUtilString &GetPrompt() const;
- bool SetPrompt(const CMIUtilString &vNewPrompt);
- void SetEnablePrompt(const bool vbYes);
- bool GetEnablePrompt() const;
- const char *ReadLine(CMIUtilString &vwErrMsg);
-
- // Methods:
- private:
- /* ctor */ CMICmnStreamStdin();
- /* ctor */ CMICmnStreamStdin(const CMICmnStreamStdin &);
- void operator=(const CMICmnStreamStdin &);
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMICmnStreamStdin() override;
-
- // Attributes:
- private:
- CMIUtilString m_strPromptCurrent; // Command line prompt as shown to the user
- bool m_bShowPrompt; // True = Yes prompt is shown/output to the user (stdout), false = no prompt
- static const int m_constBufferSize = 2048;
- char *m_pCmdBuffer;
+class CMICmnStreamStdin : public CMICmnBase,
+ public MI::ISingleton<CMICmnStreamStdin> {
+ // Give singleton access to private constructors
+ friend MI::ISingleton<CMICmnStreamStdin>;
+
+ // Methods:
+public:
+ bool Initialize() override;
+ bool Shutdown() override;
+ //
+ const CMIUtilString &GetPrompt() const;
+ bool SetPrompt(const CMIUtilString &vNewPrompt);
+ void SetEnablePrompt(const bool vbYes);
+ bool GetEnablePrompt() const;
+ const char *ReadLine(CMIUtilString &vwErrMsg);
+
+ // Methods:
+private:
+ /* ctor */ CMICmnStreamStdin();
+ /* ctor */ CMICmnStreamStdin(const CMICmnStreamStdin &);
+ void operator=(const CMICmnStreamStdin &);
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnStreamStdin() override;
+
+ // Attributes:
+private:
+ CMIUtilString m_strPromptCurrent; // Command line prompt as shown to the user
+ bool m_bShowPrompt; // True = Yes prompt is shown/output to the user (stdout),
+ // false = no prompt
+ static const int m_constBufferSize = 2048;
+ char *m_pCmdBuffer;
};
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStdout.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStdout.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStdout.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStdout.cpp Tue Sep 6 15:57:50 2016
@@ -13,30 +13,28 @@
#include "MICmnResources.h"
#include "MIDriver.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStdout constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnStreamStdout::CMICmnStreamStdout()
-{
-}
+CMICmnStreamStdout::CMICmnStreamStdout() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnStreamStdout destructor.
// Type: Overridable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnStreamStdout::~CMICmnStreamStdout()
-{
- Shutdown();
-}
+CMICmnStreamStdout::~CMICmnStreamStdout() { Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize resources for *this Stdout stream.
// Type: Method.
// Args: None.
@@ -44,15 +42,13 @@ CMICmnStreamStdout::~CMICmnStreamStdout(
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::Initialize()
-{
- m_clientUsageRefCnt++;
+bool CMICmnStreamStdout::Initialize() {
+ m_clientUsageRefCnt++;
- if (m_bInitialized)
- return MIstatus::success;
+ if (m_bInitialized)
+ return MIstatus::success;
- bool bOk = MIstatus::success;
+ bool bOk = MIstatus::success;
#ifdef _MSC_VER
// Debugging / I/O issues with client.
@@ -62,12 +58,13 @@ CMICmnStreamStdout::Initialize()
//::setbuf( stdout, NULL );
#endif // _MSC_VER
- m_bInitialized = bOk;
+ m_bInitialized = bOk;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resources for *this Stdout stream.
// Type: Method.
// Args: None.
@@ -75,106 +72,117 @@ CMICmnStreamStdout::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
+bool CMICmnStreamStdout::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- if (!m_bInitialized)
- return MIstatus::success;
+ if (!m_bInitialized)
+ return MIstatus::success;
- ClrErrorDescription();
+ ClrErrorDescription();
- m_bInitialized = false;
+ m_bInitialized = false;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Write an MI format type response to stdout. The text data does not need to
-// include a carriage line return as this is added to the text. The function also
+//++
+//------------------------------------------------------------------------------------
+// Details: Write an MI format type response to stdout. The text data does not
+// need to
+// include a carriage line return as this is added to the text. The
+// function also
// then passes the text data into the CMICmnLog logger.
// Type: Method.
// Args: vText - (R) MI formatted text.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false = do
+// not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::WriteMIResponse(const CMIUtilString &vText, const bool vbSendToLog /* = true */)
-{
- return WritePriv(vText, vText, vbSendToLog);
+bool CMICmnStreamStdout::WriteMIResponse(const CMIUtilString &vText,
+ const bool vbSendToLog /* = true */) {
+ return WritePriv(vText, vText, vbSendToLog);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write text data to stdout. The text data does not need to
-// include a carriage line return as this is added to the text. The function also
+// include a carriage line return as this is added to the text. The
+// function also
// then passes the text data into the CMICmnLog logger.
// Type: Method.
// Args: vText - (R) Text data.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false = do
+// not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::Write(const CMIUtilString &vText, const bool vbSendToLog /* = true */)
-{
- if (vText.length() == 0)
- return MIstatus::failure;
+bool CMICmnStreamStdout::Write(const CMIUtilString &vText,
+ const bool vbSendToLog /* = true */) {
+ if (vText.length() == 0)
+ return MIstatus::failure;
- const CMIUtilString strPrefixed(CMIUtilString::Format("%s: %s", CMIDriver::Instance().GetAppNameShort().c_str(), vText.c_str()));
+ const CMIUtilString strPrefixed(CMIUtilString::Format(
+ "%s: %s", CMIDriver::Instance().GetAppNameShort().c_str(),
+ vText.c_str()));
- return WritePriv(strPrefixed, vText, vbSendToLog);
+ return WritePriv(strPrefixed, vText, vbSendToLog);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write text data to stdout. The text data does not need to
-// include a carriage line return as this is added to the text. The function also
+// include a carriage line return as this is added to the text. The
+// function also
// then passes the text data into the CMICmnLog logger.
// Type: Method.
// Args: vText - (R) Text data prefixed with MI app's short name.
// vTxtForLogFile - (R) Text data.
-// vbSendToLog - (R) True = Yes send to the Log file too, false = do not. (Dflt = true)
+// vbSendToLog - (R) True = Yes send to the Log file too, false =
+// do not. (Dflt = true)
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::WritePriv(const CMIUtilString &vText, const CMIUtilString &vTxtForLogFile, const bool vbSendToLog /* = true */)
-{
- if (vText.length() == 0)
- return MIstatus::failure;
-
- bool bOk = MIstatus::success;
- {
- // Grab the stdout thread lock while we print
- CMIUtilThreadLock _lock(m_mutex);
-
- // Send this text to stdout
- const MIint status = ::fputs(vText.c_str(), stdout);
- if (status == EOF)
- // Don't call the CMICmnBase::SetErrorDescription() because it will cause a stack overflow:
- // CMICmnBase::SetErrorDescription -> CMICmnStreamStdout::Write -> CMICmnStreamStdout::WritePriv -> CMICmnBase::SetErrorDescription
- bOk = MIstatus::failure;
- else
- {
- ::fprintf(stdout, "\n");
- ::fflush(stdout);
- }
-
- // Send this text to the log
- if (bOk && vbSendToLog)
- bOk &= m_pLog->WriteLog(vTxtForLogFile);
+bool CMICmnStreamStdout::WritePriv(const CMIUtilString &vText,
+ const CMIUtilString &vTxtForLogFile,
+ const bool vbSendToLog /* = true */) {
+ if (vText.length() == 0)
+ return MIstatus::failure;
+
+ bool bOk = MIstatus::success;
+ {
+ // Grab the stdout thread lock while we print
+ CMIUtilThreadLock _lock(m_mutex);
+
+ // Send this text to stdout
+ const MIint status = ::fputs(vText.c_str(), stdout);
+ if (status == EOF)
+ // Don't call the CMICmnBase::SetErrorDescription() because it will cause
+ // a stack overflow:
+ // CMICmnBase::SetErrorDescription -> CMICmnStreamStdout::Write ->
+ // CMICmnStreamStdout::WritePriv -> CMICmnBase::SetErrorDescription
+ bOk = MIstatus::failure;
+ else {
+ ::fprintf(stdout, "\n");
+ ::fflush(stdout);
}
- return bOk;
+ // Send this text to the log
+ if (bOk && vbSendToLog)
+ bOk &= m_pLog->WriteLog(vTxtForLogFile);
+ }
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Lock the availability of the stream stdout. Other users of *this stream will
+//++
+//------------------------------------------------------------------------------------
+// Details: Lock the availability of the stream stdout. Other users of *this
+// stream will
// be stalled until it is available (Unlock()).
// Type: Method.
// Args: None.
@@ -182,14 +190,13 @@ CMICmnStreamStdout::WritePriv(const CMIU
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::Lock()
-{
- m_mutex.Lock();
- return MIstatus::success;
+bool CMICmnStreamStdout::Lock() {
+ m_mutex.Lock();
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release a previously locked stdout.
// Type: Method.
// Args: None.
@@ -197,15 +204,15 @@ CMICmnStreamStdout::Lock()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::Unlock()
-{
- m_mutex.Unlock();
- return MIstatus::success;
+bool CMICmnStreamStdout::Unlock() {
+ m_mutex.Unlock();
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Take a text data and send to the stdout stream. Also output to the MI Log
+//++
+//------------------------------------------------------------------------------------
+// Details: Take a text data and send to the stdout stream. Also output to the
+// MI Log
// file.
// Type: Static method.
// Args: vrTxt - (R) Text.
@@ -213,14 +220,13 @@ CMICmnStreamStdout::Unlock()
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::TextToStdout(const CMIUtilString &vrTxt)
-{
- const bool bSendToLog = true;
- return CMICmnStreamStdout::Instance().WriteMIResponse(vrTxt, bSendToLog);
+bool CMICmnStreamStdout::TextToStdout(const CMIUtilString &vrTxt) {
+ const bool bSendToLog = true;
+ return CMICmnStreamStdout::Instance().WriteMIResponse(vrTxt, bSendToLog);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write prompt to stdout if it's enabled.
// Type: Static method.
// Args: None.
@@ -228,11 +234,9 @@ CMICmnStreamStdout::TextToStdout(const C
// MIstatus::failure - Function failed.
// Throws: None.
//--
-bool
-CMICmnStreamStdout::WritePrompt()
-{
- const CMICmnStreamStdin &rStdinMan = CMICmnStreamStdin::Instance();
- if (rStdinMan.GetEnablePrompt())
- return TextToStdout(rStdinMan.GetPrompt());
- return MIstatus::success;
+bool CMICmnStreamStdout::WritePrompt() {
+ const CMICmnStreamStdin &rStdinMan = CMICmnStreamStdin::Instance();
+ if (rStdinMan.GetEnablePrompt())
+ return TextToStdout(rStdinMan.GetPrompt());
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnStreamStdout.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnStreamStdout.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnStreamStdout.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnStreamStdout.h Tue Sep 6 15:57:50 2016
@@ -10,50 +10,54 @@
#pragma once
// In-house headers:
-#include "MIUtilString.h"
#include "MICmnBase.h"
-#include "MIUtilThreadBaseStd.h"
#include "MIUtilSingletonBase.h"
+#include "MIUtilString.h"
+#include "MIUtilThreadBaseStd.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code class. The MI driver requires this object.
// CMICmnStreamStdout sets up and tears downs stdout for the driver.
//
// Singleton class.
//--
-class CMICmnStreamStdout : public CMICmnBase, public MI::ISingleton<CMICmnStreamStdout>
-{
- friend class MI::ISingleton<CMICmnStreamStdout>;
-
- // Statics:
- public:
- static bool TextToStdout(const CMIUtilString &vrTxt);
- static bool WritePrompt();
-
- // Methods:
- public:
- bool Initialize() override;
- bool Shutdown() override;
- //
- bool Lock();
- bool Unlock();
- bool Write(const CMIUtilString &vText, const bool vbSendToLog = true);
- bool WriteMIResponse(const CMIUtilString &vText, const bool vbSendToLog = true);
-
- // Methods:
- private:
- /* ctor */ CMICmnStreamStdout();
- /* ctor */ CMICmnStreamStdout(const CMICmnStreamStdout &);
- void operator=(const CMICmnStreamStdout &);
- //
- bool WritePriv(const CMIUtilString &vText, const CMIUtilString &vTxtForLogFile, const bool vbSendToLog = true);
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMICmnStreamStdout() override;
-
- // Attributes:
- private:
- CMIUtilThreadMutex m_mutex; // Mutex object for sync during writing to stream
+class CMICmnStreamStdout : public CMICmnBase,
+ public MI::ISingleton<CMICmnStreamStdout> {
+ friend class MI::ISingleton<CMICmnStreamStdout>;
+
+ // Statics:
+public:
+ static bool TextToStdout(const CMIUtilString &vrTxt);
+ static bool WritePrompt();
+
+ // Methods:
+public:
+ bool Initialize() override;
+ bool Shutdown() override;
+ //
+ bool Lock();
+ bool Unlock();
+ bool Write(const CMIUtilString &vText, const bool vbSendToLog = true);
+ bool WriteMIResponse(const CMIUtilString &vText,
+ const bool vbSendToLog = true);
+
+ // Methods:
+private:
+ /* ctor */ CMICmnStreamStdout();
+ /* ctor */ CMICmnStreamStdout(const CMICmnStreamStdout &);
+ void operator=(const CMICmnStreamStdout &);
+ //
+ bool WritePriv(const CMIUtilString &vText,
+ const CMIUtilString &vTxtForLogFile,
+ const bool vbSendToLog = true);
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnStreamStdout() override;
+
+ // Attributes:
+private:
+ CMIUtilThreadMutex m_mutex; // Mutex object for sync during writing to stream
};
Modified: lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.cpp Tue Sep 6 15:57:50 2016
@@ -13,30 +13,28 @@
#include "MICmnResources.h"
#include "MIUtilSingletonHelper.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnThreadMgr constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnThreadMgrStd::CMICmnThreadMgrStd()
-{
-}
+CMICmnThreadMgrStd::CMICmnThreadMgrStd() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMICmnThreadMgr destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMICmnThreadMgrStd::~CMICmnThreadMgrStd()
-{
- Shutdown();
-}
+CMICmnThreadMgrStd::~CMICmnThreadMgrStd() { Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialise resources for *this thread manager.
// Type: Method.
// Args: None.
@@ -44,36 +42,36 @@ CMICmnThreadMgrStd::~CMICmnThreadMgrStd(
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnThreadMgrStd::Initialize()
-{
- m_clientUsageRefCnt++;
-
- if (m_bInitialized)
- return MIstatus::success;
-
- bool bOk = MIstatus::success;
-
- ClrErrorDescription();
- CMIUtilString errMsg;
-
- // Note initialisation order is important here as some resources depend on previous
- MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
- MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
-
- m_bInitialized = bOk;
-
- if (!bOk)
- {
- CMIUtilString strInitError(CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_THREADMGR), errMsg.c_str()));
- SetErrorDescription(strInitError);
- return MIstatus::failure;
- }
+bool CMICmnThreadMgrStd::Initialize() {
+ m_clientUsageRefCnt++;
+
+ if (m_bInitialized)
+ return MIstatus::success;
+
+ bool bOk = MIstatus::success;
+
+ ClrErrorDescription();
+ CMIUtilString errMsg;
+
+ // Note initialisation order is important here as some resources depend on
+ // previous
+ MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
+ MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
- return bOk;
+ m_bInitialized = bOk;
+
+ if (!bOk) {
+ CMIUtilString strInitError(CMIUtilString::Format(
+ MIRSRC(IDS_MI_INIT_ERR_THREADMGR), errMsg.c_str()));
+ SetErrorDescription(strInitError);
+ return MIstatus::failure;
+ }
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resources for *this thread manager.
// Type: Method.
// Args: None.
@@ -81,68 +79,65 @@ CMICmnThreadMgrStd::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnThreadMgrStd::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
+bool CMICmnThreadMgrStd::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- if (!m_bInitialized)
- return MIstatus::success;
+ if (!m_bInitialized)
+ return MIstatus::success;
- m_bInitialized = false;
+ m_bInitialized = false;
- ClrErrorDescription();
+ ClrErrorDescription();
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
- // Tidy up
- ThreadAllTerminate();
+ // Tidy up
+ ThreadAllTerminate();
- // Note shutdown order is important here
- MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
- MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
+ // Note shutdown order is important here
+ MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
+ MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
- if (!bOk)
- {
- SetErrorDescriptionn(MIRSRC(IDS_MI_SHUTDOWN_ERR), errMsg.c_str());
- }
+ if (!bOk) {
+ SetErrorDescriptionn(MIRSRC(IDS_MI_SHUTDOWN_ERR), errMsg.c_str());
+ }
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Ask the thread manager to kill all threads and wait until they have died
+//++
+//------------------------------------------------------------------------------------
+// Details: Ask the thread manager to kill all threads and wait until they have
+// died
// Type: Method.
// Args: None.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnThreadMgrStd::ThreadAllTerminate()
-{
- ThreadList_t::const_iterator it = m_threadList.begin();
- for (; it != m_threadList.end(); ++it)
- {
- // If the thread is still running
- CMIUtilThreadActiveObjBase *pThread = *it;
- if (pThread->ThreadIsActive())
- {
- // Ask this thread to kill itself
- pThread->ThreadKill();
-
- // Wait for this thread to die
- pThread->ThreadJoin();
- }
+bool CMICmnThreadMgrStd::ThreadAllTerminate() {
+ ThreadList_t::const_iterator it = m_threadList.begin();
+ for (; it != m_threadList.end(); ++it) {
+ // If the thread is still running
+ CMIUtilThreadActiveObjBase *pThread = *it;
+ if (pThread->ThreadIsActive()) {
+ // Ask this thread to kill itself
+ pThread->ThreadKill();
+
+ // Wait for this thread to die
+ pThread->ThreadJoin();
}
+ }
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Add a thread object to *this manager's list of thread objects. The list to
+//++
+//------------------------------------------------------------------------------------
+// Details: Add a thread object to *this manager's list of thread objects. The
+// list to
// used to manage thread objects centrally.
// Type: Method.
// Args: vrObj - (R) A thread object.
@@ -150,10 +145,8 @@ CMICmnThreadMgrStd::ThreadAllTerminate()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMICmnThreadMgrStd::AddThread(const CMIUtilThreadActiveObjBase &vrObj)
-{
- m_threadList.push_back(const_cast<CMIUtilThreadActiveObjBase *>(&vrObj));
+bool CMICmnThreadMgrStd::AddThread(const CMIUtilThreadActiveObjBase &vrObj) {
+ m_threadList.push_back(const_cast<CMIUtilThreadActiveObjBase *>(&vrObj));
- return MIstatus::success;
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.h (original)
+++ lldb/trunk/tools/lldb-mi/MICmnThreadMgrStd.h Tue Sep 6 15:57:50 2016
@@ -14,11 +14,12 @@
// In-house headers:
#include "MICmnBase.h"
-#include "MIUtilThreadBaseStd.h"
#include "MICmnResources.h"
#include "MIUtilSingletonBase.h"
+#include "MIUtilThreadBaseStd.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI's worker thread (active thread) manager.
// The manager creates threads and behalf of clients. Client are
// responsible for their threads and can delete them when necessary.
@@ -26,98 +27,99 @@
// shutdown.
// Singleton class.
//--
-class CMICmnThreadMgrStd : public CMICmnBase, public MI::ISingleton<CMICmnThreadMgrStd>
-{
- friend MI::ISingleton<CMICmnThreadMgrStd>;
-
- // Methods:
- public:
- bool Initialize() override;
- bool Shutdown() override;
- bool
- ThreadAllTerminate(); // Ask all threads to stop (caution)
- template <typename T> // Ask the thread manager to start and stop threads on our behalf
- bool ThreadStart(T &vrwObject);
-
- // Typedef:
- private:
- typedef std::vector<CMIUtilThreadActiveObjBase *> ThreadList_t;
-
- // Methods:
- private:
- /* ctor */ CMICmnThreadMgrStd();
- /* ctor */ CMICmnThreadMgrStd(const CMICmnThreadMgrStd &);
- void operator=(const CMICmnThreadMgrStd &);
- //
- bool
- AddThread(const CMIUtilThreadActiveObjBase &vrObj); // Add a thread for monitoring by the threadmanager
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMICmnThreadMgrStd() override;
-
- // Attributes:
- private:
- CMIUtilThreadMutex m_mutex;
- ThreadList_t m_threadList;
+class CMICmnThreadMgrStd : public CMICmnBase,
+ public MI::ISingleton<CMICmnThreadMgrStd> {
+ friend MI::ISingleton<CMICmnThreadMgrStd>;
+
+ // Methods:
+public:
+ bool Initialize() override;
+ bool Shutdown() override;
+ bool ThreadAllTerminate(); // Ask all threads to stop (caution)
+ template <typename T> // Ask the thread manager to start and stop threads on
+ // our behalf
+ bool ThreadStart(T &vrwObject);
+
+ // Typedef:
+private:
+ typedef std::vector<CMIUtilThreadActiveObjBase *> ThreadList_t;
+
+ // Methods:
+private:
+ /* ctor */ CMICmnThreadMgrStd();
+ /* ctor */ CMICmnThreadMgrStd(const CMICmnThreadMgrStd &);
+ void operator=(const CMICmnThreadMgrStd &);
+ //
+ bool AddThread(const CMIUtilThreadActiveObjBase &
+ vrObj); // Add a thread for monitoring by the threadmanager
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMICmnThreadMgrStd() override;
+
+ // Attributes:
+private:
+ CMIUtilThreadMutex m_mutex;
+ ThreadList_t m_threadList;
};
-//++ ------------------------------------------------------------------------------------
-// Details: Given a thread object start its (worker) thread to do work. The object is
-// added to the *this manager for housekeeping and deletion of all thread objects.
+//++
+//------------------------------------------------------------------------------------
+// Details: Given a thread object start its (worker) thread to do work. The
+// object is
+// added to the *this manager for housekeeping and deletion of all
+// thread objects.
// Type: Template method.
-// Args: vrwThreadObj - (RW) A CMIUtilThreadActiveObjBase derived object.
+// Args: vrwThreadObj - (RW) A CMIUtilThreadActiveObjBase derived
+// object.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-template <typename T>
-bool
-CMICmnThreadMgrStd::ThreadStart(T &vrwThreadObj)
-{
- bool bOk = MIstatus::success;
-
- // Grab a reference to the base object type
- CMIUtilThreadActiveObjBase &rObj = static_cast<CMIUtilThreadActiveObjBase &>(vrwThreadObj);
-
- // Add to the thread managers internal database
- bOk &= AddThread(rObj);
- if (!bOk)
- {
- const CMIUtilString errMsg(
- CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE), vrwThreadObj.ThreadGetName().c_str()));
- SetErrorDescription(errMsg);
- return MIstatus::failure;
- }
-
- // Grab a reference on behalf of the caller
- bOk &= vrwThreadObj.Acquire();
- if (!bOk)
- {
- const CMIUtilString errMsg(
- CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE), vrwThreadObj.ThreadGetName().c_str()));
- SetErrorDescription(errMsg);
- return MIstatus::failure;
- }
-
- // Thread is already started
- // This call must come after the reference count increment
- if (vrwThreadObj.ThreadIsActive())
- {
- // Early exit on thread already running condition
- return MIstatus::success;
- }
-
- // Start the thread running
- bOk &= vrwThreadObj.ThreadExecute();
- if (!bOk)
- {
- const CMIUtilString errMsg(
- CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE), vrwThreadObj.ThreadGetName().c_str()));
- SetErrorDescription(errMsg);
- return MIstatus::failure;
- }
+template <typename T> bool CMICmnThreadMgrStd::ThreadStart(T &vrwThreadObj) {
+ bool bOk = MIstatus::success;
+ // Grab a reference to the base object type
+ CMIUtilThreadActiveObjBase &rObj =
+ static_cast<CMIUtilThreadActiveObjBase &>(vrwThreadObj);
+
+ // Add to the thread managers internal database
+ bOk &= AddThread(rObj);
+ if (!bOk) {
+ const CMIUtilString errMsg(
+ CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE),
+ vrwThreadObj.ThreadGetName().c_str()));
+ SetErrorDescription(errMsg);
+ return MIstatus::failure;
+ }
+
+ // Grab a reference on behalf of the caller
+ bOk &= vrwThreadObj.Acquire();
+ if (!bOk) {
+ const CMIUtilString errMsg(
+ CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE),
+ vrwThreadObj.ThreadGetName().c_str()));
+ SetErrorDescription(errMsg);
+ return MIstatus::failure;
+ }
+
+ // Thread is already started
+ // This call must come after the reference count increment
+ if (vrwThreadObj.ThreadIsActive()) {
+ // Early exit on thread already running condition
return MIstatus::success;
+ }
+
+ // Start the thread running
+ bOk &= vrwThreadObj.ThreadExecute();
+ if (!bOk) {
+ const CMIUtilString errMsg(
+ CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE),
+ vrwThreadObj.ThreadGetName().c_str()));
+ SetErrorDescription(errMsg);
+ return MIstatus::failure;
+ }
+
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MIDataTypes.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDataTypes.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDataTypes.h (original)
+++ lldb/trunk/tools/lldb-mi/MIDataTypes.h Tue Sep 6 15:57:50 2016
@@ -30,14 +30,13 @@
// Common definitions:
// Function return status
-namespace MIstatus
-{
+namespace MIstatus {
const bool success = true;
const bool failure = false;
}
// Use to avoid "unused parameter" compiler warnings:
-#define MIunused(x) (void) x;
+#define MIunused(x) (void)x;
// Portability issues
#ifdef _WIN64
Modified: lldb/trunk/tools/lldb-mi/MIDriver.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriver.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriver.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIDriver.cpp Tue Sep 6 15:57:50 2016
@@ -8,37 +8,41 @@
//===----------------------------------------------------------------------===//
// Third party headers:
-#include <fstream>
#include "lldb/API/SBError.h"
+#include <fstream>
// In-house headers:
-#include "MIDriver.h"
-#include "MICmnResources.h"
-#include "MICmnLog.h"
+#include "MICmdArgValFile.h"
+#include "MICmdArgValString.h"
#include "MICmdMgr.h"
+#include "MICmnConfig.h"
+#include "MICmnLLDBDebugSessionInfo.h"
#include "MICmnLLDBDebugger.h"
+#include "MICmnLog.h"
#include "MICmnMIResultRecord.h"
#include "MICmnMIValueConst.h"
+#include "MICmnResources.h"
+#include "MICmnStreamStderr.h"
+#include "MICmnStreamStdout.h"
#include "MICmnThreadMgrStd.h"
+#include "MIDriver.h"
#include "MIUtilDebug.h"
#include "MIUtilSingletonHelper.h"
-#include "MICmnStreamStdout.h"
-#include "MICmnStreamStderr.h"
-#include "MICmdArgValFile.h"
-#include "MICmdArgValString.h"
-#include "MICmnConfig.h"
-#include "MICmnLLDBDebugSessionInfo.h"
// Instantiations:
#if _DEBUG
-const CMIUtilString CMIDriver::ms_constMIVersion = MIRSRC(IDS_MI_VERSION_DESCRIPTION_DEBUG);
+const CMIUtilString CMIDriver::ms_constMIVersion =
+ MIRSRC(IDS_MI_VERSION_DESCRIPTION_DEBUG);
#else
-const CMIUtilString CMIDriver::ms_constMIVersion = MIRSRC(IDS_MI_VERSION_DESCRIPTION); // Matches version in resources file
+const CMIUtilString CMIDriver::ms_constMIVersion =
+ MIRSRC(IDS_MI_VERSION_DESCRIPTION); // Matches version in resources file
#endif // _DEBUG
-const CMIUtilString CMIDriver::ms_constAppNameShort(MIRSRC(IDS_MI_APPNAME_SHORT));
+const CMIUtilString
+ CMIDriver::ms_constAppNameShort(MIRSRC(IDS_MI_APPNAME_SHORT));
const CMIUtilString CMIDriver::ms_constAppNameLong(MIRSRC(IDS_MI_APPNAME_LONG));
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriver constructor.
// Type: Method.
// Args: None.
@@ -46,102 +50,98 @@ const CMIUtilString CMIDriver::ms_constA
// Throws: None.
//--
CMIDriver::CMIDriver()
- : m_bFallThruToOtherDriverEnabled(false)
- , m_bDriverIsExiting(false)
- , m_handleMainThread(0)
- , m_rStdin(CMICmnStreamStdin::Instance())
- , m_rLldbDebugger(CMICmnLLDBDebugger::Instance())
- , m_rStdOut(CMICmnStreamStdout::Instance())
- , m_eCurrentDriverState(eDriverState_NotRunning)
- , m_bHaveExecutableFileNamePathOnCmdLine(false)
- , m_bDriverDebuggingArgExecutable(false)
- , m_bHaveCommandFileNamePathOnCmdLine(false)
-{
-}
+ : m_bFallThruToOtherDriverEnabled(false), m_bDriverIsExiting(false),
+ m_handleMainThread(0), m_rStdin(CMICmnStreamStdin::Instance()),
+ m_rLldbDebugger(CMICmnLLDBDebugger::Instance()),
+ m_rStdOut(CMICmnStreamStdout::Instance()),
+ m_eCurrentDriverState(eDriverState_NotRunning),
+ m_bHaveExecutableFileNamePathOnCmdLine(false),
+ m_bDriverDebuggingArgExecutable(false),
+ m_bHaveCommandFileNamePathOnCmdLine(false) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriver destructor.
// Type: Overridden.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIDriver::~CMIDriver()
-{
-}
+CMIDriver::~CMIDriver() {}
-//++ ------------------------------------------------------------------------------------
-// Details: Set whether *this driver (the parent) is enabled to pass a command to its
-// fall through (child) driver to interpret the command and do work instead
+//++
+//------------------------------------------------------------------------------------
+// Details: Set whether *this driver (the parent) is enabled to pass a command
+// to its
+// fall through (child) driver to interpret the command and do work
+// instead
// (if *this driver decides it can't handle the command).
// Type: Method.
-// Args: vbYes - (R) True = yes fall through, false = do not pass on command.
+// Args: vbYes - (R) True = yes fall through, false = do not pass on
+// command.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::SetEnableFallThru(const bool vbYes)
-{
- m_bFallThruToOtherDriverEnabled = vbYes;
- return MIstatus::success;
+bool CMIDriver::SetEnableFallThru(const bool vbYes) {
+ m_bFallThruToOtherDriverEnabled = vbYes;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Get whether *this driver (the parent) is enabled to pass a command to its
-// fall through (child) driver to interpret the command and do work instead
+//++
+//------------------------------------------------------------------------------------
+// Details: Get whether *this driver (the parent) is enabled to pass a command
+// to its
+// fall through (child) driver to interpret the command and do work
+// instead
// (if *this driver decides it can't handle the command).
// Type: Method.
// Args: None.
// Return: bool - True = yes fall through, false = do not pass on command.
// Throws: None.
//--
-bool
-CMIDriver::GetEnableFallThru() const
-{
- return m_bFallThruToOtherDriverEnabled;
+bool CMIDriver::GetEnableFallThru() const {
+ return m_bFallThruToOtherDriverEnabled;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve MI's application name of itself.
// Type: Method.
// Args: None.
// Return: CMIUtilString & - Text description.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetAppNameShort() const
-{
- return ms_constAppNameShort;
+const CMIUtilString &CMIDriver::GetAppNameShort() const {
+ return ms_constAppNameShort;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve MI's application name of itself.
// Type: Method.
// Args: None.
// Return: CMIUtilString & - Text description.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetAppNameLong() const
-{
- return ms_constAppNameLong;
+const CMIUtilString &CMIDriver::GetAppNameLong() const {
+ return ms_constAppNameLong;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve MI's version description of itself.
// Type: Method.
// Args: None.
// Return: CMIUtilString & - Text description.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetVersionDescription() const
-{
- return ms_constMIVersion;
+const CMIUtilString &CMIDriver::GetVersionDescription() const {
+ return ms_constMIVersion;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize setup *this driver ready for use.
// Type: Method.
// Args: None.
@@ -149,48 +149,48 @@ CMIDriver::GetVersionDescription() const
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::Initialize()
-{
- m_eCurrentDriverState = eDriverState_Initialising;
- m_clientUsageRefCnt++;
-
- ClrErrorDescription();
-
- if (m_bInitialized)
- return MIstatus::success;
-
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
-
- // Initialize all of the modules we depend on
- MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
- MI::ModuleInit<CMICmnStreamStdout>(IDS_MI_INIT_ERR_STREAMSTDOUT, bOk, errMsg);
- MI::ModuleInit<CMICmnStreamStderr>(IDS_MI_INIT_ERR_STREAMSTDERR, bOk, errMsg);
- MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
- MI::ModuleInit<CMICmnThreadMgrStd>(IDS_MI_INIT_ERR_THREADMANAGER, bOk, errMsg);
- MI::ModuleInit<CMICmnStreamStdin>(IDS_MI_INIT_ERR_STREAMSTDIN, bOk, errMsg);
- MI::ModuleInit<CMICmdMgr>(IDS_MI_INIT_ERR_CMDMGR, bOk, errMsg);
- bOk &= m_rLldbDebugger.SetDriver(*this);
- MI::ModuleInit<CMICmnLLDBDebugger>(IDS_MI_INIT_ERR_LLDBDEBUGGER, bOk, errMsg);
-
- m_bExitApp = false;
-
- m_bInitialized = bOk;
-
- if (!bOk)
- {
- const CMIUtilString msg = CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_DRIVER), errMsg.c_str());
- SetErrorDescription(msg);
- return MIstatus::failure;
- }
+bool CMIDriver::Initialize() {
+ m_eCurrentDriverState = eDriverState_Initialising;
+ m_clientUsageRefCnt++;
- m_eCurrentDriverState = eDriverState_RunningNotDebugging;
+ ClrErrorDescription();
- return bOk;
+ if (m_bInitialized)
+ return MIstatus::success;
+
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
+
+ // Initialize all of the modules we depend on
+ MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
+ MI::ModuleInit<CMICmnStreamStdout>(IDS_MI_INIT_ERR_STREAMSTDOUT, bOk, errMsg);
+ MI::ModuleInit<CMICmnStreamStderr>(IDS_MI_INIT_ERR_STREAMSTDERR, bOk, errMsg);
+ MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
+ MI::ModuleInit<CMICmnThreadMgrStd>(IDS_MI_INIT_ERR_THREADMANAGER, bOk,
+ errMsg);
+ MI::ModuleInit<CMICmnStreamStdin>(IDS_MI_INIT_ERR_STREAMSTDIN, bOk, errMsg);
+ MI::ModuleInit<CMICmdMgr>(IDS_MI_INIT_ERR_CMDMGR, bOk, errMsg);
+ bOk &= m_rLldbDebugger.SetDriver(*this);
+ MI::ModuleInit<CMICmnLLDBDebugger>(IDS_MI_INIT_ERR_LLDBDEBUGGER, bOk, errMsg);
+
+ m_bExitApp = false;
+
+ m_bInitialized = bOk;
+
+ if (!bOk) {
+ const CMIUtilString msg =
+ CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_DRIVER), errMsg.c_str());
+ SetErrorDescription(msg);
+ return MIstatus::failure;
+ }
+
+ m_eCurrentDriverState = eDriverState_RunningNotDebugging;
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Unbind detach or release resources used by *this driver.
// Type: Method.
// Args: None.
@@ -198,44 +198,48 @@ CMIDriver::Initialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::Shutdown()
-{
- if (--m_clientUsageRefCnt > 0)
- return MIstatus::success;
-
- if (!m_bInitialized)
- return MIstatus::success;
-
- m_eCurrentDriverState = eDriverState_ShuttingDown;
-
- ClrErrorDescription();
-
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
-
- // Shutdown all of the modules we depend on
- MI::ModuleShutdown<CMICmnLLDBDebugger>(IDS_MI_INIT_ERR_LLDBDEBUGGER, bOk, errMsg);
- MI::ModuleShutdown<CMICmdMgr>(IDS_MI_INIT_ERR_CMDMGR, bOk, errMsg);
- MI::ModuleShutdown<CMICmnStreamStdin>(IDS_MI_INIT_ERR_STREAMSTDIN, bOk, errMsg);
- MI::ModuleShutdown<CMICmnThreadMgrStd>(IDS_MI_INIT_ERR_THREADMANAGER, bOk, errMsg);
- MI::ModuleShutdown<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
- MI::ModuleShutdown<CMICmnStreamStderr>(IDS_MI_INIT_ERR_STREAMSTDERR, bOk, errMsg);
- MI::ModuleShutdown<CMICmnStreamStdout>(IDS_MI_INIT_ERR_STREAMSTDOUT, bOk, errMsg);
- MI::ModuleShutdown<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
-
- if (!bOk)
- {
- SetErrorDescriptionn(MIRSRC(IDS_MI_SHUTDOWN_ERR), errMsg.c_str());
- }
+bool CMIDriver::Shutdown() {
+ if (--m_clientUsageRefCnt > 0)
+ return MIstatus::success;
- m_eCurrentDriverState = eDriverState_NotRunning;
+ if (!m_bInitialized)
+ return MIstatus::success;
- return bOk;
-}
+ m_eCurrentDriverState = eDriverState_ShuttingDown;
-//++ ------------------------------------------------------------------------------------
-// Details: Work function. Client (the driver's user) is able to append their own message
+ ClrErrorDescription();
+
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
+
+ // Shutdown all of the modules we depend on
+ MI::ModuleShutdown<CMICmnLLDBDebugger>(IDS_MI_INIT_ERR_LLDBDEBUGGER, bOk,
+ errMsg);
+ MI::ModuleShutdown<CMICmdMgr>(IDS_MI_INIT_ERR_CMDMGR, bOk, errMsg);
+ MI::ModuleShutdown<CMICmnStreamStdin>(IDS_MI_INIT_ERR_STREAMSTDIN, bOk,
+ errMsg);
+ MI::ModuleShutdown<CMICmnThreadMgrStd>(IDS_MI_INIT_ERR_THREADMANAGER, bOk,
+ errMsg);
+ MI::ModuleShutdown<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
+ MI::ModuleShutdown<CMICmnStreamStderr>(IDS_MI_INIT_ERR_STREAMSTDERR, bOk,
+ errMsg);
+ MI::ModuleShutdown<CMICmnStreamStdout>(IDS_MI_INIT_ERR_STREAMSTDOUT, bOk,
+ errMsg);
+ MI::ModuleShutdown<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
+
+ if (!bOk) {
+ SetErrorDescriptionn(MIRSRC(IDS_MI_SHUTDOWN_ERR), errMsg.c_str());
+ }
+
+ m_eCurrentDriverState = eDriverState_NotRunning;
+
+ return bOk;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Work function. Client (the driver's user) is able to append their
+// own message
// in to the MI's Log trace file.
// Type: Method.
// Args: vMessage - (R) Client's text message.
@@ -243,15 +247,14 @@ CMIDriver::Shutdown()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::WriteMessageToLog(const CMIUtilString &vMessage)
-{
- CMIUtilString msg;
- msg = CMIUtilString::Format(MIRSRC(IDS_MI_CLIENT_MSG), vMessage.c_str());
- return m_pLog->Write(msg, CMICmnLog::eLogVerbosity_ClientMsg);
+bool CMIDriver::WriteMessageToLog(const CMIUtilString &vMessage) {
+ CMIUtilString msg;
+ msg = CMIUtilString::Format(MIRSRC(IDS_MI_CLIENT_MSG), vMessage.c_str());
+ return m_pLog->Write(msg, CMICmnLog::eLogVerbosity_ClientMsg);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDriverMgr calls *this driver initialize setup ready for use.
// Type: Overridden.
// Args: None.
@@ -259,14 +262,12 @@ CMIDriver::WriteMessageToLog(const CMIUt
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::DoInitialize()
-{
- return CMIDriver::Instance().Initialize();
-}
+bool CMIDriver::DoInitialize() { return CMIDriver::Instance().Initialize(); }
-//++ ------------------------------------------------------------------------------------
-// Details: CDriverMgr calls *this driver to unbind detach or release resources used by
+//++
+//------------------------------------------------------------------------------------
+// Details: CDriverMgr calls *this driver to unbind detach or release resources
+// used by
// *this driver.
// Type: Overridden.
// Args: None.
@@ -274,189 +275,211 @@ CMIDriver::DoInitialize()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::DoShutdown()
-{
- return CMIDriver::Instance().Shutdown();
-}
+bool CMIDriver::DoShutdown() { return CMIDriver::Instance().Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the name for *this driver.
// Type: Overridden.
// Args: None.
// Return: CMIUtilString & - Driver name.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetName() const
-{
- const CMIUtilString &rName = GetAppNameLong();
- const CMIUtilString &rVsn = GetVersionDescription();
- static CMIUtilString strName = CMIUtilString::Format("%s %s", rName.c_str(), rVsn.c_str());
+const CMIUtilString &CMIDriver::GetName() const {
+ const CMIUtilString &rName = GetAppNameLong();
+ const CMIUtilString &rVsn = GetVersionDescription();
+ static CMIUtilString strName =
+ CMIUtilString::Format("%s %s", rName.c_str(), rVsn.c_str());
- return strName;
+ return strName;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve *this driver's last error condition.
// Type: Overridden.
// Args: None.
// Return: CMIUtilString - Text description.
// Throws: None.
//--
-CMIUtilString
-CMIDriver::GetError() const
-{
- return GetErrorDescription();
-}
+CMIUtilString CMIDriver::GetError() const { return GetErrorDescription(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Call *this driver to return it's debugger.
// Type: Overridden.
// Args: None.
// Return: lldb::SBDebugger & - LLDB debugger object reference.
// Throws: None.
//--
-lldb::SBDebugger &
-CMIDriver::GetTheDebugger()
-{
- return m_rLldbDebugger.GetTheDebugger();
+lldb::SBDebugger &CMIDriver::GetTheDebugger() {
+ return m_rLldbDebugger.GetTheDebugger();
}
-//++ ------------------------------------------------------------------------------------
-// Details: Specify another driver *this driver can call should this driver not be able
-// to handle the client data input. DoFallThruToAnotherDriver() makes the call.
+//++
+//------------------------------------------------------------------------------------
+// Details: Specify another driver *this driver can call should this driver not
+// be able
+// to handle the client data input. DoFallThruToAnotherDriver() makes
+// the call.
// Type: Overridden.
// Args: vrOtherDriver - (R) Reference to another driver object.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver)
-{
- m_pDriverFallThru = const_cast<CMIDriverBase *>(&vrOtherDriver);
-
- return m_pDriverFallThru->SetDriverParent(*this);
+bool CMIDriver::SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver) {
+ m_pDriverFallThru = const_cast<CMIDriverBase *>(&vrOtherDriver);
+
+ return m_pDriverFallThru->SetDriverParent(*this);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Proxy function CMIDriverMgr IDriver interface implementation. *this driver's
-// implementation called from here to match the existing function name of the
-// original LLDB driver class (the extra indirection is not necessarily required).
-// Check the arguments that were passed to this program to make sure they are
+//++
+//------------------------------------------------------------------------------------
+// Details: Proxy function CMIDriverMgr IDriver interface implementation. *this
+// driver's
+// implementation called from here to match the existing function name
+// of the
+// original LLDB driver class (the extra indirection is not necessarily
+// required).
+// Check the arguments that were passed to this program to make sure
+// they are
// valid and to get their argument values (if any).
// Type: Overridden.
-// Args: argc - (R) An integer that contains the count of arguments that follow in
-// argv. The argc parameter is always greater than or equal to 1.
-// argv - (R) An array of null-terminated strings representing command-line
-// arguments entered by the user of the program. By convention,
-// argv[0] is the command with which the program is invoked.
+// Args: argc - (R) An integer that contains the count of arguments
+// that follow in
+// argv. The argc parameter is always greater than
+// or equal to 1.
+// argv - (R) An array of null-terminated strings representing
+// command-line
+// arguments entered by the user of the program. By
+// convention,
+// argv[0] is the command with which the program is
+// invoked.
// vpStdOut - (R) Pointer to a standard output stream.
-// vwbExiting - (W) True = *this want to exit, Reasons: help, invalid arg(s),
+// vwbExiting - (W) True = *this want to exit, Reasons: help,
+// invalid arg(s),
// version information only.
-// False = Continue to work, start debugger i.e. Command
+// False = Continue to work, start debugger i.e.
+// Command
// interpreter.
// Return: lldb::SBError - LLDB current error status.
// Throws: None.
//--
-lldb::SBError
-CMIDriver::DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting)
-{
- return ParseArgs(argc, argv, vpStdOut, vwbExiting);
+lldb::SBError CMIDriver::DoParseArgs(const int argc, const char *argv[],
+ FILE *vpStdOut, bool &vwbExiting) {
+ return ParseArgs(argc, argv, vpStdOut, vwbExiting);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Check the arguments that were passed to this program to make sure they are
-// valid and to get their argument values (if any). The following are options
+//++
+//------------------------------------------------------------------------------------
+// Details: Check the arguments that were passed to this program to make sure
+// they are
+// valid and to get their argument values (if any). The following are
+// options
// that are only handled by *this driver:
// --executable <file>
// --source <file> or -s <file>
-// The application's options --interpreter and --executable in code act very similar.
-// The --executable is necessary to differentiate whether the MI Driver is being
-// used by a client (e.g. Eclipse) or from the command line. Eclipse issues the option
-// --interpreter and also passes additional arguments which can be interpreted as an
-// executable if called from the command line. Using --executable tells the MI Driver
-// it is being called from the command line and to prepare to launch the executable
-// argument for a debug session. Using --interpreter on the command line does not
+// The application's options --interpreter and --executable in code act
+// very similar.
+// The --executable is necessary to differentiate whether the MI Driver
+// is being
+// used by a client (e.g. Eclipse) or from the command line. Eclipse
+// issues the option
+// --interpreter and also passes additional arguments which can be
+// interpreted as an
+// executable if called from the command line. Using --executable tells
+// the MI Driver
+// it is being called from the command line and to prepare to launch
+// the executable
+// argument for a debug session. Using --interpreter on the command
+// line does not
// issue additional commands to initialise a debug session.
// Type: Overridden.
-// Args: argc - (R) An integer that contains the count of arguments that follow in
-// argv. The argc parameter is always greater than or equal to 1.
-// argv - (R) An array of null-terminated strings representing command-line
-// arguments entered by the user of the program. By convention,
-// argv[0] is the command with which the program is invoked.
+// Args: argc - (R) An integer that contains the count of arguments
+// that follow in
+// argv. The argc parameter is always greater than
+// or equal to 1.
+// argv - (R) An array of null-terminated strings representing
+// command-line
+// arguments entered by the user of the program. By
+// convention,
+// argv[0] is the command with which the program is
+// invoked.
// vpStdOut - (R) Pointer to a standard output stream.
-// vwbExiting - (W) True = *this want to exit, Reasons: help, invalid arg(s),
+// vwbExiting - (W) True = *this want to exit, Reasons: help,
+// invalid arg(s),
// version information only.
-// False = Continue to work, start debugger i.e. Command
+// False = Continue to work, start debugger i.e.
+// Command
// interpreter.
// Return: lldb::SBError - LLDB current error status.
// Throws: None.
//--
-lldb::SBError
-CMIDriver::ParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting)
-{
- lldb::SBError errStatus;
- const bool bHaveArgs(argc >= 2);
-
- // *** Add any args handled here to GetHelpOnCmdLineArgOptions() ***
-
- // CODETAG_MIDRIVE_CMD_LINE_ARG_HANDLING
- // Look for the command line options
- bool bHaveExecutableFileNamePath = false;
- bool bHaveExecutableLongOption = false;
-
- if (bHaveArgs)
- {
- // Search right to left to look for filenames
- for (MIint i = argc - 1; i > 0; i--)
- {
- const CMIUtilString strArg(argv[i]);
- const CMICmdArgValFile argFile;
-
- // Check for a filename
- if (argFile.IsFilePath(strArg) || CMICmdArgValString(true, false, true).IsStringArg(strArg))
- {
- // Is this the command file for the '-s' or '--source' options?
- const CMIUtilString strPrevArg(argv[i - 1]);
- if (strPrevArg.compare("-s") == 0 || strPrevArg.compare("--source") == 0)
- {
- m_strCmdLineArgCommandFileNamePath = strArg;
- m_bHaveCommandFileNamePathOnCmdLine = true;
- i--; // skip '-s' on the next loop
- continue;
- }
- // Else, must be the executable
- bHaveExecutableFileNamePath = true;
- m_strCmdLineArgExecuteableFileNamePath = strArg;
- m_bHaveExecutableFileNamePathOnCmdLine = true;
- }
- // Report error if no command file was specified for the '-s' or '--source' options
- else if (strArg.compare("-s") == 0 || strArg.compare("--source") == 0)
- {
- vwbExiting = true;
- const CMIUtilString errMsg = CMIUtilString::Format(MIRSRC(IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF), strArg.c_str());
- errStatus.SetErrorString(errMsg.c_str());
- break;
- }
- // This argument is also checked for in CMIDriverMgr::ParseArgs()
- else if (strArg.compare("--executable") == 0) // Used to specify that there is executable argument also on the command line
- { // See fn description.
- bHaveExecutableLongOption = true;
- }
+lldb::SBError CMIDriver::ParseArgs(const int argc, const char *argv[],
+ FILE *vpStdOut, bool &vwbExiting) {
+ lldb::SBError errStatus;
+ const bool bHaveArgs(argc >= 2);
+
+ // *** Add any args handled here to GetHelpOnCmdLineArgOptions() ***
+
+ // CODETAG_MIDRIVE_CMD_LINE_ARG_HANDLING
+ // Look for the command line options
+ bool bHaveExecutableFileNamePath = false;
+ bool bHaveExecutableLongOption = false;
+
+ if (bHaveArgs) {
+ // Search right to left to look for filenames
+ for (MIint i = argc - 1; i > 0; i--) {
+ const CMIUtilString strArg(argv[i]);
+ const CMICmdArgValFile argFile;
+
+ // Check for a filename
+ if (argFile.IsFilePath(strArg) ||
+ CMICmdArgValString(true, false, true).IsStringArg(strArg)) {
+ // Is this the command file for the '-s' or '--source' options?
+ const CMIUtilString strPrevArg(argv[i - 1]);
+ if (strPrevArg.compare("-s") == 0 ||
+ strPrevArg.compare("--source") == 0) {
+ m_strCmdLineArgCommandFileNamePath = strArg;
+ m_bHaveCommandFileNamePathOnCmdLine = true;
+ i--; // skip '-s' on the next loop
+ continue;
}
- }
-
- if (bHaveExecutableFileNamePath && bHaveExecutableLongOption)
- {
- SetDriverDebuggingArgExecutable();
- }
+ // Else, must be the executable
+ bHaveExecutableFileNamePath = true;
+ m_strCmdLineArgExecuteableFileNamePath = strArg;
+ m_bHaveExecutableFileNamePathOnCmdLine = true;
+ }
+ // Report error if no command file was specified for the '-s' or
+ // '--source' options
+ else if (strArg.compare("-s") == 0 || strArg.compare("--source") == 0) {
+ vwbExiting = true;
+ const CMIUtilString errMsg = CMIUtilString::Format(
+ MIRSRC(IDS_CMD_ARGS_ERR_VALIDATION_MISSING_INF), strArg.c_str());
+ errStatus.SetErrorString(errMsg.c_str());
+ break;
+ }
+ // This argument is also checked for in CMIDriverMgr::ParseArgs()
+ else if (strArg.compare("--executable") == 0) // Used to specify that
+ // there is executable
+ // argument also on the
+ // command line
+ { // See fn description.
+ bHaveExecutableLongOption = true;
+ }
+ }
+ }
+
+ if (bHaveExecutableFileNamePath && bHaveExecutableLongOption) {
+ SetDriverDebuggingArgExecutable();
+ }
- return errStatus;
+ return errStatus;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: A client can ask if *this driver is GDB/MI compatible.
// Type: Overridden.
// Args: None.
@@ -464,13 +487,10 @@ CMIDriver::ParseArgs(const int argc, con
// False - Not GBD/MI compatible LLDB front end.
// Throws: None.
//--
-bool
-CMIDriver::GetDriverIsGDBMICompatibleDriver() const
-{
- return true;
-}
+bool CMIDriver::GetDriverIsGDBMICompatibleDriver() const { return true; }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Start worker threads for the driver.
// Type: Method.
// Args: None.
@@ -478,27 +498,26 @@ CMIDriver::GetDriverIsGDBMICompatibleDri
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::StartWorkerThreads()
-{
- bool bOk = MIstatus::success;
-
- // Grab the thread manager
- CMICmnThreadMgrStd &rThreadMgr = CMICmnThreadMgrStd::Instance();
-
- // Start the event polling thread
- if (bOk && !rThreadMgr.ThreadStart<CMICmnLLDBDebugger>(m_rLldbDebugger))
- {
- const CMIUtilString errMsg = CMIUtilString::Format(MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE),
- CMICmnThreadMgrStd::Instance().GetErrorDescription().c_str());
- SetErrorDescriptionn(errMsg);
- return MIstatus::failure;
- }
+bool CMIDriver::StartWorkerThreads() {
+ bool bOk = MIstatus::success;
- return bOk;
+ // Grab the thread manager
+ CMICmnThreadMgrStd &rThreadMgr = CMICmnThreadMgrStd::Instance();
+
+ // Start the event polling thread
+ if (bOk && !rThreadMgr.ThreadStart<CMICmnLLDBDebugger>(m_rLldbDebugger)) {
+ const CMIUtilString errMsg = CMIUtilString::Format(
+ MIRSRC(IDS_THREADMGR_ERR_THREAD_FAIL_CREATE),
+ CMICmnThreadMgrStd::Instance().GetErrorDescription().c_str());
+ SetErrorDescriptionn(errMsg);
+ return MIstatus::failure;
+ }
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Stop worker threads for the driver.
// Type: Method.
// Args: None.
@@ -506,14 +525,13 @@ CMIDriver::StartWorkerThreads()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::StopWorkerThreads()
-{
- CMICmnThreadMgrStd &rThreadMgr = CMICmnThreadMgrStd::Instance();
- return rThreadMgr.ThreadAllTerminate();
+bool CMIDriver::StopWorkerThreads() {
+ CMICmnThreadMgrStd &rThreadMgr = CMICmnThreadMgrStd::Instance();
+ return rThreadMgr.ThreadAllTerminate();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Call this function puts *this driver to work.
// This function is used by the application's main thread.
// Type: Overridden.
@@ -522,82 +540,78 @@ CMIDriver::StopWorkerThreads()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::DoMainLoop()
-{
- if (!InitClientIDEToMIDriver()) // Init Eclipse IDE
- {
- SetErrorDescriptionn(MIRSRC(IDS_MI_INIT_ERR_CLIENT_USING_DRIVER));
- return MIstatus::failure;
- }
-
- if (!StartWorkerThreads())
- return MIstatus::failure;
+bool CMIDriver::DoMainLoop() {
+ if (!InitClientIDEToMIDriver()) // Init Eclipse IDE
+ {
+ SetErrorDescriptionn(MIRSRC(IDS_MI_INIT_ERR_CLIENT_USING_DRIVER));
+ return MIstatus::failure;
+ }
+
+ if (!StartWorkerThreads())
+ return MIstatus::failure;
+
+ bool bOk = MIstatus::success;
+
+ if (HaveExecutableFileNamePathOnCmdLine()) {
+ if (!LocalDebugSessionStartupExecuteCommands()) {
+ SetErrorDescription(MIRSRC(IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION));
+ bOk = MIstatus::failure;
+ }
+ }
+
+ // App is not quitting currently
+ m_bExitApp = false;
+
+ // Handle source file
+ if (m_bHaveCommandFileNamePathOnCmdLine) {
+ const bool bAsyncMode = false;
+ ExecuteCommandFile(bAsyncMode);
+ }
+
+ // While the app is active
+ while (bOk && !m_bExitApp) {
+ CMIUtilString errorText;
+ const char *pCmd = m_rStdin.ReadLine(errorText);
+ if (pCmd != nullptr) {
+ CMIUtilString lineText(pCmd);
+ if (!lineText.empty()) {
+ // Check that the handler thread is alive (otherwise we stuck here)
+ assert(CMICmnLLDBDebugger::Instance().ThreadIsActive());
- bool bOk = MIstatus::success;
-
- if (HaveExecutableFileNamePathOnCmdLine())
- {
- if (!LocalDebugSessionStartupExecuteCommands())
{
- SetErrorDescription(MIRSRC(IDS_MI_INIT_ERR_LOCAL_DEBUG_SESSION));
- bOk = MIstatus::failure;
+ // Lock Mutex before processing commands so that we don't disturb an
+ // event
+ // being processed
+ CMIUtilThreadLock lock(
+ CMICmnLLDBDebugSessionInfo::Instance().GetSessionMutex());
+ bOk = InterpretCommand(lineText);
}
- }
- // App is not quitting currently
- m_bExitApp = false;
-
- // Handle source file
- if (m_bHaveCommandFileNamePathOnCmdLine)
- {
- const bool bAsyncMode = false;
- ExecuteCommandFile(bAsyncMode);
- }
+ // Draw prompt if desired
+ bOk = bOk && CMICmnStreamStdout::WritePrompt();
- // While the app is active
- while (bOk && !m_bExitApp)
- {
- CMIUtilString errorText;
- const char *pCmd = m_rStdin.ReadLine (errorText);
- if (pCmd != nullptr)
- {
- CMIUtilString lineText(pCmd);
- if (!lineText.empty ())
- {
- // Check that the handler thread is alive (otherwise we stuck here)
- assert(CMICmnLLDBDebugger::Instance().ThreadIsActive());
-
- {
- // Lock Mutex before processing commands so that we don't disturb an event
- // being processed
- CMIUtilThreadLock lock(CMICmnLLDBDebugSessionInfo::Instance().GetSessionMutex());
- bOk = InterpretCommand(lineText);
- }
-
- // Draw prompt if desired
- bOk = bOk && CMICmnStreamStdout::WritePrompt();
-
- // Wait while the handler thread handles incoming events
- CMICmnLLDBDebugger::Instance().WaitForHandleEvent();
- }
- }
+ // Wait while the handler thread handles incoming events
+ CMICmnLLDBDebugger::Instance().WaitForHandleEvent();
+ }
}
+ }
- // Signal that the application is shutting down
- DoAppQuit();
+ // Signal that the application is shutting down
+ DoAppQuit();
- // Close and wait for the workers to stop
- StopWorkerThreads();
+ // Close and wait for the workers to stop
+ StopWorkerThreads();
- // Ensure that a new line is sent as the last act of the dying driver
- m_rStdOut.WriteMIResponse("\n", false);
+ // Ensure that a new line is sent as the last act of the dying driver
+ m_rStdOut.WriteMIResponse("\n", false);
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set things in motion, set state etc that brings *this driver (and the
+//++
+//------------------------------------------------------------------------------------
+// Details: Set things in motion, set state etc that brings *this driver (and
+// the
// application) to a tidy shutdown.
// This function is used by the application's main thread.
// Type: Method.
@@ -606,95 +620,94 @@ CMIDriver::DoMainLoop()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::DoAppQuit()
-{
- bool bYesQuit = true;
-
- // Shutdown stuff, ready app for exit
- {
- CMIUtilThreadLock lock(m_threadMutex);
- m_bDriverIsExiting = true;
- }
+bool CMIDriver::DoAppQuit() {
+ bool bYesQuit = true;
- return bYesQuit;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver passes text commands to a fall through driver is it does not
+ // Shutdown stuff, ready app for exit
+ {
+ CMIUtilThreadLock lock(m_threadMutex);
+ m_bDriverIsExiting = true;
+ }
+
+ return bYesQuit;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver passes text commands to a fall through driver is it
+// does not
// understand them (the LLDB driver).
// This function is used by the application's main thread.
// Type: Method.
// Args: vTextLine - (R) Text data representing a possible command.
-// vwbCmdYesValid - (W) True = Command valid, false = command not handled.
+// vwbCmdYesValid - (W) True = Command valid, false = command not
+// handled.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::InterpretCommandFallThruDriver(const CMIUtilString &vTextLine, bool &vwbCmdYesValid)
-{
- MIunused(vTextLine);
- MIunused(vwbCmdYesValid);
-
- // ToDo: Implement when less urgent work to be done or decide remove as not required
- // bool bOk = MIstatus::success;
- // bool bCmdNotUnderstood = true;
- // if( bCmdNotUnderstood && GetEnableFallThru() )
- //{
- // CMIUtilString errMsg;
- // bOk = DoFallThruToAnotherDriver( vStdInBuffer, errMsg );
- // if( !bOk )
- // {
- // errMsg = errMsg.StripCREndOfLine();
- // errMsg = errMsg.StripCRAll();
- // const CMIDriverBase * pOtherDriver = GetDriverToFallThruTo();
- // const char * pName = pOtherDriver->GetDriverName().c_str();
- // const char * pId = pOtherDriver->GetDriverId().c_str();
- // const CMIUtilString msg( CMIUtilString::Format( MIRSRC( IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR ), pName, pId, errMsg.c_str() )
- //);
- // m_pLog->WriteMsg( msg );
- // }
- //}
- //
- // vwbCmdYesValid = bOk;
- // CMIUtilString strNot;
- // if( vwbCmdYesValid)
- // strNot = CMIUtilString::Format( "%s ", MIRSRC( IDS_WORD_NOT ) );
- // const CMIUtilString msg( CMIUtilString::Format( MIRSRC( IDS_FALLTHRU_DRIVER_CMD_RECEIVED ), vTextLine.c_str(), strNot.c_str() ) );
- // m_pLog->WriteLog( msg );
+bool CMIDriver::InterpretCommandFallThruDriver(const CMIUtilString &vTextLine,
+ bool &vwbCmdYesValid) {
+ MIunused(vTextLine);
+ MIunused(vwbCmdYesValid);
+
+ // ToDo: Implement when less urgent work to be done or decide remove as not
+ // required
+ // bool bOk = MIstatus::success;
+ // bool bCmdNotUnderstood = true;
+ // if( bCmdNotUnderstood && GetEnableFallThru() )
+ //{
+ // CMIUtilString errMsg;
+ // bOk = DoFallThruToAnotherDriver( vStdInBuffer, errMsg );
+ // if( !bOk )
+ // {
+ // errMsg = errMsg.StripCREndOfLine();
+ // errMsg = errMsg.StripCRAll();
+ // const CMIDriverBase * pOtherDriver = GetDriverToFallThruTo();
+ // const char * pName = pOtherDriver->GetDriverName().c_str();
+ // const char * pId = pOtherDriver->GetDriverId().c_str();
+ // const CMIUtilString msg( CMIUtilString::Format( MIRSRC(
+ // IDS_DRIVER_ERR_FALLTHRU_DRIVER_ERR ), pName, pId, errMsg.c_str() )
+ //);
+ // m_pLog->WriteMsg( msg );
+ // }
+ //}
+ //
+ // vwbCmdYesValid = bOk;
+ // CMIUtilString strNot;
+ // if( vwbCmdYesValid)
+ // strNot = CMIUtilString::Format( "%s ", MIRSRC( IDS_WORD_NOT ) );
+ // const CMIUtilString msg( CMIUtilString::Format( MIRSRC(
+ // IDS_FALLTHRU_DRIVER_CMD_RECEIVED ), vTextLine.c_str(), strNot.c_str() ) );
+ // m_pLog->WriteLog( msg );
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the name for *this driver.
// Type: Overridden.
// Args: None.
// Return: CMIUtilString & - Driver name.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetDriverName() const
-{
- return GetName();
-}
+const CMIUtilString &CMIDriver::GetDriverName() const { return GetName(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Get the unique ID for *this driver.
// Type: Overridden.
// Args: None.
// Return: CMIUtilString & - Text description.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetDriverId() const
-{
- return GetId();
-}
+const CMIUtilString &CMIDriver::GetDriverId() const { return GetId(); }
-//++ ------------------------------------------------------------------------------------
-// Details: This function allows *this driver to call on another driver to perform work
+//++
+//------------------------------------------------------------------------------------
+// Details: This function allows *this driver to call on another driver to
+// perform work
// should this driver not be able to handle the client data input.
// SetDriverToFallThruTo() specifies the fall through to driver.
// Check the error message if the function returns a failure.
@@ -705,76 +718,77 @@ CMIDriver::GetDriverId() const
// MIstatus::failure - Command failed.
// Throws: None.
//--
-bool
-CMIDriver::DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg)
-{
- bool bOk = MIstatus::success;
+bool CMIDriver::DoFallThruToAnotherDriver(const CMIUtilString &vCmd,
+ CMIUtilString &vwErrMsg) {
+ bool bOk = MIstatus::success;
- CMIDriverBase *pOtherDriver = GetDriverToFallThruTo();
- if (pOtherDriver == nullptr)
- return bOk;
+ CMIDriverBase *pOtherDriver = GetDriverToFallThruTo();
+ if (pOtherDriver == nullptr)
+ return bOk;
- return pOtherDriver->DoFallThruToAnotherDriver(vCmd, vwErrMsg);
+ return pOtherDriver->DoFallThruToAnotherDriver(vCmd, vwErrMsg);
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a file stream to other drivers on which *this driver
-// write's out to and they read as expected input. *this driver is passing
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a file stream to other drivers on which *this
+// driver
+// write's out to and they read as expected input. *this driver is
+// passing
// through commands to the (child) pass through assigned driver.
// Type: Overrdidden.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriver::GetStdin() const
-{
- // Note this fn is called on CMIDriverMgr register driver so stream has to be
- // available before *this driver has been initialized! Flaw?
-
- // This very likely to change later to a stream that the pass thru driver
- // will read and we write to give it 'input'
- return stdin;
+FILE *CMIDriver::GetStdin() const {
+ // Note this fn is called on CMIDriverMgr register driver so stream has to be
+ // available before *this driver has been initialized! Flaw?
+
+ // This very likely to change later to a stream that the pass thru driver
+ // will read and we write to give it 'input'
+ return stdin;
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a file stream to other pass through assigned drivers
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a file stream to other pass through assigned
+// drivers
// so they know what to write to.
// Type: Overidden.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriver::GetStdout() const
-{
- // Note this fn is called on CMIDriverMgr register driver so stream has to be
- // available before *this driver has been initialized! Flaw?
-
- // Do not want to pass through driver to write to stdout
- return NULL;
+FILE *CMIDriver::GetStdout() const {
+ // Note this fn is called on CMIDriverMgr register driver so stream has to be
+ // available before *this driver has been initialized! Flaw?
+
+ // Do not want to pass through driver to write to stdout
+ return NULL;
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a error file stream to other pass through assigned drivers
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a error file stream to other pass through
+// assigned drivers
// so they know what to write to.
// Type: Overidden.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriver::GetStderr() const
-{
- // Note this fn is called on CMIDriverMgr register driver so stream has to be
- // available before *this driver has been initialized! Flaw?
-
- // This very likely to change later to a stream that the pass thru driver
- // will write to and *this driver reads from to pass on the CMICmnLog object
- return stderr;
+FILE *CMIDriver::GetStderr() const {
+ // Note this fn is called on CMIDriverMgr register driver so stream has to be
+ // available before *this driver has been initialized! Flaw?
+
+ // This very likely to change later to a stream that the pass thru driver
+ // will write to and *this driver reads from to pass on the CMICmnLog object
+ return stderr;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Set a unique ID for *this driver. It cannot be empty.
// Type: Overridden.
// Args: vId - (R) Text description.
@@ -782,36 +796,35 @@ CMIDriver::GetStderr() const
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::SetId(const CMIUtilString &vId)
-{
- if (vId.empty())
- {
- SetErrorDescriptionn(MIRSRC(IDS_DRIVER_ERR_ID_INVALID), GetName().c_str(), vId.c_str());
- return MIstatus::failure;
- }
+bool CMIDriver::SetId(const CMIUtilString &vId) {
+ if (vId.empty()) {
+ SetErrorDescriptionn(MIRSRC(IDS_DRIVER_ERR_ID_INVALID), GetName().c_str(),
+ vId.c_str());
+ return MIstatus::failure;
+ }
- m_strDriverId = vId;
- return MIstatus::success;
+ m_strDriverId = vId;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Get the unique ID for *this driver.
// Type: Overridden.
// Args: None.
// Return: CMIUtilString & - Text description.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetId() const
-{
- return m_strDriverId;
-}
+const CMIUtilString &CMIDriver::GetId() const { return m_strDriverId; }
-//++ ------------------------------------------------------------------------------------
-// Details: Interpret the text data and match against current commands to see if there
-// is a match. If a match then the command is issued and actioned on. The
-// text data if not understood by *this driver is past on to the Fall Thru
+//++
+//------------------------------------------------------------------------------------
+// Details: Interpret the text data and match against current commands to see if
+// there
+// is a match. If a match then the command is issued and actioned on.
+// The
+// text data if not understood by *this driver is past on to the Fall
+// Thru
// driver.
// This function is used by the application's main thread.
// Type: Method.
@@ -820,22 +833,22 @@ CMIDriver::GetId() const
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::InterpretCommand(const CMIUtilString &vTextLine)
-{
- const bool bNeedToRebroadcastStopEvent = m_rLldbDebugger.CheckIfNeedToRebroadcastStopEvent();
- bool bCmdYesValid = false;
- bool bOk = InterpretCommandThisDriver(vTextLine, bCmdYesValid);
- if (bOk && !bCmdYesValid)
- bOk = InterpretCommandFallThruDriver(vTextLine, bCmdYesValid);
+bool CMIDriver::InterpretCommand(const CMIUtilString &vTextLine) {
+ const bool bNeedToRebroadcastStopEvent =
+ m_rLldbDebugger.CheckIfNeedToRebroadcastStopEvent();
+ bool bCmdYesValid = false;
+ bool bOk = InterpretCommandThisDriver(vTextLine, bCmdYesValid);
+ if (bOk && !bCmdYesValid)
+ bOk = InterpretCommandFallThruDriver(vTextLine, bCmdYesValid);
- if (bNeedToRebroadcastStopEvent)
- m_rLldbDebugger.RebroadcastStopEvent();
+ if (bNeedToRebroadcastStopEvent)
+ m_rLldbDebugger.RebroadcastStopEvent();
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Helper function for CMIDriver::InterpretCommandThisDriver.
// Convert a CLI command to MI command (just wrap any CLI command
// into "<tokens>-interpreter-exec command \"<CLI command>\"").
@@ -846,135 +859,147 @@ CMIDriver::InterpretCommand(const CMIUti
// Throws: None.
//--
CMIUtilString
-CMIDriver::WrapCLICommandIntoMICommand(const CMIUtilString &vTextLine) const
-{
- // Tokens contain following digits
- static const CMIUtilString digits("0123456789");
-
- // Consider an algorithm on the following example:
- // 001-file-exec-and-symbols "/path/to/file"
- //
- // 1. Skip a command token
- // For example:
- // 001-file-exec-and-symbols "/path/to/file"
- // 001target create "/path/to/file"
- // ^ -- command starts here (in both cases)
- // Also possible case when command not found:
- // 001
- // ^ -- i.e. only tokens are present (or empty string at all)
- const size_t nCommandOffset = vTextLine.find_first_not_of(digits);
-
- // 2. Check if command is empty
- // For example:
- // 001-file-exec-and-symbols "/path/to/file"
- // 001target create "/path/to/file"
- // ^ -- command not empty (in both cases)
- // or:
- // 001
- // ^ -- command wasn't found
- const bool bIsEmptyCommand = (nCommandOffset == CMIUtilString::npos);
-
- // 3. Check and exit if it isn't a CLI command
- // For example:
- // 001-file-exec-and-symbols "/path/to/file"
- // 001
- // ^ -- it isn't CLI command (in both cases)
- // or:
- // 001target create "/path/to/file"
- // ^ -- it's CLI command
- const bool bIsCliCommand = !bIsEmptyCommand && (vTextLine.at(nCommandOffset) != '-');
- if (!bIsCliCommand)
- return vTextLine;
-
- // 4. Wrap CLI command to make it MI-compatible
- //
- // 001target create "/path/to/file"
- // ^^^ -- token
- const std::string vToken(vTextLine.begin(), vTextLine.begin() + nCommandOffset);
- // 001target create "/path/to/file"
- // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- CLI command
- const CMIUtilString vCliCommand(std::string(vTextLine, nCommandOffset));
-
- // 5. Escape special characters and embed the command in a string
- // Result: it looks like -- target create \"/path/to/file\".
- const std::string vShieldedCliCommand(vCliCommand.AddSlashes());
-
- // 6. Turn the CLI command into an MI command, as in:
- // 001-interpreter-exec command "target create \"/path/to/file\""
- // ^^^ -- token
- // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ -- wrapper
- // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- shielded CLI command
- return CMIUtilString::Format("%s-interpreter-exec command \"%s\"",
- vToken.c_str(), vShieldedCliCommand.c_str());
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Interpret the text data and match against current commands to see if there
-// is a match. If a match then the command is issued and actioned on. If a
-// command cannot be found to match then vwbCmdYesValid is set to false and
+CMIDriver::WrapCLICommandIntoMICommand(const CMIUtilString &vTextLine) const {
+ // Tokens contain following digits
+ static const CMIUtilString digits("0123456789");
+
+ // Consider an algorithm on the following example:
+ // 001-file-exec-and-symbols "/path/to/file"
+ //
+ // 1. Skip a command token
+ // For example:
+ // 001-file-exec-and-symbols "/path/to/file"
+ // 001target create "/path/to/file"
+ // ^ -- command starts here (in both cases)
+ // Also possible case when command not found:
+ // 001
+ // ^ -- i.e. only tokens are present (or empty string at all)
+ const size_t nCommandOffset = vTextLine.find_first_not_of(digits);
+
+ // 2. Check if command is empty
+ // For example:
+ // 001-file-exec-and-symbols "/path/to/file"
+ // 001target create "/path/to/file"
+ // ^ -- command not empty (in both cases)
+ // or:
+ // 001
+ // ^ -- command wasn't found
+ const bool bIsEmptyCommand = (nCommandOffset == CMIUtilString::npos);
+
+ // 3. Check and exit if it isn't a CLI command
+ // For example:
+ // 001-file-exec-and-symbols "/path/to/file"
+ // 001
+ // ^ -- it isn't CLI command (in both cases)
+ // or:
+ // 001target create "/path/to/file"
+ // ^ -- it's CLI command
+ const bool bIsCliCommand =
+ !bIsEmptyCommand && (vTextLine.at(nCommandOffset) != '-');
+ if (!bIsCliCommand)
+ return vTextLine;
+
+ // 4. Wrap CLI command to make it MI-compatible
+ //
+ // 001target create "/path/to/file"
+ // ^^^ -- token
+ const std::string vToken(vTextLine.begin(),
+ vTextLine.begin() + nCommandOffset);
+ // 001target create "/path/to/file"
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- CLI command
+ const CMIUtilString vCliCommand(std::string(vTextLine, nCommandOffset));
+
+ // 5. Escape special characters and embed the command in a string
+ // Result: it looks like -- target create \"/path/to/file\".
+ const std::string vShieldedCliCommand(vCliCommand.AddSlashes());
+
+ // 6. Turn the CLI command into an MI command, as in:
+ // 001-interpreter-exec command "target create \"/path/to/file\""
+ // ^^^ -- token
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ -- wrapper
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- shielded
+ // CLI command
+ return CMIUtilString::Format("%s-interpreter-exec command \"%s\"",
+ vToken.c_str(), vShieldedCliCommand.c_str());
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Interpret the text data and match against current commands to see if
+// there
+// is a match. If a match then the command is issued and actioned on.
+// If a
+// command cannot be found to match then vwbCmdYesValid is set to false
+// and
// nothing else is done here.
// This function is used by the application's main thread.
// Type: Method.
// Args: vTextLine - (R) Text data representing a possible command.
-// vwbCmdYesValid - (W) True = Command valid, false = command not handled.
+// vwbCmdYesValid - (W) True = Command valid, false = command not
+// handled.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::InterpretCommandThisDriver(const CMIUtilString &vTextLine, bool &vwbCmdYesValid)
-{
- // Convert any CLI commands into MI commands
- const CMIUtilString vMITextLine(WrapCLICommandIntoMICommand(vTextLine));
-
- vwbCmdYesValid = false;
- bool bCmdNotInCmdFactor = false;
- SMICmdData cmdData;
- CMICmdMgr &rCmdMgr = CMICmdMgr::Instance();
- if (!rCmdMgr.CmdInterpret(vMITextLine, vwbCmdYesValid, bCmdNotInCmdFactor, cmdData))
- return MIstatus::failure;
-
- if (vwbCmdYesValid)
- {
- // For debugging only
- // m_pLog->WriteLog( cmdData.strMiCmdAll.c_str() );
-
- return ExecuteCommand(cmdData);
- }
-
- // Check for escape character, may be cursor control characters
- // This code is not necessary for application operation, just want to keep tabs on what
- // has been given to the driver to try and interpret.
- if (vMITextLine.at(0) == 27)
- {
- CMIUtilString logInput(MIRSRC(IDS_STDIN_INPUT_CTRL_CHARS));
- for (MIuint i = 0; i < vMITextLine.length(); i++)
- {
- logInput += CMIUtilString::Format("%d ", vMITextLine.at(i));
- }
- m_pLog->WriteLog(logInput);
- return MIstatus::success;
+bool CMIDriver::InterpretCommandThisDriver(const CMIUtilString &vTextLine,
+ bool &vwbCmdYesValid) {
+ // Convert any CLI commands into MI commands
+ const CMIUtilString vMITextLine(WrapCLICommandIntoMICommand(vTextLine));
+
+ vwbCmdYesValid = false;
+ bool bCmdNotInCmdFactor = false;
+ SMICmdData cmdData;
+ CMICmdMgr &rCmdMgr = CMICmdMgr::Instance();
+ if (!rCmdMgr.CmdInterpret(vMITextLine, vwbCmdYesValid, bCmdNotInCmdFactor,
+ cmdData))
+ return MIstatus::failure;
+
+ if (vwbCmdYesValid) {
+ // For debugging only
+ // m_pLog->WriteLog( cmdData.strMiCmdAll.c_str() );
+
+ return ExecuteCommand(cmdData);
+ }
+
+ // Check for escape character, may be cursor control characters
+ // This code is not necessary for application operation, just want to keep
+ // tabs on what
+ // has been given to the driver to try and interpret.
+ if (vMITextLine.at(0) == 27) {
+ CMIUtilString logInput(MIRSRC(IDS_STDIN_INPUT_CTRL_CHARS));
+ for (MIuint i = 0; i < vMITextLine.length(); i++) {
+ logInput += CMIUtilString::Format("%d ", vMITextLine.at(i));
}
+ m_pLog->WriteLog(logInput);
+ return MIstatus::success;
+ }
- // Write to the Log that a 'command' was not valid.
- // Report back to the MI client via MI result record.
- CMIUtilString strNotInCmdFactory;
- if (bCmdNotInCmdFactor)
- strNotInCmdFactory = CMIUtilString::Format(MIRSRC(IDS_DRIVER_CMD_NOT_IN_FACTORY), cmdData.strMiCmd.c_str());
- const CMIUtilString strNot(CMIUtilString::Format("%s ", MIRSRC(IDS_WORD_NOT)));
- const CMIUtilString msg(
- CMIUtilString::Format(MIRSRC(IDS_DRIVER_CMD_RECEIVED), vMITextLine.c_str(), strNot.c_str(), strNotInCmdFactory.c_str()));
- const CMICmnMIValueConst vconst = CMICmnMIValueConst(msg);
- const CMICmnMIValueResult valueResult("msg", vconst);
- const CMICmnMIResultRecord miResultRecord(cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Error, valueResult);
- const bool bOk = m_rStdOut.WriteMIResponse(miResultRecord.GetString());
-
- // Proceed to wait for or execute next command
- return bOk;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Having previously had the potential command validated and found valid now
+ // Write to the Log that a 'command' was not valid.
+ // Report back to the MI client via MI result record.
+ CMIUtilString strNotInCmdFactory;
+ if (bCmdNotInCmdFactor)
+ strNotInCmdFactory = CMIUtilString::Format(
+ MIRSRC(IDS_DRIVER_CMD_NOT_IN_FACTORY), cmdData.strMiCmd.c_str());
+ const CMIUtilString strNot(
+ CMIUtilString::Format("%s ", MIRSRC(IDS_WORD_NOT)));
+ const CMIUtilString msg(CMIUtilString::Format(
+ MIRSRC(IDS_DRIVER_CMD_RECEIVED), vMITextLine.c_str(), strNot.c_str(),
+ strNotInCmdFactory.c_str()));
+ const CMICmnMIValueConst vconst = CMICmnMIValueConst(msg);
+ const CMICmnMIValueResult valueResult("msg", vconst);
+ const CMICmnMIResultRecord miResultRecord(
+ cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Error,
+ valueResult);
+ const bool bOk = m_rStdOut.WriteMIResponse(miResultRecord.GetString());
+
+ // Proceed to wait for or execute next command
+ return bOk;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Having previously had the potential command validated and found
+// valid now
// get the command executed.
// This function is used by the application's main thread.
// Type: Method.
@@ -983,17 +1008,18 @@ CMIDriver::InterpretCommandThisDriver(co
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriver::ExecuteCommand(const SMICmdData &vCmdData)
-{
- CMICmdMgr &rCmdMgr = CMICmdMgr::Instance();
- return rCmdMgr.CmdExecute(vCmdData);
+bool CMIDriver::ExecuteCommand(const SMICmdData &vCmdData) {
+ CMICmdMgr &rCmdMgr = CMICmdMgr::Instance();
+ return rCmdMgr.CmdExecute(vCmdData);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set the MI Driver's exit application flag. The application checks this flag
+//++
+//------------------------------------------------------------------------------------
+// Details: Set the MI Driver's exit application flag. The application checks
+// this flag
// after every stdin line is read so the exit may not be instantaneous.
-// If vbForceExit is false the MI Driver queries its state and determines if is
+// If vbForceExit is false the MI Driver queries its state and
+// determines if is
// should exit or continue operating depending on that running state.
// This is related to the running state of the MI driver.
// Type: Overridden.
@@ -1001,58 +1027,53 @@ CMIDriver::ExecuteCommand(const SMICmdDa
// Return: None.
// Throws: None.
//--
-void
-CMIDriver::SetExitApplicationFlag(const bool vbForceExit)
-{
- if (vbForceExit)
- {
- CMIUtilThreadLock lock(m_threadMutex);
- m_bExitApp = true;
- return;
- }
+void CMIDriver::SetExitApplicationFlag(const bool vbForceExit) {
+ if (vbForceExit) {
+ CMIUtilThreadLock lock(m_threadMutex);
+ m_bExitApp = true;
+ return;
+ }
- // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
- // Did we receive a SIGINT from the client during a running debug program, if
- // so then SIGINT is not to be taken as meaning kill the MI driver application
- // but halt the inferior program being debugged instead
- if (m_eCurrentDriverState == eDriverState_RunningDebugging)
- {
- InterpretCommand("-exec-interrupt");
- return;
- }
+ // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
+ // Did we receive a SIGINT from the client during a running debug program, if
+ // so then SIGINT is not to be taken as meaning kill the MI driver application
+ // but halt the inferior program being debugged instead
+ if (m_eCurrentDriverState == eDriverState_RunningDebugging) {
+ InterpretCommand("-exec-interrupt");
+ return;
+ }
- m_bExitApp = true;
+ m_bExitApp = true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Get the MI Driver's exit exit application flag.
// This is related to the running state of the MI driver.
// Type: Method.
// Args: None.
-// Return: bool - True = MI Driver is shutting down, false = MI driver is running.
+// Return: bool - True = MI Driver is shutting down, false = MI driver is
+// running.
// Throws: None.
//--
-bool
-CMIDriver::GetExitApplicationFlag() const
-{
- return m_bExitApp;
-}
+bool CMIDriver::GetExitApplicationFlag() const { return m_bExitApp; }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Get the current running state of the MI Driver.
// Type: Method.
// Args: None.
// Return: DriverState_e - The current running state of the application.
// Throws: None.
//--
-CMIDriver::DriverState_e
-CMIDriver::GetCurrentDriverState() const
-{
- return m_eCurrentDriverState;
+CMIDriver::DriverState_e CMIDriver::GetCurrentDriverState() const {
+ return m_eCurrentDriverState;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set the current running state of the MI Driver to running and currently not in
+//++
+//------------------------------------------------------------------------------------
+// Details: Set the current running state of the MI Driver to running and
+// currently not in
// a debug session.
// Type: Method.
// Return: MIstatus::success - Functionality succeeded.
@@ -1060,48 +1081,48 @@ CMIDriver::GetCurrentDriverState() const
// Return: DriverState_e - The current running state of the application.
// Throws: None.
//--
-bool
-CMIDriver::SetDriverStateRunningNotDebugging()
-{
- // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
-
- if (m_eCurrentDriverState == eDriverState_RunningNotDebugging)
- return MIstatus::success;
-
- // Driver cannot be in the following states to set eDriverState_RunningNotDebugging
- switch (m_eCurrentDriverState)
- {
- case eDriverState_NotRunning:
- case eDriverState_Initialising:
- case eDriverState_ShuttingDown:
- {
- SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
- return MIstatus::failure;
- }
- case eDriverState_RunningDebugging:
- case eDriverState_RunningNotDebugging:
- break;
- case eDriverState_count:
- SetErrorDescription(
- CMIUtilString::Format(MIRSRC(IDS_CODE_ERR_INVALID_ENUMERATION_VALUE), "SetDriverStateRunningNotDebugging()"));
- return MIstatus::failure;
- }
-
- // Driver must be in this state to set eDriverState_RunningNotDebugging
- if (m_eCurrentDriverState != eDriverState_RunningDebugging)
- {
- SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
- return MIstatus::failure;
- }
-
- m_eCurrentDriverState = eDriverState_RunningNotDebugging;
+bool CMIDriver::SetDriverStateRunningNotDebugging() {
+ // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
+ if (m_eCurrentDriverState == eDriverState_RunningNotDebugging)
return MIstatus::success;
-}
-//++ ------------------------------------------------------------------------------------
-// Details: Set the current running state of the MI Driver to running and currently not in
-// a debug session. The driver's state must in the state running and in a
+ // Driver cannot be in the following states to set
+ // eDriverState_RunningNotDebugging
+ switch (m_eCurrentDriverState) {
+ case eDriverState_NotRunning:
+ case eDriverState_Initialising:
+ case eDriverState_ShuttingDown: {
+ SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
+ return MIstatus::failure;
+ }
+ case eDriverState_RunningDebugging:
+ case eDriverState_RunningNotDebugging:
+ break;
+ case eDriverState_count:
+ SetErrorDescription(
+ CMIUtilString::Format(MIRSRC(IDS_CODE_ERR_INVALID_ENUMERATION_VALUE),
+ "SetDriverStateRunningNotDebugging()"));
+ return MIstatus::failure;
+ }
+
+ // Driver must be in this state to set eDriverState_RunningNotDebugging
+ if (m_eCurrentDriverState != eDriverState_RunningDebugging) {
+ SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
+ return MIstatus::failure;
+ }
+
+ m_eCurrentDriverState = eDriverState_RunningNotDebugging;
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Set the current running state of the MI Driver to running and
+// currently not in
+// a debug session. The driver's state must in the state running and in
+// a
// debug session to set this new state.
// Type: Method.
// Return: MIstatus::success - Functionality succeeded.
@@ -1109,46 +1130,46 @@ CMIDriver::SetDriverStateRunningNotDebug
// Return: DriverState_e - The current running state of the application.
// Throws: None.
//--
-bool
-CMIDriver::SetDriverStateRunningDebugging()
-{
- // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
-
- if (m_eCurrentDriverState == eDriverState_RunningDebugging)
- return MIstatus::success;
-
- // Driver cannot be in the following states to set eDriverState_RunningDebugging
- switch (m_eCurrentDriverState)
- {
- case eDriverState_NotRunning:
- case eDriverState_Initialising:
- case eDriverState_ShuttingDown:
- {
- SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
- return MIstatus::failure;
- }
- case eDriverState_RunningDebugging:
- case eDriverState_RunningNotDebugging:
- break;
- case eDriverState_count:
- SetErrorDescription(CMIUtilString::Format(MIRSRC(IDS_CODE_ERR_INVALID_ENUMERATION_VALUE), "SetDriverStateRunningDebugging()"));
- return MIstatus::failure;
- }
-
- // Driver must be in this state to set eDriverState_RunningDebugging
- if (m_eCurrentDriverState != eDriverState_RunningNotDebugging)
- {
- SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
- return MIstatus::failure;
- }
-
- m_eCurrentDriverState = eDriverState_RunningDebugging;
+bool CMIDriver::SetDriverStateRunningDebugging() {
+ // CODETAG_DEBUG_SESSION_RUNNING_PROG_RECEIVED_SIGINT_PAUSE_PROGRAM
+ if (m_eCurrentDriverState == eDriverState_RunningDebugging)
return MIstatus::success;
-}
-//++ ------------------------------------------------------------------------------------
-// Details: Prepare the client IDE so it will start working/communicating with *this MI
+ // Driver cannot be in the following states to set
+ // eDriverState_RunningDebugging
+ switch (m_eCurrentDriverState) {
+ case eDriverState_NotRunning:
+ case eDriverState_Initialising:
+ case eDriverState_ShuttingDown: {
+ SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
+ return MIstatus::failure;
+ }
+ case eDriverState_RunningDebugging:
+ case eDriverState_RunningNotDebugging:
+ break;
+ case eDriverState_count:
+ SetErrorDescription(
+ CMIUtilString::Format(MIRSRC(IDS_CODE_ERR_INVALID_ENUMERATION_VALUE),
+ "SetDriverStateRunningDebugging()"));
+ return MIstatus::failure;
+ }
+
+ // Driver must be in this state to set eDriverState_RunningDebugging
+ if (m_eCurrentDriverState != eDriverState_RunningNotDebugging) {
+ SetErrorDescription(MIRSRC(IDS_DRIVER_ERR_DRIVER_STATE_ERROR));
+ return MIstatus::failure;
+ }
+
+ m_eCurrentDriverState = eDriverState_RunningDebugging;
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Prepare the client IDE so it will start working/communicating with
+// *this MI
// driver.
// Type: Method.
// Args: None.
@@ -1156,16 +1177,16 @@ CMIDriver::SetDriverStateRunningDebuggin
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMIDriver::InitClientIDEToMIDriver() const
-{
- // Put other IDE init functions here
- return InitClientIDEEclipse();
+bool CMIDriver::InitClientIDEToMIDriver() const {
+ // Put other IDE init functions here
+ return InitClientIDEEclipse();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: The IDE Eclipse when debugging locally expects "(gdb)\n" character
-// sequence otherwise it refuses to communicate and times out. This should be
+// sequence otherwise it refuses to communicate and times out. This
+// should be
// sent to Eclipse before anything else.
// Type: Method.
// Args: None.
@@ -1173,46 +1194,49 @@ CMIDriver::InitClientIDEToMIDriver() con
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMIDriver::InitClientIDEEclipse() const
-{
- return CMICmnStreamStdout::WritePrompt();
+bool CMIDriver::InitClientIDEEclipse() const {
+ return CMICmnStreamStdout::WritePrompt();
}
-//++ ------------------------------------------------------------------------------------
-// Details: Ask *this driver whether it found an executable in the MI Driver's list of
-// arguments which to open and debug. If so instigate commands to set up a debug
+//++
+//------------------------------------------------------------------------------------
+// Details: Ask *this driver whether it found an executable in the MI Driver's
+// list of
+// arguments which to open and debug. If so instigate commands to set
+// up a debug
// session for that executable.
// Type: Method.
// Args: None.
-// Return: bool - True = True = Yes executable given as one of the parameters to the MI
+// Return: bool - True = True = Yes executable given as one of the parameters
+// to the MI
// Driver.
// False = not found.
// Throws: None.
//--
-bool
-CMIDriver::HaveExecutableFileNamePathOnCmdLine() const
-{
- return m_bHaveExecutableFileNamePathOnCmdLine;
+bool CMIDriver::HaveExecutableFileNamePathOnCmdLine() const {
+ return m_bHaveExecutableFileNamePathOnCmdLine;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve from *this driver executable file name path to start a debug session
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve from *this driver executable file name path to start a
+// debug session
// with (if present see HaveExecutableFileNamePathOnCmdLine()).
// Type: Method.
// Args: None.
// Return: CMIUtilString & - Executeable file name path or empty string.
// Throws: None.
//--
-const CMIUtilString &
-CMIDriver::GetExecutableFileNamePathOnCmdLine() const
-{
- return m_strCmdLineArgExecuteableFileNamePath;
+const CMIUtilString &CMIDriver::GetExecutableFileNamePathOnCmdLine() const {
+ return m_strCmdLineArgExecuteableFileNamePath;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Execute commands (by injecting them into the stdin line queue container) and
-// other code to set up the MI Driver such that is can take the executable
+//++
+//------------------------------------------------------------------------------------
+// Details: Execute commands (by injecting them into the stdin line queue
+// container) and
+// other code to set up the MI Driver such that is can take the
+// executable
// argument passed on the command and create a debug session for it.
// Type: Method.
// Args: None.
@@ -1220,124 +1244,124 @@ CMIDriver::GetExecutableFileNamePathOnCm
// MIstatus::failure - Functionality failed.
// Throws: None.
//--
-bool
-CMIDriver::LocalDebugSessionStartupExecuteCommands()
-{
- const CMIUtilString strCmd(CMIUtilString::Format("-file-exec-and-symbols \"%s\"", m_strCmdLineArgExecuteableFileNamePath.AddSlashes().c_str()));
- bool bOk = CMICmnStreamStdout::TextToStdout(strCmd);
- bOk = bOk && InterpretCommand(strCmd);
- bOk = bOk && CMICmnStreamStdout::WritePrompt();
- return bOk;
+bool CMIDriver::LocalDebugSessionStartupExecuteCommands() {
+ const CMIUtilString strCmd(CMIUtilString::Format(
+ "-file-exec-and-symbols \"%s\"",
+ m_strCmdLineArgExecuteableFileNamePath.AddSlashes().c_str()));
+ bool bOk = CMICmnStreamStdout::TextToStdout(strCmd);
+ bOk = bOk && InterpretCommand(strCmd);
+ bOk = bOk && CMICmnStreamStdout::WritePrompt();
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set the MI Driver into "its debugging an executable passed as an argument"
+//++
+//------------------------------------------------------------------------------------
+// Details: Set the MI Driver into "its debugging an executable passed as an
+// argument"
// mode as against running via a client like Eclipse.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIDriver::SetDriverDebuggingArgExecutable()
-{
- m_bDriverDebuggingArgExecutable = true;
+void CMIDriver::SetDriverDebuggingArgExecutable() {
+ m_bDriverDebuggingArgExecutable = true;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve the MI Driver state indicating if it is operating in "its debugging
-// an executable passed as an argument" mode as against running via a client
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve the MI Driver state indicating if it is operating in "its
+// debugging
+// an executable passed as an argument" mode as against running via a
+// client
// like Eclipse.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-bool
-CMIDriver::IsDriverDebuggingArgExecutable() const
-{
- return m_bDriverDebuggingArgExecutable;
+bool CMIDriver::IsDriverDebuggingArgExecutable() const {
+ return m_bDriverDebuggingArgExecutable;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Execute commands from command source file in specified mode, and
// set exit-flag if needed.
// Type: Method.
-// Args: vbAsyncMode - (R) True = execute commands in asynchronous mode, false = otherwise.
+// Args: vbAsyncMode - (R) True = execute commands in asynchronous
+// mode, false = otherwise.
// Return: MIstatus::success - Function succeeded.
// MIstatus::failure - Function failed.
// Throws: None.
//--
-bool
-CMIDriver::ExecuteCommandFile(const bool vbAsyncMode)
-{
- std::ifstream ifsStartScript(m_strCmdLineArgCommandFileNamePath.c_str());
- if (!ifsStartScript.is_open())
- {
- const CMIUtilString errMsg(
- CMIUtilString::Format(MIRSRC(IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN), m_strCmdLineArgCommandFileNamePath.c_str()));
- SetErrorDescription(errMsg.c_str());
- const bool bForceExit = true;
- SetExitApplicationFlag(bForceExit);
- return MIstatus::failure;
+bool CMIDriver::ExecuteCommandFile(const bool vbAsyncMode) {
+ std::ifstream ifsStartScript(m_strCmdLineArgCommandFileNamePath.c_str());
+ if (!ifsStartScript.is_open()) {
+ const CMIUtilString errMsg(
+ CMIUtilString::Format(MIRSRC(IDS_UTIL_FILE_ERR_OPENING_FILE_UNKNOWN),
+ m_strCmdLineArgCommandFileNamePath.c_str()));
+ SetErrorDescription(errMsg.c_str());
+ const bool bForceExit = true;
+ SetExitApplicationFlag(bForceExit);
+ return MIstatus::failure;
+ }
+
+ // Switch lldb to synchronous mode
+ CMICmnLLDBDebugSessionInfo &rSessionInfo(
+ CMICmnLLDBDebugSessionInfo::Instance());
+ const bool bAsyncSetting = rSessionInfo.GetDebugger().GetAsync();
+ rSessionInfo.GetDebugger().SetAsync(vbAsyncMode);
+
+ // Execute commands from file
+ bool bOk = MIstatus::success;
+ CMIUtilString strCommand;
+ while (!m_bExitApp && std::getline(ifsStartScript, strCommand)) {
+ // Print command
+ bOk = CMICmnStreamStdout::TextToStdout(strCommand);
+
+ // Skip if it's a comment or empty line
+ if (strCommand.empty() || strCommand[0] == '#')
+ continue;
+
+ // Execute if no error
+ if (bOk) {
+ CMIUtilThreadLock lock(rSessionInfo.GetSessionMutex());
+ bOk = InterpretCommand(strCommand);
}
- // Switch lldb to synchronous mode
- CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
- const bool bAsyncSetting = rSessionInfo.GetDebugger().GetAsync();
- rSessionInfo.GetDebugger().SetAsync(vbAsyncMode);
-
- // Execute commands from file
- bool bOk = MIstatus::success;
- CMIUtilString strCommand;
- while (!m_bExitApp && std::getline(ifsStartScript, strCommand))
- {
- // Print command
- bOk = CMICmnStreamStdout::TextToStdout(strCommand);
-
- // Skip if it's a comment or empty line
- if (strCommand.empty() || strCommand[0] == '#')
- continue;
-
- // Execute if no error
- if (bOk)
- {
- CMIUtilThreadLock lock(rSessionInfo.GetSessionMutex());
- bOk = InterpretCommand(strCommand);
- }
-
- // Draw the prompt after command will be executed (if enabled)
- bOk = bOk && CMICmnStreamStdout::WritePrompt();
-
- // Exit if there is an error
- if (!bOk)
- {
- const bool bForceExit = true;
- SetExitApplicationFlag(bForceExit);
- break;
- }
+ // Draw the prompt after command will be executed (if enabled)
+ bOk = bOk && CMICmnStreamStdout::WritePrompt();
- // Wait while the handler thread handles incoming events
- CMICmnLLDBDebugger::Instance().WaitForHandleEvent();
+ // Exit if there is an error
+ if (!bOk) {
+ const bool bForceExit = true;
+ SetExitApplicationFlag(bForceExit);
+ break;
}
- // Switch lldb back to initial mode
- rSessionInfo.GetDebugger().SetAsync(bAsyncSetting);
+ // Wait while the handler thread handles incoming events
+ CMICmnLLDBDebugger::Instance().WaitForHandleEvent();
+ }
- return bOk;
+ // Switch lldb back to initial mode
+ rSessionInfo.GetDebugger().SetAsync(bAsyncSetting);
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Gets called when lldb-mi gets a signal. Stops the process if it was SIGINT.
+//++
+//------------------------------------------------------------------------------------
+// Details: Gets called when lldb-mi gets a signal. Stops the process if it was
+// SIGINT.
//
// Type: Method.
// Args: signal that was delivered
// Return: None.
// Throws: None.
//--
-void
-CMIDriver::DeliverSignal(int signal)
-{
- if (signal == SIGINT && (m_eCurrentDriverState == eDriverState_RunningDebugging))
- InterpretCommand("-exec-interrupt");
+void CMIDriver::DeliverSignal(int signal) {
+ if (signal == SIGINT &&
+ (m_eCurrentDriverState == eDriverState_RunningDebugging))
+ InterpretCommand("-exec-interrupt");
}
Modified: lldb/trunk/tools/lldb-mi/MIDriver.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriver.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriver.h (original)
+++ lldb/trunk/tools/lldb-mi/MIDriver.h Tue Sep 6 15:57:50 2016
@@ -13,19 +13,20 @@
#include <queue>
// In-house headers:
-#include "MICmnConfig.h"
+#include "MICmdData.h"
#include "MICmnBase.h"
+#include "MICmnConfig.h"
+#include "MICmnStreamStdin.h"
#include "MIDriverBase.h"
#include "MIDriverMgr.h"
-#include "MICmnStreamStdin.h"
-#include "MICmdData.h"
#include "MIUtilSingletonBase.h"
// Declarations:
class CMICmnLLDBDebugger;
class CMICmnStreamStdout;
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI driver implementation class. A singleton class derived from
// LLDB SBBroadcaster class. Register the instance of *this class with
// the CMIDriverMgr. The CMIDriverMgr sets the driver(s) of to start
@@ -36,129 +37,145 @@ class CMICmnStreamStdout;
class CMIDriver : public CMICmnBase,
public CMIDriverMgr::IDriver,
public CMIDriverBase,
- public MI::ISingleton<CMIDriver>
-{
- friend class MI::ISingleton<CMIDriver>;
-
- // Enumerations:
- public:
- //++ ----------------------------------------------------------------------
- // Details: The MI Driver has a running state which is used to help determine
- // which specific action(s) it should take or not allow.
- // The driver when operational and not shutting down alternates
- // between eDriverState_RunningNotDebugging and
- // eDriverState_RunningDebugging. eDriverState_RunningNotDebugging
- // is normally set when a breakpoint is hit or halted.
- // eDriverState_RunningDebugging is normally set when "exec-continue"
- // or "exec-run" is issued.
- //--
- enum DriverState_e
- {
- eDriverState_NotRunning = 0, // The MI Driver is not operating
- eDriverState_Initialising, // The MI Driver is setting itself up
- eDriverState_RunningNotDebugging, // The MI Driver is operational acting on any MI commands sent to it
- eDriverState_RunningDebugging, // The MI Driver is currently overseeing an inferior program that is running
- eDriverState_ShuttingDown, // The MI Driver is tearing down resources and about exit
- eDriverState_count // Always last
- };
-
- // Methods:
- public:
- // MI system
- bool Initialize() override;
- bool Shutdown() override;
-
- // MI state
- bool GetExitApplicationFlag() const;
- DriverState_e GetCurrentDriverState() const;
- bool SetDriverStateRunningNotDebugging();
- bool SetDriverStateRunningDebugging();
- void SetDriverDebuggingArgExecutable();
- bool IsDriverDebuggingArgExecutable() const;
-
- // MI information about itself
- const CMIUtilString &GetAppNameShort() const;
- const CMIUtilString &GetAppNameLong() const;
- const CMIUtilString &GetVersionDescription() const;
-
- // MI do work
- bool WriteMessageToLog(const CMIUtilString &vMessage);
- bool SetEnableFallThru(const bool vbYes);
- bool GetEnableFallThru() const;
- bool HaveExecutableFileNamePathOnCmdLine() const;
- const CMIUtilString &GetExecutableFileNamePathOnCmdLine() const;
-
- // Overridden:
- public:
- // From CMIDriverMgr::IDriver
- bool DoInitialize() override;
- bool DoShutdown() override;
- bool DoMainLoop() override;
- lldb::SBError DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting) override;
- CMIUtilString GetError() const override;
- const CMIUtilString &GetName() const override;
- lldb::SBDebugger &GetTheDebugger() override;
- bool GetDriverIsGDBMICompatibleDriver() const override;
- bool SetId(const CMIUtilString &vId) override;
- const CMIUtilString &GetId() const override;
- // From CMIDriverBase
- void SetExitApplicationFlag(const bool vbForceExit) override;
- bool DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg) override;
- bool SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver) override;
- FILE *GetStdin() const override;
- FILE *GetStdout() const override;
- FILE *GetStderr() const override;
- const CMIUtilString &GetDriverName() const override;
- const CMIUtilString &GetDriverId() const override;
- void DeliverSignal(int signal) override;
-
- // Typedefs:
- private:
- typedef std::queue<CMIUtilString> QueueStdinLine_t;
-
- // Methods:
- private:
- /* ctor */ CMIDriver();
- /* ctor */ CMIDriver(const CMIDriver &);
- void operator=(const CMIDriver &);
-
- lldb::SBError ParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting);
- bool DoAppQuit();
- bool InterpretCommand(const CMIUtilString &vTextLine);
- bool InterpretCommandThisDriver(const CMIUtilString &vTextLine, bool &vwbCmdYesValid);
- CMIUtilString WrapCLICommandIntoMICommand(const CMIUtilString &vTextLine) const;
- bool InterpretCommandFallThruDriver(const CMIUtilString &vTextLine, bool &vwbCmdYesValid);
- bool ExecuteCommand(const SMICmdData &vCmdData);
- bool StartWorkerThreads();
- bool StopWorkerThreads();
- bool InitClientIDEToMIDriver() const;
- bool InitClientIDEEclipse() const;
- bool LocalDebugSessionStartupExecuteCommands();
- bool ExecuteCommandFile(const bool vbAsyncMode);
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMIDriver() override;
-
- // Attributes:
- private:
- static const CMIUtilString ms_constAppNameShort;
- static const CMIUtilString ms_constAppNameLong;
- static const CMIUtilString ms_constMIVersion;
- //
- bool m_bFallThruToOtherDriverEnabled; // True = yes fall through, false = do not pass on command
- CMIUtilThreadMutex m_threadMutex;
- bool m_bDriverIsExiting; // True = yes, driver told to quit, false = continue working
- void *m_handleMainThread; // *this driver is run by the main thread
- CMICmnStreamStdin &m_rStdin;
- CMICmnLLDBDebugger &m_rLldbDebugger;
- CMICmnStreamStdout &m_rStdOut;
- DriverState_e m_eCurrentDriverState;
- bool m_bHaveExecutableFileNamePathOnCmdLine; // True = yes, executable given as one of the parameters to the MI Driver, false = not found
- CMIUtilString m_strCmdLineArgExecuteableFileNamePath;
- bool m_bDriverDebuggingArgExecutable; // True = the MI Driver (MI mode) is debugging executable passed as argument,
- // false = running via a client (e.g. Eclipse)
- bool m_bHaveCommandFileNamePathOnCmdLine; // True = file with initial commands given as one of the parameters to the MI Driver, false = not found
- CMIUtilString m_strCmdLineArgCommandFileNamePath;
+ public MI::ISingleton<CMIDriver> {
+ friend class MI::ISingleton<CMIDriver>;
+
+ // Enumerations:
+public:
+ //++ ----------------------------------------------------------------------
+ // Details: The MI Driver has a running state which is used to help determine
+ // which specific action(s) it should take or not allow.
+ // The driver when operational and not shutting down alternates
+ // between eDriverState_RunningNotDebugging and
+ // eDriverState_RunningDebugging. eDriverState_RunningNotDebugging
+ // is normally set when a breakpoint is hit or halted.
+ // eDriverState_RunningDebugging is normally set when "exec-continue"
+ // or "exec-run" is issued.
+ //--
+ enum DriverState_e {
+ eDriverState_NotRunning = 0, // The MI Driver is not operating
+ eDriverState_Initialising, // The MI Driver is setting itself up
+ eDriverState_RunningNotDebugging, // The MI Driver is operational acting on
+ // any MI commands sent to it
+ eDriverState_RunningDebugging, // The MI Driver is currently overseeing an
+ // inferior program that is running
+ eDriverState_ShuttingDown, // The MI Driver is tearing down resources and
+ // about exit
+ eDriverState_count // Always last
+ };
+
+ // Methods:
+public:
+ // MI system
+ bool Initialize() override;
+ bool Shutdown() override;
+
+ // MI state
+ bool GetExitApplicationFlag() const;
+ DriverState_e GetCurrentDriverState() const;
+ bool SetDriverStateRunningNotDebugging();
+ bool SetDriverStateRunningDebugging();
+ void SetDriverDebuggingArgExecutable();
+ bool IsDriverDebuggingArgExecutable() const;
+
+ // MI information about itself
+ const CMIUtilString &GetAppNameShort() const;
+ const CMIUtilString &GetAppNameLong() const;
+ const CMIUtilString &GetVersionDescription() const;
+
+ // MI do work
+ bool WriteMessageToLog(const CMIUtilString &vMessage);
+ bool SetEnableFallThru(const bool vbYes);
+ bool GetEnableFallThru() const;
+ bool HaveExecutableFileNamePathOnCmdLine() const;
+ const CMIUtilString &GetExecutableFileNamePathOnCmdLine() const;
+
+ // Overridden:
+public:
+ // From CMIDriverMgr::IDriver
+ bool DoInitialize() override;
+ bool DoShutdown() override;
+ bool DoMainLoop() override;
+ lldb::SBError DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut,
+ bool &vwbExiting) override;
+ CMIUtilString GetError() const override;
+ const CMIUtilString &GetName() const override;
+ lldb::SBDebugger &GetTheDebugger() override;
+ bool GetDriverIsGDBMICompatibleDriver() const override;
+ bool SetId(const CMIUtilString &vId) override;
+ const CMIUtilString &GetId() const override;
+ // From CMIDriverBase
+ void SetExitApplicationFlag(const bool vbForceExit) override;
+ bool DoFallThruToAnotherDriver(const CMIUtilString &vCmd,
+ CMIUtilString &vwErrMsg) override;
+ bool SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver) override;
+ FILE *GetStdin() const override;
+ FILE *GetStdout() const override;
+ FILE *GetStderr() const override;
+ const CMIUtilString &GetDriverName() const override;
+ const CMIUtilString &GetDriverId() const override;
+ void DeliverSignal(int signal) override;
+
+ // Typedefs:
+private:
+ typedef std::queue<CMIUtilString> QueueStdinLine_t;
+
+ // Methods:
+private:
+ /* ctor */ CMIDriver();
+ /* ctor */ CMIDriver(const CMIDriver &);
+ void operator=(const CMIDriver &);
+
+ lldb::SBError ParseArgs(const int argc, const char *argv[], FILE *vpStdOut,
+ bool &vwbExiting);
+ bool DoAppQuit();
+ bool InterpretCommand(const CMIUtilString &vTextLine);
+ bool InterpretCommandThisDriver(const CMIUtilString &vTextLine,
+ bool &vwbCmdYesValid);
+ CMIUtilString
+ WrapCLICommandIntoMICommand(const CMIUtilString &vTextLine) const;
+ bool InterpretCommandFallThruDriver(const CMIUtilString &vTextLine,
+ bool &vwbCmdYesValid);
+ bool ExecuteCommand(const SMICmdData &vCmdData);
+ bool StartWorkerThreads();
+ bool StopWorkerThreads();
+ bool InitClientIDEToMIDriver() const;
+ bool InitClientIDEEclipse() const;
+ bool LocalDebugSessionStartupExecuteCommands();
+ bool ExecuteCommandFile(const bool vbAsyncMode);
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMIDriver() override;
+
+ // Attributes:
+private:
+ static const CMIUtilString ms_constAppNameShort;
+ static const CMIUtilString ms_constAppNameLong;
+ static const CMIUtilString ms_constMIVersion;
+ //
+ bool m_bFallThruToOtherDriverEnabled; // True = yes fall through, false = do
+ // not pass on command
+ CMIUtilThreadMutex m_threadMutex;
+ bool m_bDriverIsExiting; // True = yes, driver told to quit, false = continue
+ // working
+ void *m_handleMainThread; // *this driver is run by the main thread
+ CMICmnStreamStdin &m_rStdin;
+ CMICmnLLDBDebugger &m_rLldbDebugger;
+ CMICmnStreamStdout &m_rStdOut;
+ DriverState_e m_eCurrentDriverState;
+ bool m_bHaveExecutableFileNamePathOnCmdLine; // True = yes, executable given
+ // as one of the parameters to
+ // the MI Driver, false = not
+ // found
+ CMIUtilString m_strCmdLineArgExecuteableFileNamePath;
+ bool m_bDriverDebuggingArgExecutable; // True = the MI Driver (MI mode) is
+ // debugging executable passed as
+ // argument,
+ // false = running via a client (e.g. Eclipse)
+ bool m_bHaveCommandFileNamePathOnCmdLine; // True = file with initial commands
+ // given as one of the parameters to
+ // the MI Driver, false = not found
+ CMIUtilString m_strCmdLineArgCommandFileNamePath;
};
Modified: lldb/trunk/tools/lldb-mi/MIDriverBase.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriverBase.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriverBase.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIDriverBase.cpp Tue Sep 6 15:57:50 2016
@@ -8,13 +8,14 @@
//===----------------------------------------------------------------------===//
// Third party headers:
-#include "lldb/API/SBEvent.h"
#include "lldb/API/SBBroadcaster.h"
+#include "lldb/API/SBEvent.h"
// In-house headers:
#include "MIDriverBase.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriverBase constructor.
// Type: Method.
// Args: None.
@@ -22,26 +23,22 @@
// Throws: None.
//--
CMIDriverBase::CMIDriverBase()
- : m_pDriverFallThru(nullptr)
- , m_pDriverParent(nullptr)
- , m_bExitApp(false)
-{
-}
+ : m_pDriverFallThru(nullptr), m_pDriverParent(nullptr), m_bExitApp(false) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriverBase destructor.
// Type: Overrideable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIDriverBase::~CMIDriverBase()
-{
- m_pDriverFallThru = NULL;
-}
+CMIDriverBase::~CMIDriverBase() { m_pDriverFallThru = NULL; }
-//++ ------------------------------------------------------------------------------------
-// Details: This function allows *this driver to call on another driver to perform work
+//++
+//------------------------------------------------------------------------------------
+// Details: This function allows *this driver to call on another driver to
+// perform work
// should this driver not be able to handle the client data input.
// Type: Overrideable.
// Check the error message if the function returns a failure.
@@ -52,15 +49,16 @@ CMIDriverBase::~CMIDriverBase()
// MIstatus::failure - Command failed.
// Throws: None.
//--
-bool
-CMIDriverBase::DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg)
-{
- // Do nothing - override and implement. Use m_pDriverFallThru.
- return MIstatus::success;
+bool CMIDriverBase::DoFallThruToAnotherDriver(const CMIUtilString &vCmd,
+ CMIUtilString &vwErrMsg) {
+ // Do nothing - override and implement. Use m_pDriverFallThru.
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: This function allows *this driver to call on another driver to perform work
+//++
+//------------------------------------------------------------------------------------
+// Details: This function allows *this driver to call on another driver to
+// perform work
// should this driver not be able to handle the client data input.
// Type: Overrideable.
// Args: vrOtherDriver - (R) Reference to another driver object.
@@ -68,18 +66,18 @@ CMIDriverBase::DoFallThruToAnotherDriver
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverBase::SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver)
-{
- MIunused(vrOtherDriver);
+bool CMIDriverBase::SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver) {
+ MIunused(vrOtherDriver);
- // Do nothing - override and implement. Set m_pDriverFallThru.
+ // Do nothing - override and implement. Set m_pDriverFallThru.
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: This function allows *this driver to call functionality on the parent driver
+//++
+//------------------------------------------------------------------------------------
+// Details: This function allows *this driver to call functionality on the
+// parent driver
// ask for information for example.
// Type: Overrideable.
// Args: vrOtherDriver - (R) Reference to another driver object.
@@ -87,18 +85,18 @@ CMIDriverBase::SetDriverToFallThruTo(con
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverBase::SetDriverParent(const CMIDriverBase &vrOtherDriver)
-{
- MIunused(vrOtherDriver);
+bool CMIDriverBase::SetDriverParent(const CMIDriverBase &vrOtherDriver) {
+ MIunused(vrOtherDriver);
- // Do nothing - override and implement. Set m_pDriverParent.
+ // Do nothing - override and implement. Set m_pDriverParent.
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve the parent driver to *this driver if one assigned. If assigned *this
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve the parent driver to *this driver if one assigned. If
+// assigned *this
// is the pass through driver that the parent driver passes work to.
// Type: Method.
// Args: None.
@@ -106,14 +104,14 @@ CMIDriverBase::SetDriverParent(const CMI
// - NULL = there is not parent to *this driver.
// Throws: None.
//--
-CMIDriverBase *
-CMIDriverBase::GetDriversParent() const
-{
- return m_pDriverParent;
+CMIDriverBase *CMIDriverBase::GetDriversParent() const {
+ return m_pDriverParent;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve the pointer to the other fall through driver *this driver is using
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve the pointer to the other fall through driver *this driver
+// is using
// (or not using).
// Type: Method.
// Args: None.
@@ -121,72 +119,73 @@ CMIDriverBase::GetDriversParent() const
// - NULL if no driver set.
// Throws: None.
//--
-CMIDriverBase *
-CMIDriverBase::GetDriverToFallThruTo() const
-{
- return m_pDriverFallThru;
+CMIDriverBase *CMIDriverBase::GetDriverToFallThruTo() const {
+ return m_pDriverFallThru;
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a file stream to other drivers on which *this driver
-// write's out to and they read as expected input. *this driver is passing
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a file stream to other drivers on which *this
+// driver
+// write's out to and they read as expected input. *this driver is
+// passing
// through commands to the (child) pass through assigned driver.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriverBase::GetStdin() const
-{
- // Do nothing - override and implement
- return nullptr;
+FILE *CMIDriverBase::GetStdin() const {
+ // Do nothing - override and implement
+ return nullptr;
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a file stream to other pass through assigned drivers
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a file stream to other pass through assigned
+// drivers
// so they know what to write to.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriverBase::GetStdout() const
-{
- // Do nothing - override and implement
- return nullptr;
+FILE *CMIDriverBase::GetStdout() const {
+ // Do nothing - override and implement
+ return nullptr;
}
-//++ ------------------------------------------------------------------------------------
-// Details: *this driver provides a error file stream to other pass through assigned drivers
+//++
+//------------------------------------------------------------------------------------
+// Details: *this driver provides a error file stream to other pass through
+// assigned drivers
// so they know what to write to.
// Type: Overrideable.
// Args: None.
// Return: FILE * - Pointer to stream.
// Throws: None.
//--
-FILE *
-CMIDriverBase::GetStderr() const
-{
- // Do nothing - override and implement
- return nullptr;
+FILE *CMIDriverBase::GetStderr() const {
+ // Do nothing - override and implement
+ return nullptr;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Set the MI Driver's exit application flag. The application checks this flag
+//++
+//------------------------------------------------------------------------------------
+// Details: Set the MI Driver's exit application flag. The application checks
+// this flag
// after every stdin line is read so the exit may not be instantaneous.
-// If vbForceExit is false the MI Driver queries its state and determines if is
+// If vbForceExit is false the MI Driver queries its state and
+// determines if is
// should exit or continue operating depending on that running state.
// Type: Overrideable.
-// Args: vbForceExit - (R) True = Do not query, set state to exit, false = query if can/should exit right now.
+// Args: vbForceExit - (R) True = Do not query, set state to exit, false =
+// query if can/should exit right now.
// Return: None.
// Throws: None.
//--
-void
-CMIDriverBase::SetExitApplicationFlag(const bool vbForceExit)
-{
- MIunused(vbForceExit);
+void CMIDriverBase::SetExitApplicationFlag(const bool vbForceExit) {
+ MIunused(vbForceExit);
- // Do nothing - override and implement
+ // Do nothing - override and implement
}
Modified: lldb/trunk/tools/lldb-mi/MIDriverBase.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriverBase.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriverBase.h (original)
+++ lldb/trunk/tools/lldb-mi/MIDriverBase.h Tue Sep 6 15:57:50 2016
@@ -10,19 +10,19 @@
#pragma once
// Third party headers:
-#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBBroadcaster.h"
+#include "lldb/API/SBDebugger.h"
// In-house headers:
#include "MIUtilString.h"
// Declarations:
-namespace lldb
-{
+namespace lldb {
class SBBroadcaster;
}
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI driver base implementation class. This class has been created so
// not have to edit the lldb::SBBroadcaster class code. Functionality
// and attributes need to be common to the LLDB Driver class and the
@@ -32,35 +32,37 @@ class SBBroadcaster;
// Each driver instance (the CMIDriver, LLDB::Driver) has its own
// LLDB::SBDebugger object.
//--
-class CMIDriverBase
-{
- // Methods:
- public:
- /* ctor */ CMIDriverBase();
-
- CMIDriverBase *GetDriverToFallThruTo() const;
- CMIDriverBase *GetDriversParent() const;
-
- // Overrideable:
- public:
- /* dtor */ virtual ~CMIDriverBase();
-
- virtual bool DoFallThruToAnotherDriver(const CMIUtilString &vCmd, CMIUtilString &vwErrMsg);
- virtual bool SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver);
- virtual bool SetDriverParent(const CMIDriverBase &vrOtherDriver);
- virtual const CMIUtilString &GetDriverName() const = 0;
- virtual const CMIUtilString &GetDriverId() const = 0;
- virtual void SetExitApplicationFlag(const bool vbForceExit);
-
- // MI provide information for the pass through (child) assigned driver
- virtual FILE *GetStdin() const;
- virtual FILE *GetStdout() const;
- virtual FILE *GetStderr() const;
-
- // Attributes:
- protected:
- CMIDriverBase *m_pDriverFallThru; // Child driver to use should *this driver not be able to handle client input
- CMIDriverBase *m_pDriverParent; // The parent driver who passes work to *this driver to do work
- CMIUtilString m_strDriverId;
- bool m_bExitApp; // True = Yes, exit application, false = continue execution
+class CMIDriverBase {
+ // Methods:
+public:
+ /* ctor */ CMIDriverBase();
+
+ CMIDriverBase *GetDriverToFallThruTo() const;
+ CMIDriverBase *GetDriversParent() const;
+
+ // Overrideable:
+public:
+ /* dtor */ virtual ~CMIDriverBase();
+
+ virtual bool DoFallThruToAnotherDriver(const CMIUtilString &vCmd,
+ CMIUtilString &vwErrMsg);
+ virtual bool SetDriverToFallThruTo(const CMIDriverBase &vrOtherDriver);
+ virtual bool SetDriverParent(const CMIDriverBase &vrOtherDriver);
+ virtual const CMIUtilString &GetDriverName() const = 0;
+ virtual const CMIUtilString &GetDriverId() const = 0;
+ virtual void SetExitApplicationFlag(const bool vbForceExit);
+
+ // MI provide information for the pass through (child) assigned driver
+ virtual FILE *GetStdin() const;
+ virtual FILE *GetStdout() const;
+ virtual FILE *GetStderr() const;
+
+ // Attributes:
+protected:
+ CMIDriverBase *m_pDriverFallThru; // Child driver to use should *this driver
+ // not be able to handle client input
+ CMIDriverBase *m_pDriverParent; // The parent driver who passes work to *this
+ // driver to do work
+ CMIUtilString m_strDriverId;
+ bool m_bExitApp; // True = Yes, exit application, false = continue execution
};
Modified: lldb/trunk/tools/lldb-mi/MIDriverMain.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriverMain.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriverMain.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIDriverMain.cpp Tue Sep 6 15:57:50 2016
@@ -9,78 +9,87 @@
// Overview: Defines the entry point for the console application.
// The MI application (project name MI) runs in two modes:
-// An LLDB native driver mode where it acts no different from the LLDB driver.
+// An LLDB native driver mode where it acts no different from the
+// LLDB driver.
// The other mode is the MI when it finds on the command line
-// the --interpreter option. Command line argument --help on its own will give
-// help for the LLDB driver. If entered with --interpreter then MI help will
+// the --interpreter option. Command line argument --help on its
+// own will give
+// help for the LLDB driver. If entered with --interpreter then MI
+// help will
// provided.
-// To implement new MI commands derive a new command class from the command base
-// class. To enable the new command for interpretation add the new command class
+// To implement new MI commands derive a new command class from the
+// command base
+// class. To enable the new command for interpretation add the new
+// command class
// to the command factory. The files of relevance are:
// MICmdCommands.cpp
// MICmdBase.h / .cpp
// MICmdCmd.h / .cpp
-
#if defined(_MSC_VER)
-#define _INC_SIGNAL // Stop window's signal.h being included - CODETAG_IOR_SIGNALS
+#define _INC_SIGNAL // Stop window's signal.h being included -
+ // CODETAG_IOR_SIGNALS
#endif // _MSC_VER
// Third party headers:
-#include <stdio.h>
#include "lldb/API/SBHostOS.h"
+#include <stdio.h>
// In house headers:
#include "MICmnConfig.h"
-#include "Platform.h" // Define signals - CODETAG_IOR_SIGNALS
-#include "MIDriverMgr.h"
-#include "MIDriver.h"
#include "MICmnResources.h"
#include "MICmnStreamStdin.h"
+#include "MIDriver.h"
+#include "MIDriverMgr.h"
#include "MIUtilDebug.h"
-
+#include "Platform.h" // Define signals - CODETAG_IOR_SIGNALS
#if defined(_MSC_VER)
-#pragma warning(once : 4530) // Warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
-#endif // _MSC_VER
+#pragma warning( \
+ once : 4530) // Warning C4530: C++ exception handler used, but unwind
+ // semantics are not enabled. Specify /EHsc
+#endif // _MSC_VER
// CODETAG_IOR_SIGNALS
-//++ ------------------------------------------------------------------------------------
-// Details: The SIGINT signal is sent to a process by its controlling terminal when a
-// user wishes to interrupt the process. This is typically initiated by pressing
-// Control-C, but on some systems, the "delete" character or "break" key can be
+//++
+//------------------------------------------------------------------------------------
+// Details: The SIGINT signal is sent to a process by its controlling terminal
+// when a
+// user wishes to interrupt the process. This is typically initiated by
+// pressing
+// Control-C, but on some systems, the "delete" character or "break"
+// key can be
// used.
-// Be aware this function may be called on another thread besides the main thread.
+// Be aware this function may be called on another thread besides the
+// main thread.
// Type: Function.
// Args: vSigno - (R) Signal number.
// Return: None.
// Throws: None.
//--
-void
-sigint_handler(int vSigno)
-{
+void sigint_handler(int vSigno) {
#ifdef _WIN32 // Restore handler as it is not persistent on Windows
- signal(SIGINT, sigint_handler);
+ signal(SIGINT, sigint_handler);
#endif
- static bool g_interrupt_sent = false;
- CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
- lldb::SBDebugger *pDebugger = rDriverMgr.DriverGetTheDebugger();
- if (pDebugger != nullptr)
- {
- if (!g_interrupt_sent)
- {
- g_interrupt_sent = true;
- pDebugger->DispatchInputInterrupt();
- g_interrupt_sent = false;
- }
+ static bool g_interrupt_sent = false;
+ CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
+ lldb::SBDebugger *pDebugger = rDriverMgr.DriverGetTheDebugger();
+ if (pDebugger != nullptr) {
+ if (!g_interrupt_sent) {
+ g_interrupt_sent = true;
+ pDebugger->DispatchInputInterrupt();
+ g_interrupt_sent = false;
}
+ }
- // Send signal to driver so that it can take suitable action
- rDriverMgr.DeliverSignal (vSigno);
+ // Send signal to driver so that it can take suitable action
+ rDriverMgr.DeliverSignal(vSigno);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Init the MI driver system. Initialize the whole driver system which includes
+//++
+//------------------------------------------------------------------------------------
+// Details: Init the MI driver system. Initialize the whole driver system which
+// includes
// both the original LLDB driver and the MI driver.
// Type: Function.
// Args: None.
@@ -88,95 +97,104 @@ sigint_handler(int vSigno)
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-DriverSystemInit()
-{
- bool bOk = MIstatus::success;
- CMIDriver &rMIDriver = CMIDriver::Instance();
- CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
- bOk = rDriverMgr.Initialize();
-
- // Register MIDriver first as it needs to initialize and be ready
- // for the Driver to get information from MIDriver when it initializes
- // (LLDB Driver is registered with the Driver Manager in MI's Initialize())
- bOk = bOk && rDriverMgr.RegisterDriver(rMIDriver, "MIDriver"); // Will be main driver
+bool DriverSystemInit() {
+ bool bOk = MIstatus::success;
+ CMIDriver &rMIDriver = CMIDriver::Instance();
+ CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
+ bOk = rDriverMgr.Initialize();
+
+ // Register MIDriver first as it needs to initialize and be ready
+ // for the Driver to get information from MIDriver when it initializes
+ // (LLDB Driver is registered with the Driver Manager in MI's Initialize())
+ bOk = bOk &&
+ rDriverMgr.RegisterDriver(rMIDriver, "MIDriver"); // Will be main driver
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Shutdown the debugger system. Release / terminate resources external to
+//++
+//------------------------------------------------------------------------------------
+// Details: Shutdown the debugger system. Release / terminate resources external
+// to
// specifically the MI driver.
// Type: Function.
-// Args: vbAppExitOk - (R) True = No problems, false = App exiting with problems (investigate!).
+// Args: vbAppExitOk - (R) True = No problems, false = App exiting with
+// problems (investigate!).
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-DriverSystemShutdown(const bool vbAppExitOk)
-{
- bool bOk = MIstatus::success;
-
- // *** Order is important here ***
- CMIDriverMgr::Instance().Shutdown();
- return bOk;
+bool DriverSystemShutdown(const bool vbAppExitOk) {
+ bool bOk = MIstatus::success;
+
+ // *** Order is important here ***
+ CMIDriverMgr::Instance().Shutdown();
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: MI's application start point of execution. The application runs in two modes.
-// An LLDB native driver mode where it acts no different from the LLDB driver.
+//++
+//------------------------------------------------------------------------------------
+// Details: MI's application start point of execution. The application runs in
+// two modes.
+// An LLDB native driver mode where it acts no different from the LLDB
+// driver.
// The other mode is the MI when it finds on the command line
-// the --interpreter option. Command line argument --help on its own will give
-// help for the LLDB driver. If entered with --interpreter then application
+// the --interpreter option. Command line argument --help on its own
+// will give
+// help for the LLDB driver. If entered with --interpreter then
+// application
// help will provided.
// Type: Method.
-// Args: argc - (R) An integer that contains the count of arguments that follow in
-// argv. The argc parameter is always greater than or equal to 1.
-// argv - (R) An array of null-terminated strings representing command-line
-// arguments entered by the user of the program. By convention,
-// argv[0] is the command with which the program is invoked.
+// Args: argc - (R) An integer that contains the count of arguments that
+// follow in
+// argv. The argc parameter is always greater than or
+// equal to 1.
+// argv - (R) An array of null-terminated strings representing
+// command-line
+// arguments entered by the user of the program. By
+// convention,
+// argv[0] is the command with which the program is
+// invoked.
// Return: int - 0 = Normal exit, program success.
-// >0 = Program success with status i.e. Control-C signal status
+// >0 = Program success with status i.e. Control-C signal
+// status
// <0 = Program failed.
-// -1 = Program failed reason not specified here, see MI log file.
+// -1 = Program failed reason not specified here, see MI log
+// file.
// -1000 = Program failed did not initialize successfully.
// Throws: None.
//--
-int
-main(int argc, char const *argv[])
-{
+int main(int argc, char const *argv[]) {
#if MICONFIG_DEBUG_SHOW_ATTACH_DBG_DLG
#ifdef _WIN32
- CMIUtilDebug::ShowDlgWaitForDbgAttach();
+ CMIUtilDebug::ShowDlgWaitForDbgAttach();
#else
- CMIUtilDebug::WaitForDbgAttachInfinteLoop();
+ CMIUtilDebug::WaitForDbgAttachInfinteLoop();
#endif // _WIN32
#endif // MICONFIG_DEBUG_SHOW_ATTACH_DBG_DLG
- // *** Order is important here ***
- bool bOk = DriverSystemInit();
- if (!bOk)
- {
- DriverSystemShutdown(bOk);
- return -1000;
- }
+ // *** Order is important here ***
+ bool bOk = DriverSystemInit();
+ if (!bOk) {
+ DriverSystemShutdown(bOk);
+ return -1000;
+ }
- // CODETAG_IOR_SIGNALS
- signal(SIGINT, sigint_handler);
+ // CODETAG_IOR_SIGNALS
+ signal(SIGINT, sigint_handler);
- bool bExiting = false;
- CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
- bOk = bOk && rDriverMgr.ParseArgs(argc, argv, bExiting);
- if (bOk && !bExiting)
- bOk = rDriverMgr.DriverParseArgs(argc, argv, stdout, bExiting);
- if (bOk && !bExiting)
- bOk = rDriverMgr.DriverMainLoop();
+ bool bExiting = false;
+ CMIDriverMgr &rDriverMgr = CMIDriverMgr::Instance();
+ bOk = bOk && rDriverMgr.ParseArgs(argc, argv, bExiting);
+ if (bOk && !bExiting)
+ bOk = rDriverMgr.DriverParseArgs(argc, argv, stdout, bExiting);
+ if (bOk && !bExiting)
+ bOk = rDriverMgr.DriverMainLoop();
- // Logger and other resources shutdown now
- DriverSystemShutdown(bOk);
+ // Logger and other resources shutdown now
+ DriverSystemShutdown(bOk);
- const int appResult = bOk ? 0 : -1;
+ const int appResult = bOk ? 0 : -1;
- return appResult;
+ return appResult;
}
Modified: lldb/trunk/tools/lldb-mi/MIDriverMgr.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriverMgr.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriverMgr.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIDriverMgr.cpp Tue Sep 6 15:57:50 2016
@@ -11,40 +11,36 @@
#include "lldb/API/SBError.h"
// In-house headers:
-#include "MIDriverMgr.h"
-#include "MICmnResources.h"
#include "MICmnLog.h"
#include "MICmnLogMediumFile.h"
-#include "MIDriver.h"
+#include "MICmnResources.h"
#include "MICmnStreamStdout.h"
+#include "MIDriver.h"
+#include "MIDriverMgr.h"
#include "MIUtilSingletonHelper.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriverMgr constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIDriverMgr::CMIDriverMgr()
- : m_pDriverCurrent(nullptr)
- , m_bInMi2Mode(false)
-{
-}
+CMIDriverMgr::CMIDriverMgr() : m_pDriverCurrent(nullptr), m_bInMi2Mode(false) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIDriverMgr destructor.
// Type: Overridden.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIDriverMgr::~CMIDriverMgr()
-{
- Shutdown();
-}
+CMIDriverMgr::~CMIDriverMgr() { Shutdown(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Initialize *this manager.
// Type: Method.
// Args: None.
@@ -52,78 +48,81 @@ CMIDriverMgr::~CMIDriverMgr()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::Initialize()
-{
- m_clientUsageRefCnt++;
+bool CMIDriverMgr::Initialize() {
+ m_clientUsageRefCnt++;
- ClrErrorDescription();
+ ClrErrorDescription();
- if (m_bInitialized)
- return MIstatus::success;
+ if (m_bInitialized)
+ return MIstatus::success;
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
- // Note initialisation order is important here as some resources depend on previous
- MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
- MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
-
- m_bInitialized = bOk;
-
- if (!bOk)
- {
- CMIUtilString strInitError(CMIUtilString::Format(MIRSRC(IDS_MI_INIT_ERR_DRIVERMGR), errMsg.c_str()));
- SetErrorDescription(strInitError);
- return MIstatus::failure;
- }
-
- return bOk;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Unbind detach or release resources used by this server in general common
-// functionality shared between versions of any server interfaces implemented.
+ // Note initialisation order is important here as some resources depend on
+ // previous
+ MI::ModuleInit<CMICmnLog>(IDS_MI_INIT_ERR_LOG, bOk, errMsg);
+ MI::ModuleInit<CMICmnResources>(IDS_MI_INIT_ERR_RESOURCES, bOk, errMsg);
+
+ m_bInitialized = bOk;
+
+ if (!bOk) {
+ CMIUtilString strInitError(CMIUtilString::Format(
+ MIRSRC(IDS_MI_INIT_ERR_DRIVERMGR), errMsg.c_str()));
+ SetErrorDescription(strInitError);
+ return MIstatus::failure;
+ }
+
+ return bOk;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Unbind detach or release resources used by this server in general
+// common
+// functionality shared between versions of any server interfaces
+// implemented.
// Type: Method.
-// Args: vbAppExitOk - (R) True = No problems, false = App exiting with problems (investigate!).
+// Args: vbAppExitOk - (R) True = No problems, false = App exiting with
+// problems (investigate!).
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::Shutdown()
-{
- // Do not want a ref counter because this function needs to be called how ever this
- // application stops running
- // if( --m_clientUsageRefCnt > 0 )
- // return MIstatus::success;
+bool CMIDriverMgr::Shutdown() {
+ // Do not want a ref counter because this function needs to be called how ever
+ // this
+ // application stops running
+ // if( --m_clientUsageRefCnt > 0 )
+ // return MIstatus::success;
- ClrErrorDescription();
+ ClrErrorDescription();
- if (!m_bInitialized)
- return MIstatus::success;
+ if (!m_bInitialized)
+ return MIstatus::success;
- m_bInitialized = false;
+ m_bInitialized = false;
- bool bOk = MIstatus::success;
- CMIUtilString errMsg;
+ bool bOk = MIstatus::success;
+ CMIUtilString errMsg;
- // Tidy up
- UnregisterDriverAll();
+ // Tidy up
+ UnregisterDriverAll();
- // Note shutdown order is important here
- MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
- MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
-
- if (!bOk)
- {
- SetErrorDescriptionn(MIRSRC(IDS_MI_SHTDWN_ERR_DRIVERMGR), errMsg.c_str());
- }
+ // Note shutdown order is important here
+ MI::ModuleShutdown<CMICmnResources>(IDE_MI_SHTDWN_ERR_RESOURCES, bOk, errMsg);
+ MI::ModuleShutdown<CMICmnLog>(IDS_MI_SHTDWN_ERR_LOG, bOk, errMsg);
- return bOk;
+ if (!bOk) {
+ SetErrorDescriptionn(MIRSRC(IDS_MI_SHTDWN_ERR_DRIVERMGR), errMsg.c_str());
+ }
+
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Unregister all the Driver registered with *this manager. The manager also
+//++
+//------------------------------------------------------------------------------------
+// Details: Unregister all the Driver registered with *this manager. The manager
+// also
// deletes
// Type: Method.
// Args: None.
@@ -131,29 +130,30 @@ CMIDriverMgr::Shutdown()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::UnregisterDriverAll()
-{
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
- while (it != m_mapDriverIdToDriver.end())
- {
- IDriver *pDriver = (*it).second;
- pDriver->DoShutdown();
-
- // Next
- ++it;
- }
-
- m_mapDriverIdToDriver.clear();
- m_pDriverCurrent = NULL;
-
- return MIstatus::success;
-}
+bool CMIDriverMgr::UnregisterDriverAll() {
+ MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
+ while (it != m_mapDriverIdToDriver.end()) {
+ IDriver *pDriver = (*it).second;
+ pDriver->DoShutdown();
-//++ ------------------------------------------------------------------------------------
-// Details: Register a driver with *this Driver Manager. Call SetUseThisDriverToDoWork()
-// inform the manager which driver is the one to the work. The manager calls
-// the driver's init function which must be successful in order to complete the
+ // Next
+ ++it;
+ }
+
+ m_mapDriverIdToDriver.clear();
+ m_pDriverCurrent = NULL;
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Register a driver with *this Driver Manager. Call
+// SetUseThisDriverToDoWork()
+// inform the manager which driver is the one to the work. The manager
+// calls
+// the driver's init function which must be successful in order to
+// complete the
// registration.
// Type: Method.
// Args: vrDriver - (R) The driver to register.
@@ -162,30 +162,31 @@ CMIDriverMgr::UnregisterDriverAll()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::RegisterDriver(const IDriver &vrDriver, const CMIUtilString &vrDriverID)
-{
- if (HaveDriverAlready(vrDriver))
- return MIstatus::success;
-
- IDriver *pDriver = const_cast<IDriver *>(&vrDriver);
- if (!pDriver->SetId(vrDriverID))
- return MIstatus::failure;
- if (!pDriver->DoInitialize())
- {
- SetErrorDescriptionn(MIRSRC(IDS_DRIVERMGR_DRIVER_ERR_INIT), pDriver->GetName().c_str(), vrDriverID.c_str(),
- pDriver->GetError().c_str());
- return MIstatus::failure;
- }
-
- MapPairDriverIdToDriver_t pr(vrDriverID, pDriver);
- m_mapDriverIdToDriver.insert(pr);
-
+bool CMIDriverMgr::RegisterDriver(const IDriver &vrDriver,
+ const CMIUtilString &vrDriverID) {
+ if (HaveDriverAlready(vrDriver))
return MIstatus::success;
-}
-//++ ------------------------------------------------------------------------------------
-// Details: Query the Driver Manager to see if *this manager has the driver already
+ IDriver *pDriver = const_cast<IDriver *>(&vrDriver);
+ if (!pDriver->SetId(vrDriverID))
+ return MIstatus::failure;
+ if (!pDriver->DoInitialize()) {
+ SetErrorDescriptionn(MIRSRC(IDS_DRIVERMGR_DRIVER_ERR_INIT),
+ pDriver->GetName().c_str(), vrDriverID.c_str(),
+ pDriver->GetError().c_str());
+ return MIstatus::failure;
+ }
+
+ MapPairDriverIdToDriver_t pr(vrDriverID, pDriver);
+ m_mapDriverIdToDriver.insert(pr);
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Query the Driver Manager to see if *this manager has the driver
+// already
// registered.
// Type: Method.
// Args: vrDriver - (R) The driver to query.
@@ -193,26 +194,26 @@ CMIDriverMgr::RegisterDriver(const IDriv
// False - not registered.
// Throws: None.
//--
-bool
-CMIDriverMgr::HaveDriverAlready(const IDriver &vrDriver) const
-{
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
- while (it != m_mapDriverIdToDriver.end())
- {
- const IDriver *pDrvr = (*it).second;
- if (pDrvr == &vrDriver)
- return true;
-
- // Next
- ++it;
- }
-
- return false;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Unregister a driver from the Driver Manager. Call the SetUseThisDriverToDoWork()
-// function to define another driver to do work if the one being unregistered did
+bool CMIDriverMgr::HaveDriverAlready(const IDriver &vrDriver) const {
+ MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
+ while (it != m_mapDriverIdToDriver.end()) {
+ const IDriver *pDrvr = (*it).second;
+ if (pDrvr == &vrDriver)
+ return true;
+
+ // Next
+ ++it;
+ }
+
+ return false;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Unregister a driver from the Driver Manager. Call the
+// SetUseThisDriverToDoWork()
+// function to define another driver to do work if the one being
+// unregistered did
// the work previously.
// Type: Method.
// Args: vrDriver - (R) The driver to unregister.
@@ -220,31 +221,31 @@ CMIDriverMgr::HaveDriverAlready(const ID
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::UnregisterDriver(const IDriver &vrDriver)
-{
- const IDriver *pDrvr = nullptr;
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
- while (it != m_mapDriverIdToDriver.end())
- {
- pDrvr = (*it).second;
- if (pDrvr == &vrDriver)
- break;
-
- // Next
- ++it;
- }
- m_mapDriverIdToDriver.erase(it);
-
- if (m_pDriverCurrent == pDrvr)
- m_pDriverCurrent = nullptr;
-
- return MIstatus::success;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Specify the driver to do work. The Driver Manager drives this driver. Any
-// previous driver doing work is not called anymore (so be sure the previous
+bool CMIDriverMgr::UnregisterDriver(const IDriver &vrDriver) {
+ const IDriver *pDrvr = nullptr;
+ MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
+ while (it != m_mapDriverIdToDriver.end()) {
+ pDrvr = (*it).second;
+ if (pDrvr == &vrDriver)
+ break;
+
+ // Next
+ ++it;
+ }
+ m_mapDriverIdToDriver.erase(it);
+
+ if (m_pDriverCurrent == pDrvr)
+ m_pDriverCurrent = nullptr;
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Specify the driver to do work. The Driver Manager drives this
+// driver. Any
+// previous driver doing work is not called anymore (so be sure the
+// previous
// driver is in a tidy state before stopping it working).
// Type: Method.
// Args: vrADriver - (R) A lldb::SBBroadcaster/IDriver derived object.
@@ -252,33 +253,34 @@ CMIDriverMgr::UnregisterDriver(const IDr
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::SetUseThisDriverToDoWork(const IDriver &vrADriver)
-{
- m_pDriverCurrent = const_cast<IDriver *>(&vrADriver);
+bool CMIDriverMgr::SetUseThisDriverToDoWork(const IDriver &vrADriver) {
+ m_pDriverCurrent = const_cast<IDriver *>(&vrADriver);
- const CMIUtilString msg(CMIUtilString::Format(MIRSRC(IDS_DRIVER_SAY_DRIVER_USING), m_pDriverCurrent->GetName().c_str()));
- m_pLog->Write(msg, CMICmnLog::eLogVerbosity_Log);
+ const CMIUtilString msg(
+ CMIUtilString::Format(MIRSRC(IDS_DRIVER_SAY_DRIVER_USING),
+ m_pDriverCurrent->GetName().c_str()));
+ m_pLog->Write(msg, CMICmnLog::eLogVerbosity_Log);
- m_bInMi2Mode = m_pDriverCurrent->GetDriverIsGDBMICompatibleDriver();
+ m_bInMi2Mode = m_pDriverCurrent->GetDriverIsGDBMICompatibleDriver();
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Ask *this manager which driver is currently doing the work.
// Type: Method.
// Args: None.
-// Return: IDriver * - Pointer to a driver, NULL if there is no current working driver.
+// Return: IDriver * - Pointer to a driver, NULL if there is no current working
+// driver.
// Throws: None.
//--
-CMIDriverMgr::IDriver *
-CMIDriverMgr::GetUseThisDriverToDoWork() const
-{
- return m_pDriverCurrent;
+CMIDriverMgr::IDriver *CMIDriverMgr::GetUseThisDriverToDoWork() const {
+ return m_pDriverCurrent;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Call this function puts *this driver to work.
// Type: Method.
// Args: None.
@@ -286,91 +288,95 @@ CMIDriverMgr::GetUseThisDriverToDoWork()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::DriverMainLoop()
-{
- if (m_pDriverCurrent != nullptr)
- {
- if (!m_pDriverCurrent->DoMainLoop())
- {
- const CMIUtilString errMsg(CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_MAINLOOP), m_pDriverCurrent->GetError().c_str()));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- return MIstatus::failure;
- }
- }
- else
- {
- const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- return MIstatus::failure;
- }
-
- return MIstatus::success;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Get the current driver to validate executable command line arguments.
-// Type: Method.
-// Args: argc - (R) An integer that contains the count of arguments that follow in
-// argv. The argc parameter is always greater than or equal to 1.
-// argv - (R) An array of null-terminated strings representing command-line
-// arguments entered by the user of the program. By convention,
-// argv[0] is the command with which the program is invoked.
+bool CMIDriverMgr::DriverMainLoop() {
+ if (m_pDriverCurrent != nullptr) {
+ if (!m_pDriverCurrent->DoMainLoop()) {
+ const CMIUtilString errMsg(
+ CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_MAINLOOP),
+ m_pDriverCurrent->GetError().c_str()));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ return MIstatus::failure;
+ }
+ } else {
+ const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ return MIstatus::failure;
+ }
+
+ return MIstatus::success;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Get the current driver to validate executable command line
+// arguments.
+// Type: Method.
+// Args: argc - (R) An integer that contains the count of arguments
+// that follow in
+// argv. The argc parameter is always greater than
+// or equal to 1.
+// argv - (R) An array of null-terminated strings representing
+// command-line
+// arguments entered by the user of the program. By
+// convention,
+// argv[0] is the command with which the program is
+// invoked.
// vpStdOut - (R) Point to a standard output stream.
-// vwbExiting - (W) True = *this want to exit, false = continue to work.
+// vwbExiting - (W) True = *this want to exit, false = continue to
+// work.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIDriverMgr::DriverParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting)
-{
- if (m_pDriverCurrent == nullptr)
- {
- const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- return MIstatus::failure;
- }
+bool CMIDriverMgr::DriverParseArgs(const int argc, const char *argv[],
+ FILE *vpStdOut, bool &vwbExiting) {
+ if (m_pDriverCurrent == nullptr) {
+ const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ return MIstatus::failure;
+ }
+
+ const lldb::SBError error(
+ m_pDriverCurrent->DoParseArgs(argc, argv, vpStdOut, vwbExiting));
+ bool bOk = !error.Fail();
+ if (!bOk) {
+ CMIUtilString errMsg;
+ const char *pErrorCstr = error.GetCString();
+ if (pErrorCstr != nullptr)
+ errMsg = CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_PARSE_ARGS),
+ m_pDriverCurrent->GetName().c_str(),
+ pErrorCstr);
+ else
+ errMsg = CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN),
+ m_pDriverCurrent->GetName().c_str());
- const lldb::SBError error(m_pDriverCurrent->DoParseArgs(argc, argv, vpStdOut, vwbExiting));
- bool bOk = !error.Fail();
- if (!bOk)
- {
- CMIUtilString errMsg;
- const char *pErrorCstr = error.GetCString();
- if (pErrorCstr != nullptr)
- errMsg = CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_PARSE_ARGS), m_pDriverCurrent->GetName().c_str(), pErrorCstr);
- else
- errMsg = CMIUtilString::Format(MIRSRC(IDS_DRIVER_ERR_PARSE_ARGS_UNKNOWN), m_pDriverCurrent->GetName().c_str());
+ bOk = CMICmnStreamStdout::Instance().Write(errMsg, true);
+ }
- bOk = CMICmnStreamStdout::Instance().Write(errMsg, true);
- }
-
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the current driver's last error condition.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description.
// Throws: None.
//--
-CMIUtilString
-CMIDriverMgr::DriverGetError() const
-{
- if (m_pDriverCurrent != nullptr)
- return m_pDriverCurrent->GetError();
- else
- {
- const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- }
+CMIUtilString CMIDriverMgr::DriverGetError() const {
+ if (m_pDriverCurrent != nullptr)
+ return m_pDriverCurrent->GetError();
+ else {
+ const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ }
- return CMIUtilString();
+ return CMIUtilString();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the current driver's name.
// Type: Method.
// Args: None.
@@ -378,21 +384,19 @@ CMIDriverMgr::DriverGetError() const
// Empty string = no current working driver specified.
// Throws: None.
//--
-CMIUtilString
-CMIDriverMgr::DriverGetName() const
-{
- if (m_pDriverCurrent != nullptr)
- return m_pDriverCurrent->GetName();
- else
- {
- const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- }
+CMIUtilString CMIDriverMgr::DriverGetName() const {
+ if (m_pDriverCurrent != nullptr)
+ return m_pDriverCurrent->GetName();
+ else {
+ const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ }
- return CMIUtilString();
+ return CMIUtilString();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the current driver's debugger object.
// Type: Method.
// Args: None.
@@ -400,26 +404,28 @@ CMIDriverMgr::DriverGetName() const
// - NULL = no current working driver specified.
// Throws: None.
//--
-lldb::SBDebugger *
-CMIDriverMgr::DriverGetTheDebugger()
-{
- lldb::SBDebugger *pDebugger = nullptr;
- if (m_pDriverCurrent != nullptr)
- pDebugger = &m_pDriverCurrent->GetTheDebugger();
- else
- {
- const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
- CMICmnStreamStdout::Instance().Write(errMsg, true);
- }
-
- return pDebugger;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Check the arguments given on the command line. The main purpose of this
-// function is to check for the presence of the --interpreter option. Having
-// this option present tells *this manager to set the CMIDriver to do work. If
-// not use the LLDB driver. The following are options that are only handled by
+lldb::SBDebugger *CMIDriverMgr::DriverGetTheDebugger() {
+ lldb::SBDebugger *pDebugger = nullptr;
+ if (m_pDriverCurrent != nullptr)
+ pDebugger = &m_pDriverCurrent->GetTheDebugger();
+ else {
+ const CMIUtilString errMsg(MIRSRC(IDS_DRIVER_ERR_CURRENT_NOT_SET));
+ CMICmnStreamStdout::Instance().Write(errMsg, true);
+ }
+
+ return pDebugger;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Check the arguments given on the command line. The main purpose of
+// this
+// function is to check for the presence of the --interpreter option.
+// Having
+// this option present tells *this manager to set the CMIDriver to do
+// work. If
+// not use the LLDB driver. The following are options that are only
+// handled by
// the CMIDriverMgr are:
// --help or -h
// --interpreter
@@ -428,315 +434,317 @@ CMIDriverMgr::DriverGetTheDebugger()
// --log
// --executable
// --log-dir
-// The above arguments are not handled by any driver object except for --executable.
-// The options --interpreter and --executable in code act very similar. The
-// --executable is necessary to differentiate whither the MI Driver is being using
-// by a client i.e. Eclipse or from the command line. Eclipse issues the option
-// --interpreter and also passes additional arguments which can be interpreted as an
-// executable if called from the command line. Using --executable tells the MI
-// Driver is being called the command line and that the executable argument is indeed
-// a specified executable an so actions commands to set up the executable for a
-// debug session. Using --interpreter on the command line does not action additional
-// commands to initialise a debug session and so be able to launch the process. The directory
+// The above arguments are not handled by any driver object except for
+// --executable.
+// The options --interpreter and --executable in code act very similar.
+// The
+// --executable is necessary to differentiate whither the MI Driver is
+// being using
+// by a client i.e. Eclipse or from the command line. Eclipse issues
+// the option
+// --interpreter and also passes additional arguments which can be
+// interpreted as an
+// executable if called from the command line. Using --executable tells
+// the MI
+// Driver is being called the command line and that the executable
+// argument is indeed
+// a specified executable an so actions commands to set up the
+// executable for a
+// debug session. Using --interpreter on the command line does not
+// action additional
+// commands to initialise a debug session and so be able to launch the
+// process. The directory
// where the log file is created is specified using --log-dir.
// Type: Method.
-// Args: argc - (R) An integer that contains the count of arguments that follow in
-// argv. The argc parameter is always greater than or equal to 1.
-// argv - (R) An array of null-terminated strings representing command-line
-// arguments entered by the user of the program. By convention,
-// argv[0] is the command with which the program is invoked.
-// vwbExiting - (W) True = *this want to exit, Reasons: help, invalid arg(s),
+// Args: argc - (R) An integer that contains the count of arguments
+// that follow in
+// argv. The argc parameter is always greater than
+// or equal to 1.
+// argv - (R) An array of null-terminated strings representing
+// command-line
+// arguments entered by the user of the program. By
+// convention,
+// argv[0] is the command with which the program is
+// invoked.
+// vwbExiting - (W) True = *this want to exit, Reasons: help,
+// invalid arg(s),
// version information only.
-// False = Continue to work, start debugger i.e. Command
+// False = Continue to work, start debugger i.e.
+// Command
// interpreter.
// Return: lldb::SBError - LLDB current error status.
// Throws: None.
//--
-bool
-CMIDriverMgr::ParseArgs(const int argc, const char *argv[], bool &vwbExiting)
-{
- bool bOk = MIstatus::success;
-
- vwbExiting = false;
-
- // Print MI application path to the Log file
- const CMIUtilString appPath(CMIUtilString::Format(MIRSRC(IDS_MI_APP_FILEPATHNAME), argv[0]));
- bOk = m_pLog->Write(appPath, CMICmnLog::eLogVerbosity_Log);
-
- // Print application arguments to the Log file
- const bool bHaveArgs(argc >= 2);
- CMIUtilString strArgs(MIRSRC(IDS_MI_APP_ARGS));
- if (!bHaveArgs)
- {
- strArgs += MIRSRC(IDS_WORD_NONE);
- bOk = bOk && m_pLog->Write(strArgs, CMICmnLog::eLogVerbosity_Log);
- }
- else
- {
- for (MIint i = 1; i < argc; i++)
- {
- strArgs += CMIUtilString::Format("%d:'%s' ", i, argv[i]);
- }
- bOk = bOk && m_pLog->Write(strArgs, CMICmnLog::eLogVerbosity_Log);
- }
-
- // Look for the command line options
- bool bHaveArgInterpret = false;
- bool bHaveArgVersion = false;
- bool bHaveArgVersionLong = false;
- bool bHaveArgLog = false;
- bool bHaveArgLogDir = false;
- bool bHaveArgHelp = false;
- CMIUtilString strLogDir;
-
- bHaveArgInterpret = true;
- if (bHaveArgs)
- {
- // CODETAG_MIDRIVE_CMD_LINE_ARG_HANDLING
- for (MIint i = 1; i < argc; i++)
- {
- // *** Add args to help in GetHelpOnCmdLineArgOptions() ***
- const CMIUtilString strArg(argv[i]);
-
- // Argument "--executable" is also check for in CMIDriver::ParseArgs()
- if ((0 == strArg.compare("--interpreter")) || // Given by the client such as Eclipse
- (0 == strArg.compare("--executable"))) // Used to specify that there is executable argument also on the command line
- { // See fn description.
- bHaveArgInterpret = true;
- }
- if (0 == strArg.compare("--version"))
- {
- bHaveArgVersion = true;
- }
- if (0 == strArg.compare("--versionLong"))
- {
- bHaveArgVersionLong = true;
- }
- if (0 == strArg.compare("--log"))
- {
- bHaveArgLog = true;
- }
- if (0 == strArg.compare(0,10,"--log-dir="))
- {
- strLogDir = strArg.substr(10, CMIUtilString::npos);
- bHaveArgLogDir = true;
- }
- if ((0 == strArg.compare("--help")) || (0 == strArg.compare("-h")))
- {
- bHaveArgHelp = true;
- }
- }
- }
-
- if (bHaveArgLog)
- {
- CMICmnLog::Instance().SetEnabled(true);
- }
-
- if (bHaveArgLogDir)
- {
- bOk = bOk && CMICmnLogMediumFile::Instance().SetDirectory(strLogDir);
- }
-
- // Todo: Remove this output when MI is finished. It is temporary to persuade Eclipse plugin to work.
- // Eclipse reads this literally and will not work unless it gets this exact version text.
- // Handle --version option (ignore the --interpreter option if present)
- if (bHaveArgVersion)
- {
- vwbExiting = true;
- bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse(MIRSRC(IDE_MI_VERSION_GDB));
- return bOk;
- }
+bool CMIDriverMgr::ParseArgs(const int argc, const char *argv[],
+ bool &vwbExiting) {
+ bool bOk = MIstatus::success;
+
+ vwbExiting = false;
+
+ // Print MI application path to the Log file
+ const CMIUtilString appPath(
+ CMIUtilString::Format(MIRSRC(IDS_MI_APP_FILEPATHNAME), argv[0]));
+ bOk = m_pLog->Write(appPath, CMICmnLog::eLogVerbosity_Log);
+
+ // Print application arguments to the Log file
+ const bool bHaveArgs(argc >= 2);
+ CMIUtilString strArgs(MIRSRC(IDS_MI_APP_ARGS));
+ if (!bHaveArgs) {
+ strArgs += MIRSRC(IDS_WORD_NONE);
+ bOk = bOk && m_pLog->Write(strArgs, CMICmnLog::eLogVerbosity_Log);
+ } else {
+ for (MIint i = 1; i < argc; i++) {
+ strArgs += CMIUtilString::Format("%d:'%s' ", i, argv[i]);
+ }
+ bOk = bOk && m_pLog->Write(strArgs, CMICmnLog::eLogVerbosity_Log);
+ }
+
+ // Look for the command line options
+ bool bHaveArgInterpret = false;
+ bool bHaveArgVersion = false;
+ bool bHaveArgVersionLong = false;
+ bool bHaveArgLog = false;
+ bool bHaveArgLogDir = false;
+ bool bHaveArgHelp = false;
+ CMIUtilString strLogDir;
+
+ bHaveArgInterpret = true;
+ if (bHaveArgs) {
+ // CODETAG_MIDRIVE_CMD_LINE_ARG_HANDLING
+ for (MIint i = 1; i < argc; i++) {
+ // *** Add args to help in GetHelpOnCmdLineArgOptions() ***
+ const CMIUtilString strArg(argv[i]);
+
+ // Argument "--executable" is also check for in CMIDriver::ParseArgs()
+ if ((0 ==
+ strArg.compare(
+ "--interpreter")) || // Given by the client such as Eclipse
+ (0 == strArg.compare("--executable"))) // Used to specify that there
+ // is executable argument also
+ // on the command line
+ { // See fn description.
+ bHaveArgInterpret = true;
+ }
+ if (0 == strArg.compare("--version")) {
+ bHaveArgVersion = true;
+ }
+ if (0 == strArg.compare("--versionLong")) {
+ bHaveArgVersionLong = true;
+ }
+ if (0 == strArg.compare("--log")) {
+ bHaveArgLog = true;
+ }
+ if (0 == strArg.compare(0, 10, "--log-dir=")) {
+ strLogDir = strArg.substr(10, CMIUtilString::npos);
+ bHaveArgLogDir = true;
+ }
+ if ((0 == strArg.compare("--help")) || (0 == strArg.compare("-h"))) {
+ bHaveArgHelp = true;
+ }
+ }
+ }
+
+ if (bHaveArgLog) {
+ CMICmnLog::Instance().SetEnabled(true);
+ }
+
+ if (bHaveArgLogDir) {
+ bOk = bOk && CMICmnLogMediumFile::Instance().SetDirectory(strLogDir);
+ }
+
+ // Todo: Remove this output when MI is finished. It is temporary to persuade
+ // Eclipse plugin to work.
+ // Eclipse reads this literally and will not work unless it gets this
+ // exact version text.
+ // Handle --version option (ignore the --interpreter option if present)
+ if (bHaveArgVersion) {
+ vwbExiting = true;
+ bOk = bOk &&
+ CMICmnStreamStdout::Instance().WriteMIResponse(
+ MIRSRC(IDE_MI_VERSION_GDB));
+ return bOk;
+ }
- // Todo: Make this the --version when the above --version version is removed
- // Handle --versionlong option (ignore the --interpreter option if present)
- if (bHaveArgVersionLong)
- {
- vwbExiting = true;
- bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse(GetAppVersion());
- return bOk;
- }
+ // Todo: Make this the --version when the above --version version is removed
+ // Handle --versionlong option (ignore the --interpreter option if present)
+ if (bHaveArgVersionLong) {
+ vwbExiting = true;
+ bOk =
+ bOk && CMICmnStreamStdout::Instance().WriteMIResponse(GetAppVersion());
+ return bOk;
+ }
- // Both '--help' and '--interpreter' means give help for MI only. Without
- // '--interpreter' help the LLDB driver is working and so help is for that.
- if (bHaveArgHelp && bHaveArgInterpret)
- {
- vwbExiting = true;
- bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse(GetHelpOnCmdLineArgOptions());
- return bOk;
- }
+ // Both '--help' and '--interpreter' means give help for MI only. Without
+ // '--interpreter' help the LLDB driver is working and so help is for that.
+ if (bHaveArgHelp && bHaveArgInterpret) {
+ vwbExiting = true;
+ bOk = bOk &&
+ CMICmnStreamStdout::Instance().WriteMIResponse(
+ GetHelpOnCmdLineArgOptions());
+ return bOk;
+ }
- // This makes the assumption that there is at least one MI compatible
- // driver registered and one LLDB driver registered and the CMIDriver
- // is the first one found.
- // ToDo: Implement a better solution that handle any order, any number
- // of drivers. Or this 'feature' may be removed if deemed not required.
- IDriver *pLldbDriver = GetFirstNonMIDriver();
- IDriver *pMi2Driver = GetFirstMIDriver();
- if (bHaveArgInterpret && (pMi2Driver != nullptr))
- bOk = bOk && SetUseThisDriverToDoWork(*pMi2Driver);
- else if (pLldbDriver != nullptr)
- bOk = bOk && SetUseThisDriverToDoWork(*pLldbDriver);
- else
- {
- if (bOk)
- {
- vwbExiting = true;
- const CMIUtilString msg(MIRSRC(IDS_DRIVER_ERR_NON_REGISTERED));
- bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse(msg);
- }
+ // This makes the assumption that there is at least one MI compatible
+ // driver registered and one LLDB driver registered and the CMIDriver
+ // is the first one found.
+ // ToDo: Implement a better solution that handle any order, any number
+ // of drivers. Or this 'feature' may be removed if deemed not required.
+ IDriver *pLldbDriver = GetFirstNonMIDriver();
+ IDriver *pMi2Driver = GetFirstMIDriver();
+ if (bHaveArgInterpret && (pMi2Driver != nullptr))
+ bOk = bOk && SetUseThisDriverToDoWork(*pMi2Driver);
+ else if (pLldbDriver != nullptr)
+ bOk = bOk && SetUseThisDriverToDoWork(*pLldbDriver);
+ else {
+ if (bOk) {
+ vwbExiting = true;
+ const CMIUtilString msg(MIRSRC(IDS_DRIVER_ERR_NON_REGISTERED));
+ bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse(msg);
}
+ }
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Return formatted application version and name information.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text data.
// Throws: None.
//--
-CMIUtilString
-CMIDriverMgr::GetAppVersion() const
-{
- const CMIUtilString strProj(MIRSRC(IDS_PROJNAME));
- const CMIUtilString strVsn(CMIDriver::Instance().GetVersionDescription());
- const CMIUtilString strGdb(MIRSRC(IDE_MI_VERSION_GDB));
- const CMIUtilString strVrsnInfo(CMIUtilString::Format("%s\n%s\n%s", strProj.c_str(), strVsn.c_str(), strGdb.c_str()));
-
- return strVrsnInfo;
+CMIUtilString CMIDriverMgr::GetAppVersion() const {
+ const CMIUtilString strProj(MIRSRC(IDS_PROJNAME));
+ const CMIUtilString strVsn(CMIDriver::Instance().GetVersionDescription());
+ const CMIUtilString strGdb(MIRSRC(IDE_MI_VERSION_GDB));
+ const CMIUtilString strVrsnInfo(CMIUtilString::Format(
+ "%s\n%s\n%s", strProj.c_str(), strVsn.c_str(), strGdb.c_str()));
+
+ return strVrsnInfo;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Return formatted help information on all the MI command line options.
+//++
+//------------------------------------------------------------------------------------
+// Details: Return formatted help information on all the MI command line
+// options.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text data.
// Throws: None.
//--
-CMIUtilString
-CMIDriverMgr::GetHelpOnCmdLineArgOptions() const
-{
- const CMIUtilString pHelp[] = {
- MIRSRC(IDE_MI_APP_DESCRIPTION),
- MIRSRC(IDE_MI_APP_INFORMATION),
- MIRSRC(IDE_MI_APP_ARG_USAGE),
- MIRSRC(IDE_MI_APP_ARG_HELP),
- MIRSRC(IDE_MI_APP_ARG_VERSION),
- MIRSRC(IDE_MI_APP_ARG_VERSION_LONG),
- MIRSRC(IDE_MI_APP_ARG_INTERPRETER),
- MIRSRC(IDE_MI_APP_ARG_SOURCE),
- MIRSRC(IDE_MI_APP_ARG_EXECUTEABLE),
- CMIUtilString::Format(MIRSRC(IDE_MI_APP_ARG_APP_LOG), CMICmnLogMediumFile::Instance().GetFileName().c_str()),
- MIRSRC(IDE_MI_APP_ARG_APP_LOG_DIR),
- MIRSRC(IDE_MI_APP_ARG_EXECUTABLE),
- MIRSRC(IDS_CMD_QUIT_HELP),
- MIRSRC(IDE_MI_APP_ARG_EXAMPLE)};
- const MIuint nHelpItems = sizeof pHelp / sizeof pHelp[0];
- CMIUtilString strHelp;
- for (MIuint i = 0; i < nHelpItems; i++)
- {
- strHelp += pHelp[i];
- strHelp += "\n\n";
- }
-
- return strHelp;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Search the registered drivers and return the first driver which says it is
+CMIUtilString CMIDriverMgr::GetHelpOnCmdLineArgOptions() const {
+ const CMIUtilString pHelp[] = {
+ MIRSRC(IDE_MI_APP_DESCRIPTION), MIRSRC(IDE_MI_APP_INFORMATION),
+ MIRSRC(IDE_MI_APP_ARG_USAGE), MIRSRC(IDE_MI_APP_ARG_HELP),
+ MIRSRC(IDE_MI_APP_ARG_VERSION), MIRSRC(IDE_MI_APP_ARG_VERSION_LONG),
+ MIRSRC(IDE_MI_APP_ARG_INTERPRETER), MIRSRC(IDE_MI_APP_ARG_SOURCE),
+ MIRSRC(IDE_MI_APP_ARG_EXECUTEABLE),
+ CMIUtilString::Format(
+ MIRSRC(IDE_MI_APP_ARG_APP_LOG),
+ CMICmnLogMediumFile::Instance().GetFileName().c_str()),
+ MIRSRC(IDE_MI_APP_ARG_APP_LOG_DIR), MIRSRC(IDE_MI_APP_ARG_EXECUTABLE),
+ MIRSRC(IDS_CMD_QUIT_HELP), MIRSRC(IDE_MI_APP_ARG_EXAMPLE)};
+ const MIuint nHelpItems = sizeof pHelp / sizeof pHelp[0];
+ CMIUtilString strHelp;
+ for (MIuint i = 0; i < nHelpItems; i++) {
+ strHelp += pHelp[i];
+ strHelp += "\n\n";
+ }
+
+ return strHelp;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Search the registered drivers and return the first driver which says
+// it is
// GDB/MI compatible i.e. the CMIDriver class.
// Type: Method.
// Args: None.
// Return: IDriver * - Ptr to driver, NULL = no driver found.
// Throws: None.
//--
-CMIDriverMgr::IDriver *
-CMIDriverMgr::GetFirstMIDriver() const
-{
- IDriver *pDriver = nullptr;
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
- while (it != m_mapDriverIdToDriver.end())
- {
- const CMIUtilString &rDrvId = (*it).first;
- MIunused(rDrvId);
- IDriver *pDvr = (*it).second;
- if (pDvr->GetDriverIsGDBMICompatibleDriver())
- {
- pDriver = pDvr;
- break;
- }
-
- // Next
- ++it;
- }
-
- return pDriver;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Search the registered drivers and return the first driver which says it is
+CMIDriverMgr::IDriver *CMIDriverMgr::GetFirstMIDriver() const {
+ IDriver *pDriver = nullptr;
+ MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
+ while (it != m_mapDriverIdToDriver.end()) {
+ const CMIUtilString &rDrvId = (*it).first;
+ MIunused(rDrvId);
+ IDriver *pDvr = (*it).second;
+ if (pDvr->GetDriverIsGDBMICompatibleDriver()) {
+ pDriver = pDvr;
+ break;
+ }
+
+ // Next
+ ++it;
+ }
+
+ return pDriver;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Search the registered drivers and return the first driver which says
+// it is
// not GDB/MI compatible i.e. the LLDB Driver class.
// Type: Method.
// Args: None.
// Return: IDriver * - Ptr to driver, NULL = no driver found.
// Throws: None.
//--
-CMIDriverMgr::IDriver *
-CMIDriverMgr::GetFirstNonMIDriver() const
-{
- IDriver *pDriver = nullptr;
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
- while (it != m_mapDriverIdToDriver.end())
- {
- const CMIUtilString &rDrvId = (*it).first;
- MIunused(rDrvId);
- IDriver *pDvr = (*it).second;
- if (!pDvr->GetDriverIsGDBMICompatibleDriver())
- {
- pDriver = pDvr;
- break;
- }
-
- // Next
- ++it;
- }
-
- return pDriver;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Search the registered drivers and return driver with the specified ID.
+CMIDriverMgr::IDriver *CMIDriverMgr::GetFirstNonMIDriver() const {
+ IDriver *pDriver = nullptr;
+ MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.begin();
+ while (it != m_mapDriverIdToDriver.end()) {
+ const CMIUtilString &rDrvId = (*it).first;
+ MIunused(rDrvId);
+ IDriver *pDvr = (*it).second;
+ if (!pDvr->GetDriverIsGDBMICompatibleDriver()) {
+ pDriver = pDvr;
+ break;
+ }
+
+ // Next
+ ++it;
+ }
+
+ return pDriver;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Search the registered drivers and return driver with the specified
+// ID.
// Type: Method.
// Args: vrDriverId - (R) ID of a driver.
// Return: IDriver * - Ptr to driver, NULL = no driver found.
// Throws: None.
//--
CMIDriverMgr::IDriver *
-CMIDriverMgr::GetDriver(const CMIUtilString &vrDriverId) const
-{
- MapDriverIdToDriver_t::const_iterator it = m_mapDriverIdToDriver.find(vrDriverId);
- if (it == m_mapDriverIdToDriver.end())
- return nullptr;
+CMIDriverMgr::GetDriver(const CMIUtilString &vrDriverId) const {
+ MapDriverIdToDriver_t::const_iterator it =
+ m_mapDriverIdToDriver.find(vrDriverId);
+ if (it == m_mapDriverIdToDriver.end())
+ return nullptr;
- IDriver *pDriver = (*it).second;
+ IDriver *pDriver = (*it).second;
- return pDriver;
+ return pDriver;
}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Gets called when lldb-mi gets a signal. Passed signal to current driver.
+//++
+//------------------------------------------------------------------------------------
+// Details: Gets called when lldb-mi gets a signal. Passed signal to current
+// driver.
//
// Type: Method.
// Args: signal that was delivered
// Return: None.
// Throws: None.
//--
-void
-CMIDriverMgr::DeliverSignal(int signal)
-{
- if (m_pDriverCurrent != nullptr)
- m_pDriverCurrent->DeliverSignal(signal);
+void CMIDriverMgr::DeliverSignal(int signal) {
+ if (m_pDriverCurrent != nullptr)
+ m_pDriverCurrent->DeliverSignal(signal);
}
Modified: lldb/trunk/tools/lldb-mi/MIDriverMgr.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIDriverMgr.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIDriverMgr.h (original)
+++ lldb/trunk/tools/lldb-mi/MIDriverMgr.h Tue Sep 6 15:57:50 2016
@@ -10,26 +10,30 @@
#pragma once
// Third party headers:
-#include <map>
#include "lldb/API/SBDebugger.h"
+#include <map>
// In-house headers:
#include "MICmnBase.h"
-#include "MIUtilString.h"
#include "MICmnLog.h"
#include "MIUtilSingletonBase.h"
+#include "MIUtilString.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI Driver Manager. Register lldb::SBBroadcaster derived Driver type
// objects with *this manager. The manager does not own driver objects
// registered with it and so will not delete when this manager is
-// shutdown. The Driver flagged as "use this one" will be set as current
+// shutdown. The Driver flagged as "use this one" will be set as
+// current
// driver and will be the one that is used. Other drivers are not
// operated. A Driver can call another Driver should it not handle a
// command.
// It also initializes other resources as part it's setup such as the
-// Logger and Resources objects (explicit indicate *this object requires
-// those objects (modules/components) to support it's own functionality).
+// Logger and Resources objects (explicit indicate *this object
+// requires
+// those objects (modules/components) to support it's own
+// functionality).
// The Driver manager is the first object instantiated as part of the
// MI code base. It is also the first thing to interpret the command
// line arguments passed to the executable. Bases on options it
@@ -40,83 +44,86 @@
// LLDB::SBDebugger.
// Singleton class.
//--
-class CMIDriverMgr : public CMICmnBase, public MI::ISingleton<CMIDriverMgr>
-{
- friend MI::ISingleton<CMIDriverMgr>;
-
- // Class:
- public:
- //++
- // Description: Driver deriver objects need this interface to work with
- // *this manager.
- //--
- class IDriver
- {
- public:
- virtual bool DoInitialize() = 0;
- virtual bool DoShutdown() = 0;
- virtual bool DoMainLoop() = 0;
- virtual lldb::SBError DoParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting) = 0;
- virtual CMIUtilString GetError() const = 0;
- virtual const CMIUtilString &GetName() const = 0;
- virtual lldb::SBDebugger &GetTheDebugger() = 0;
- virtual bool GetDriverIsGDBMICompatibleDriver() const = 0;
- virtual bool SetId(const CMIUtilString &vId) = 0;
- virtual const CMIUtilString &GetId() const = 0;
- virtual void DeliverSignal(int signal) = 0;
-
- // Not part of the interface, ignore
- /* dtor */ virtual ~IDriver() {}
- };
+class CMIDriverMgr : public CMICmnBase, public MI::ISingleton<CMIDriverMgr> {
+ friend MI::ISingleton<CMIDriverMgr>;
- // Methods:
+ // Class:
+public:
+ //++
+ // Description: Driver deriver objects need this interface to work with
+ // *this manager.
+ //--
+ class IDriver {
public:
- // MI system
- bool Initialize() override;
- bool Shutdown() override;
- //
- CMIUtilString GetAppVersion() const;
- bool RegisterDriver(const IDriver &vrADriver, const CMIUtilString &vrDriverID);
- bool UnregisterDriver(const IDriver &vrADriver);
- bool
- SetUseThisDriverToDoWork(const IDriver &vrADriver); // Specify working main driver
- IDriver *GetUseThisDriverToDoWork() const;
- bool ParseArgs(const int argc, const char *argv[], bool &vwbExiting);
- IDriver *GetDriver(const CMIUtilString &vrDriverId) const;
- //
- // MI Proxy fn to current specified working driver
- bool DriverMainLoop();
- bool DriverParseArgs(const int argc, const char *argv[], FILE *vpStdOut, bool &vwbExiting);
- CMIUtilString DriverGetError() const;
- CMIUtilString DriverGetName() const;
- lldb::SBDebugger *DriverGetTheDebugger();
- void DeliverSignal(int signal);
-
- // Typedef:
- private:
- typedef std::map<CMIUtilString, IDriver *> MapDriverIdToDriver_t;
- typedef std::pair<CMIUtilString, IDriver *> MapPairDriverIdToDriver_t;
-
- // Methods:
- private:
- /* ctor */ CMIDriverMgr();
- /* ctor */ CMIDriverMgr(const CMIDriverMgr &);
- void operator=(const CMIDriverMgr &);
- //
- bool HaveDriverAlready(const IDriver &vrMedium) const;
- bool UnregisterDriverAll();
- IDriver *GetFirstMIDriver() const;
- IDriver *GetFirstNonMIDriver() const;
- CMIUtilString GetHelpOnCmdLineArgOptions() const;
-
- // Overridden:
- private:
- // From CMICmnBase
- /* dtor */ ~CMIDriverMgr() override;
-
- // Attributes:
- private:
- MapDriverIdToDriver_t m_mapDriverIdToDriver;
- IDriver *m_pDriverCurrent; // This driver is used by this manager to do work. It is the main driver.
- bool m_bInMi2Mode; // True = --interpreter entered on the cmd line, false = operate LLDB driver (non GDB)
+ virtual bool DoInitialize() = 0;
+ virtual bool DoShutdown() = 0;
+ virtual bool DoMainLoop() = 0;
+ virtual lldb::SBError DoParseArgs(const int argc, const char *argv[],
+ FILE *vpStdOut, bool &vwbExiting) = 0;
+ virtual CMIUtilString GetError() const = 0;
+ virtual const CMIUtilString &GetName() const = 0;
+ virtual lldb::SBDebugger &GetTheDebugger() = 0;
+ virtual bool GetDriverIsGDBMICompatibleDriver() const = 0;
+ virtual bool SetId(const CMIUtilString &vId) = 0;
+ virtual const CMIUtilString &GetId() const = 0;
+ virtual void DeliverSignal(int signal) = 0;
+
+ // Not part of the interface, ignore
+ /* dtor */ virtual ~IDriver() {}
+ };
+
+ // Methods:
+public:
+ // MI system
+ bool Initialize() override;
+ bool Shutdown() override;
+ //
+ CMIUtilString GetAppVersion() const;
+ bool RegisterDriver(const IDriver &vrADriver,
+ const CMIUtilString &vrDriverID);
+ bool UnregisterDriver(const IDriver &vrADriver);
+ bool SetUseThisDriverToDoWork(
+ const IDriver &vrADriver); // Specify working main driver
+ IDriver *GetUseThisDriverToDoWork() const;
+ bool ParseArgs(const int argc, const char *argv[], bool &vwbExiting);
+ IDriver *GetDriver(const CMIUtilString &vrDriverId) const;
+ //
+ // MI Proxy fn to current specified working driver
+ bool DriverMainLoop();
+ bool DriverParseArgs(const int argc, const char *argv[], FILE *vpStdOut,
+ bool &vwbExiting);
+ CMIUtilString DriverGetError() const;
+ CMIUtilString DriverGetName() const;
+ lldb::SBDebugger *DriverGetTheDebugger();
+ void DeliverSignal(int signal);
+
+ // Typedef:
+private:
+ typedef std::map<CMIUtilString, IDriver *> MapDriverIdToDriver_t;
+ typedef std::pair<CMIUtilString, IDriver *> MapPairDriverIdToDriver_t;
+
+ // Methods:
+private:
+ /* ctor */ CMIDriverMgr();
+ /* ctor */ CMIDriverMgr(const CMIDriverMgr &);
+ void operator=(const CMIDriverMgr &);
+ //
+ bool HaveDriverAlready(const IDriver &vrMedium) const;
+ bool UnregisterDriverAll();
+ IDriver *GetFirstMIDriver() const;
+ IDriver *GetFirstNonMIDriver() const;
+ CMIUtilString GetHelpOnCmdLineArgOptions() const;
+
+ // Overridden:
+private:
+ // From CMICmnBase
+ /* dtor */ ~CMIDriverMgr() override;
+
+ // Attributes:
+private:
+ MapDriverIdToDriver_t m_mapDriverIdToDriver;
+ IDriver *m_pDriverCurrent; // This driver is used by this manager to do work.
+ // It is the main driver.
+ bool m_bInMi2Mode; // True = --interpreter entered on the cmd line, false =
+ // operate LLDB driver (non GDB)
};
Modified: lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.cpp Tue Sep 6 15:57:50 2016
@@ -11,81 +11,80 @@
#include "MIUtilDateTimeStd.h"
#include "MICmnResources.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDateTimeStd constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilDateTimeStd::CMIUtilDateTimeStd()
-{
-}
+CMIUtilDateTimeStd::CMIUtilDateTimeStd() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDateTimeStd destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilDateTimeStd::~CMIUtilDateTimeStd()
-{
-}
+CMIUtilDateTimeStd::~CMIUtilDateTimeStd() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve system local current date. Format is MM/DD/YYYY.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description.
// Throws: None.
//--
-CMIUtilString
-CMIUtilDateTimeStd::GetDate()
-{
- CMIUtilString strDate(MIRSRC(IDS_WORD_INVALIDBRKTS));
-
- std::time(&m_rawTime);
- const std::tm *pTi = std::localtime(&m_rawTime);
- if (std::strftime(&m_pScratch[0], sizeof(m_pScratch), "%d/%m/%y", pTi) > 0)
- strDate = m_pScratch;
+CMIUtilString CMIUtilDateTimeStd::GetDate() {
+ CMIUtilString strDate(MIRSRC(IDS_WORD_INVALIDBRKTS));
+
+ std::time(&m_rawTime);
+ const std::tm *pTi = std::localtime(&m_rawTime);
+ if (std::strftime(&m_pScratch[0], sizeof(m_pScratch), "%d/%m/%y", pTi) > 0)
+ strDate = m_pScratch;
- return strDate;
+ return strDate;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve system local current time. Format is HH:MM:SS 24 hour clock.
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve system local current time. Format is HH:MM:SS 24 hour
+// clock.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description.
// Throws: None.
//--
-CMIUtilString
-CMIUtilDateTimeStd::GetTime()
-{
- std::time(&m_rawTime);
- const std::tm *pTi = std::localtime(&m_rawTime);
- const CMIUtilString seconds(CMIUtilString::Format("%d", pTi->tm_sec));
- const CMIUtilString zero((seconds.length() == 1) ? "0" : "");
- const CMIUtilString strTime(CMIUtilString::Format("%d:%d:%s%s", pTi->tm_hour, pTi->tm_min, zero.c_str(), seconds.c_str()));
+CMIUtilString CMIUtilDateTimeStd::GetTime() {
+ std::time(&m_rawTime);
+ const std::tm *pTi = std::localtime(&m_rawTime);
+ const CMIUtilString seconds(CMIUtilString::Format("%d", pTi->tm_sec));
+ const CMIUtilString zero((seconds.length() == 1) ? "0" : "");
+ const CMIUtilString strTime(CMIUtilString::Format(
+ "%d:%d:%s%s", pTi->tm_hour, pTi->tm_min, zero.c_str(), seconds.c_str()));
- return strTime;
+ return strTime;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve system local current date and time in yyyy-MM-dd--HH-mm-ss format for log file names.
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve system local current date and time in yyyy-MM-dd--HH-mm-ss
+// format for log file names.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Text description.
// Throws: None.
//--
-CMIUtilString
-CMIUtilDateTimeStd::GetDateTimeLogFilename()
-{
- std::time(&m_rawTime);
- const std::tm *pTi = std::localtime(&m_rawTime);
- const CMIUtilString strTime(CMIUtilString::Format("%d%02d%02d%02d%02d%02d", pTi->tm_year + 1900, pTi->tm_mon,
- pTi->tm_mday, pTi->tm_hour, pTi->tm_min, pTi->tm_sec));
+CMIUtilString CMIUtilDateTimeStd::GetDateTimeLogFilename() {
+ std::time(&m_rawTime);
+ const std::tm *pTi = std::localtime(&m_rawTime);
+ const CMIUtilString strTime(CMIUtilString::Format(
+ "%d%02d%02d%02d%02d%02d", pTi->tm_year + 1900, pTi->tm_mon, pTi->tm_mday,
+ pTi->tm_hour, pTi->tm_min, pTi->tm_sec));
- return strTime;
+ return strTime;
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilDateTimeStd.h Tue Sep 6 15:57:50 2016
@@ -15,27 +15,27 @@
// In-house headers:
#include "MIUtilString.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Used to retrieve system local date
// time.
//--
-class CMIUtilDateTimeStd
-{
- // Methods:
- public:
- /* ctor */ CMIUtilDateTimeStd();
+class CMIUtilDateTimeStd {
+ // Methods:
+public:
+ /* ctor */ CMIUtilDateTimeStd();
- CMIUtilString GetDate();
- CMIUtilString GetTime();
- CMIUtilString GetDateTimeLogFilename();
+ CMIUtilString GetDate();
+ CMIUtilString GetTime();
+ CMIUtilString GetDateTimeLogFilename();
- // Overrideable:
- public:
- // From CMICmnBase
- /* dtor */ virtual ~CMIUtilDateTimeStd();
+ // Overrideable:
+public:
+ // From CMICmnBase
+ /* dtor */ virtual ~CMIUtilDateTimeStd();
- // Attributes:
- private:
- std::time_t m_rawTime;
- char m_pScratch[16];
+ // Attributes:
+private:
+ std::time_t m_rawTime;
+ char m_pScratch[16];
};
Modified: lldb/trunk/tools/lldb-mi/MIUtilDebug.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilDebug.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilDebug.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilDebug.cpp Tue Sep 6 15:57:50 2016
@@ -13,72 +13,72 @@
#endif
// In-house headers:
-#include "MIUtilDebug.h"
-#include "MIDriver.h"
#include "MICmnLog.h"
+#include "MIDriver.h"
+#include "MIUtilDebug.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDebug constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilDebug::CMIUtilDebug()
-{
-}
+CMIUtilDebug::CMIUtilDebug() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDebug destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilDebug::~CMIUtilDebug()
-{
-}
+CMIUtilDebug::~CMIUtilDebug() {}
-//++ ------------------------------------------------------------------------------------
-// Details: Show a dialog to the process/application halts. It gives the opportunity to
+//++
+//------------------------------------------------------------------------------------
+// Details: Show a dialog to the process/application halts. It gives the
+// opportunity to
// attach a debugger.
// Type: Static method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilDebug::ShowDlgWaitForDbgAttach()
-{
- const CMIUtilString strCaption(CMIDriver::Instance().GetAppNameShort());
+void CMIUtilDebug::ShowDlgWaitForDbgAttach() {
+ const CMIUtilString strCaption(CMIDriver::Instance().GetAppNameShort());
#ifdef _WIN32
- ::MessageBoxA(NULL, "Attach your debugger now", strCaption.c_str(), MB_OK);
+ ::MessageBoxA(NULL, "Attach your debugger now", strCaption.c_str(), MB_OK);
#else
// ToDo: Implement other platform version of an Ok to continue dialog box
#endif // _WIN32
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Temporarily stall the process/application to give the programmer the
-// opportunity to attach a debugger. How to use: Put a break in the programmer
-// where you want to visit, run the application then attach your debugger to the
-// application. Hit the debugger's pause button and the debugger should should
-// show this loop. Change the i variable value to break out of the loop and
+// opportunity to attach a debugger. How to use: Put a break in the
+// programmer
+// where you want to visit, run the application then attach your
+// debugger to the
+// application. Hit the debugger's pause button and the debugger should
+// should
+// show this loop. Change the i variable value to break out of the loop
+// and
// visit your break point.
// Type: Static method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilDebug::WaitForDbgAttachInfinteLoop()
-{
- MIuint i = 0;
- while (i == 0)
- {
- const std::chrono::milliseconds time(100);
- std::this_thread::sleep_for(time);
- }
+void CMIUtilDebug::WaitForDbgAttachInfinteLoop() {
+ MIuint i = 0;
+ while (i == 0) {
+ const std::chrono::milliseconds time(100);
+ std::this_thread::sleep_for(time);
+ }
}
//---------------------------------------------------------------------------------------
@@ -89,7 +89,8 @@ CMIUtilDebug::WaitForDbgAttachInfinteLoo
CMICmnLog &CMIUtilDebugFnTrace::ms_rLog = CMICmnLog::Instance();
MIuint CMIUtilDebugFnTrace::ms_fnDepthCnt = 0;
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDebugFnTrace constructor.
// Type: Method.
// Args: vFnName - (R) The text to insert into the log.
@@ -97,21 +98,22 @@ MIuint CMIUtilDebugFnTrace::ms_fnDepthCn
// Throws: None.
//--
CMIUtilDebugFnTrace::CMIUtilDebugFnTrace(const CMIUtilString &vFnName)
- : m_strFnName(vFnName)
-{
- const CMIUtilString txt(CMIUtilString::Format("%d>%s", ++ms_fnDepthCnt, m_strFnName.c_str()));
- ms_rLog.Write(txt, CMICmnLog::eLogVerbosity_FnTrace);
+ : m_strFnName(vFnName) {
+ const CMIUtilString txt(
+ CMIUtilString::Format("%d>%s", ++ms_fnDepthCnt, m_strFnName.c_str()));
+ ms_rLog.Write(txt, CMICmnLog::eLogVerbosity_FnTrace);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilDebugFnTrace destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilDebugFnTrace::~CMIUtilDebugFnTrace()
-{
- const CMIUtilString txt(CMIUtilString::Format("%d<%s", ms_fnDepthCnt--, m_strFnName.c_str()));
- ms_rLog.Write(txt, CMICmnLog::eLogVerbosity_FnTrace);
+CMIUtilDebugFnTrace::~CMIUtilDebugFnTrace() {
+ const CMIUtilString txt(
+ CMIUtilString::Format("%d<%s", ms_fnDepthCnt--, m_strFnName.c_str()));
+ ms_rLog.Write(txt, CMICmnLog::eLogVerbosity_FnTrace);
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilDebug.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilDebug.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilDebug.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilDebug.h Tue Sep 6 15:57:50 2016
@@ -17,27 +17,28 @@
// Declarations:
class CMICmnLog;
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI debugging aid utility class.
//--
-class CMIUtilDebug
-{
- // Statics:
- public:
- static void ShowDlgWaitForDbgAttach();
- static void WaitForDbgAttachInfinteLoop();
-
- // Methods:
- public:
- /* ctor */ CMIUtilDebug();
-
- // Overrideable:
- public:
- // From CMICmnBase
- /* dtor */ virtual ~CMIUtilDebug();
+class CMIUtilDebug {
+ // Statics:
+public:
+ static void ShowDlgWaitForDbgAttach();
+ static void WaitForDbgAttachInfinteLoop();
+
+ // Methods:
+public:
+ /* ctor */ CMIUtilDebug();
+
+ // Overrideable:
+public:
+ // From CMICmnBase
+ /* dtor */ virtual ~CMIUtilDebug();
};
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI debug utility class. Used to indicate the current function
// depth in the call stack. It uses the CMIlCmnLog logger to output
// the current fn trace information.
@@ -46,27 +47,29 @@ class CMIUtilDebug
// Use preprocessor definition MI_USE_DEBUG_TRACE_FN to turn off or on
// tracing code.
//--
-class CMIUtilDebugFnTrace
-{
- // Methods:
- public:
- /* ctor */ CMIUtilDebugFnTrace(const CMIUtilString &vFnName);
-
- // Overrideable:
- public:
- // From CMICmnBase
- /* dtor */ virtual ~CMIUtilDebugFnTrace();
-
- // Attributes:
- private:
- const CMIUtilString m_strFnName;
-
- static CMICmnLog &ms_rLog;
- static MIuint ms_fnDepthCnt; // Increment count as fn depth increases, decrement count as fn stack pops off
+class CMIUtilDebugFnTrace {
+ // Methods:
+public:
+ /* ctor */ CMIUtilDebugFnTrace(const CMIUtilString &vFnName);
+
+ // Overrideable:
+public:
+ // From CMICmnBase
+ /* dtor */ virtual ~CMIUtilDebugFnTrace();
+
+ // Attributes:
+private:
+ const CMIUtilString m_strFnName;
+
+ static CMICmnLog &ms_rLog;
+ static MIuint ms_fnDepthCnt; // Increment count as fn depth increases,
+ // decrement count as fn stack pops off
};
-//++ ============================================================================
-// Details: Take the given text and send it to the server's Logger to output to the
+//++
+//============================================================================
+// Details: Take the given text and send it to the server's Logger to output to
+// the
// trace file.
// Type: Compile preprocess.
// Args: x - (R) Message (may be seen by user).
Modified: lldb/trunk/tools/lldb-mi/MIUtilFileStd.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilFileStd.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilFileStd.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilFileStd.cpp Tue Sep 6 15:57:50 2016
@@ -8,10 +8,10 @@
//===----------------------------------------------------------------------===//
// Third party headers
-#include <stdio.h>
#include <assert.h>
-#include <string.h> // For strerror()
#include <cerrno>
+#include <stdio.h>
+#include <string.h> // For strerror()
// In-house headers:
#include "MICmnResources.h"
@@ -20,7 +20,8 @@
#include "llvm/Support/ConvertUTF.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilFileStd constructor.
// Type: Method.
// Args: None.
@@ -28,87 +29,88 @@
// Throws: None.
//--
CMIUtilFileStd::CMIUtilFileStd()
- : m_fileNamePath(CMIUtilString())
- , m_pFileHandle(nullptr)
+ : m_fileNamePath(CMIUtilString()), m_pFileHandle(nullptr)
#if defined(_MSC_VER)
- , m_constCharNewLine("\r\n")
+ ,
+ m_constCharNewLine("\r\n")
#else
- , m_constCharNewLine("\n")
+ ,
+ m_constCharNewLine("\n")
#endif // #if defined( _MSC_VER )
- , m_bFileError(false)
-{
+ ,
+ m_bFileError(false) {
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilFileStd destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilFileStd::~CMIUtilFileStd()
-{
- Close();
-}
+CMIUtilFileStd::~CMIUtilFileStd() { Close(); }
-//++ ------------------------------------------------------------------------------------
-// Details: Open file for writing. On the first call to this function after *this object
-// is created the file is either created or replace, from then on open only opens
+//++
+//------------------------------------------------------------------------------------
+// Details: Open file for writing. On the first call to this function after
+// *this object
+// is created the file is either created or replace, from then on open
+// only opens
// an existing file.
// Type: Method.
// Args: vFileNamePath - (R) File name path.
-// vwrbNewCreated - (W) True - file recreated, false - file appended too.
+// vwrbNewCreated - (W) True - file recreated, false - file appended
+// too.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilFileStd::CreateWrite(const CMIUtilString &vFileNamePath, bool &vwrbNewCreated)
-{
- // Reset
- m_bFileError = false;
- vwrbNewCreated = false;
-
- if (vFileNamePath.empty())
- {
- m_bFileError = true;
- SetErrorDescription(MIRSRC(IDS_UTIL_FILE_ERR_INVALID_PATHNAME));
- return MIstatus::failure;
- }
-
- // File is already open so exit
- if (m_pFileHandle != nullptr)
- return MIstatus::success;
+bool CMIUtilFileStd::CreateWrite(const CMIUtilString &vFileNamePath,
+ bool &vwrbNewCreated) {
+ // Reset
+ m_bFileError = false;
+ vwrbNewCreated = false;
+
+ if (vFileNamePath.empty()) {
+ m_bFileError = true;
+ SetErrorDescription(MIRSRC(IDS_UTIL_FILE_ERR_INVALID_PATHNAME));
+ return MIstatus::failure;
+ }
+
+ // File is already open so exit
+ if (m_pFileHandle != nullptr)
+ return MIstatus::success;
#if !defined(_MSC_VER)
- // Open with 'write' and 'binary' mode
- m_pFileHandle = ::fopen(vFileNamePath.c_str(), "wb");
+ // Open with 'write' and 'binary' mode
+ m_pFileHandle = ::fopen(vFileNamePath.c_str(), "wb");
#else
- // Open a file with exclusive write and shared read permissions
- std::wstring path;
- if (llvm::ConvertUTF8toWide(vFileNamePath.c_str(), path))
- m_pFileHandle = ::_wfsopen(path.c_str(), L"wb", _SH_DENYWR);
- else
- {
- errno = EINVAL;
- m_pFileHandle = nullptr;
- }
+ // Open a file with exclusive write and shared read permissions
+ std::wstring path;
+ if (llvm::ConvertUTF8toWide(vFileNamePath.c_str(), path))
+ m_pFileHandle = ::_wfsopen(path.c_str(), L"wb", _SH_DENYWR);
+ else {
+ errno = EINVAL;
+ m_pFileHandle = nullptr;
+ }
#endif // !defined( _MSC_VER )
- if (m_pFileHandle == nullptr)
- {
- m_bFileError = true;
- SetErrorDescriptionn(MIRSRC(IDS_UTIL_FILE_ERR_OPENING_FILE), strerror(errno), vFileNamePath.c_str());
- return MIstatus::failure;
- }
+ if (m_pFileHandle == nullptr) {
+ m_bFileError = true;
+ SetErrorDescriptionn(MIRSRC(IDS_UTIL_FILE_ERR_OPENING_FILE),
+ strerror(errno), vFileNamePath.c_str());
+ return MIstatus::failure;
+ }
- vwrbNewCreated = true;
- m_fileNamePath = vFileNamePath;
+ vwrbNewCreated = true;
+ m_fileNamePath = vFileNamePath;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write data to existing opened file.
// Type: Method.
// Args: vData - (R) Text data.
@@ -116,38 +118,37 @@ CMIUtilFileStd::CreateWrite(const CMIUti
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilFileStd::Write(const CMIUtilString &vData)
-{
- if (vData.size() == 0)
- return MIstatus::success;
-
- if (m_bFileError)
- return MIstatus::failure;
-
- if (m_pFileHandle == nullptr)
- {
- m_bFileError = true;
- SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_NOTOPEN), m_fileNamePath.c_str());
- return MIstatus::failure;
- }
-
- // Get the string size
- MIuint size = vData.size();
- if (::fwrite(vData.c_str(), 1, size, m_pFileHandle) == size)
- {
- // Flush the data to the file
- ::fflush(m_pFileHandle);
- return MIstatus::success;
- }
+bool CMIUtilFileStd::Write(const CMIUtilString &vData) {
+ if (vData.size() == 0)
+ return MIstatus::success;
+
+ if (m_bFileError)
+ return MIstatus::failure;
- // Not all of the data has been transferred
+ if (m_pFileHandle == nullptr) {
m_bFileError = true;
- SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_FILE), m_fileNamePath.c_str());
+ SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_NOTOPEN),
+ m_fileNamePath.c_str());
return MIstatus::failure;
+ }
+
+ // Get the string size
+ MIuint size = vData.size();
+ if (::fwrite(vData.c_str(), 1, size, m_pFileHandle) == size) {
+ // Flush the data to the file
+ ::fflush(m_pFileHandle);
+ return MIstatus::success;
+ }
+
+ // Not all of the data has been transferred
+ m_bFileError = true;
+ SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_FILE),
+ m_fileNamePath.c_str());
+ return MIstatus::failure;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Write data to existing opened file.
// Type: Method.
// Args: vData - (R) Text data.
@@ -156,54 +157,53 @@ CMIUtilFileStd::Write(const CMIUtilStrin
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilFileStd::Write(const char *vpData, const MIuint vCharCnt)
-{
- if (vCharCnt == 0)
- return MIstatus::success;
-
- if (m_bFileError)
- return MIstatus::failure;
-
- if (m_pFileHandle == nullptr)
- {
- m_bFileError = true;
- SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_NOTOPEN), m_fileNamePath.c_str());
- return MIstatus::failure;
- }
-
- if (::fwrite(vpData, 1, vCharCnt, m_pFileHandle) == vCharCnt)
- {
- // Flush the data to the file
- ::fflush(m_pFileHandle);
- return MIstatus::success;
- }
+bool CMIUtilFileStd::Write(const char *vpData, const MIuint vCharCnt) {
+ if (vCharCnt == 0)
+ return MIstatus::success;
+
+ if (m_bFileError)
+ return MIstatus::failure;
- // Not all of the data has been transferred
+ if (m_pFileHandle == nullptr) {
m_bFileError = true;
- SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_FILE), m_fileNamePath.c_str());
+ SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_NOTOPEN),
+ m_fileNamePath.c_str());
return MIstatus::failure;
+ }
+
+ if (::fwrite(vpData, 1, vCharCnt, m_pFileHandle) == vCharCnt) {
+ // Flush the data to the file
+ ::fflush(m_pFileHandle);
+ return MIstatus::success;
+ }
+
+ // Not all of the data has been transferred
+ m_bFileError = true;
+ SetErrorDescriptionn(MIRSRC(IDE_UTIL_FILE_ERR_WRITING_FILE),
+ m_fileNamePath.c_str());
+ return MIstatus::failure;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Close existing opened file. Note Close() must must an open!
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilFileStd::Close()
-{
- if (m_pFileHandle == nullptr)
- return;
-
- ::fclose(m_pFileHandle);
- m_pFileHandle = nullptr;
- // m_bFileError = false; Do not reset as want to remain until next attempt at open or create
+void CMIUtilFileStd::Close() {
+ if (m_pFileHandle == nullptr)
+ return;
+
+ ::fclose(m_pFileHandle);
+ m_pFileHandle = nullptr;
+ // m_bFileError = false; Do not reset as want to remain until next attempt at
+ // open or create
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve state of whether the file is ok.
// Type: Method.
// Args: None.
@@ -211,13 +211,10 @@ CMIUtilFileStd::Close()
// False - file has a problem.
// Throws: None.
//--
-bool
-CMIUtilFileStd::IsOk() const
-{
- return !m_bFileError;
-}
+bool CMIUtilFileStd::IsOk() const { return !m_bFileError; }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Status on a file existing already.
// Type: Method.
// Args: vFileNamePath.
@@ -225,38 +222,36 @@ CMIUtilFileStd::IsOk() const
// False - Not found.
// Throws: None.
//--
-bool
-CMIUtilFileStd::IsFileExist(const CMIUtilString &vFileNamePath) const
-{
- if (vFileNamePath.empty())
- return false;
-
- FILE *pTmp = nullptr;
- pTmp = ::fopen(vFileNamePath.c_str(), "wb");
- if (pTmp != nullptr)
- {
- ::fclose(pTmp);
- return true;
- }
-
+bool CMIUtilFileStd::IsFileExist(const CMIUtilString &vFileNamePath) const {
+ if (vFileNamePath.empty())
return false;
+
+ FILE *pTmp = nullptr;
+ pTmp = ::fopen(vFileNamePath.c_str(), "wb");
+ if (pTmp != nullptr) {
+ ::fclose(pTmp);
+ return true;
+ }
+
+ return false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the file current carriage line return characters used.
// Type: Method.
// Args: None.
// Return: CMIUtilString & - Text.
// Throws: None.
//--
-const CMIUtilString &
-CMIUtilFileStd::GetLineReturn() const
-{
- return m_constCharNewLine;
+const CMIUtilString &CMIUtilFileStd::GetLineReturn() const {
+ return m_constCharNewLine;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Given a file name directory path, strip off the filename and return the path.
+//++
+//------------------------------------------------------------------------------------
+// Details: Given a file name directory path, strip off the filename and return
+// the path.
// It look for either backslash or forward slash.
// Type: Method.
// Args: vDirectoryPath - (R) Text directory path.
@@ -264,34 +259,33 @@ CMIUtilFileStd::GetLineReturn() const
// Throws: None.
//--
CMIUtilString
-CMIUtilFileStd::StripOffFileName(const CMIUtilString &vDirectoryPath)
-{
- const size_t nPos = vDirectoryPath.rfind('\\');
- size_t nPos2 = vDirectoryPath.rfind('/');
- if ((nPos == std::string::npos) && (nPos2 == std::string::npos))
- return vDirectoryPath;
-
- if (nPos > nPos2)
- nPos2 = nPos;
-
- const CMIUtilString strPath(vDirectoryPath.substr(0, nPos2).c_str());
- return strPath;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Return either backslash or forward slash appropriate to the OS this application
+CMIUtilFileStd::StripOffFileName(const CMIUtilString &vDirectoryPath) {
+ const size_t nPos = vDirectoryPath.rfind('\\');
+ size_t nPos2 = vDirectoryPath.rfind('/');
+ if ((nPos == std::string::npos) && (nPos2 == std::string::npos))
+ return vDirectoryPath;
+
+ if (nPos > nPos2)
+ nPos2 = nPos;
+
+ const CMIUtilString strPath(vDirectoryPath.substr(0, nPos2).c_str());
+ return strPath;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Return either backslash or forward slash appropriate to the OS this
+// application
// is running on.
// Type: Static method.
// Args: None.
// Return: char - '/' or '\' character.
// Throws: None.
//--
-char
-CMIUtilFileStd::GetSlash()
-{
+char CMIUtilFileStd::GetSlash() {
#if !defined(_MSC_VER)
- return '/';
+ return '/';
#else
- return '\\';
+ return '\\';
#endif // !defined( _MSC_VER )
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilFileStd.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilFileStd.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilFileStd.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilFileStd.h Tue Sep 6 15:57:50 2016
@@ -10,40 +10,40 @@
#pragma once
// In-house headers:
-#include "MIUtilString.h"
#include "MICmnBase.h"
+#include "MIUtilString.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. File handling.
//--
-class CMIUtilFileStd : public CMICmnBase
-{
- // Static:
- public:
- static char GetSlash();
+class CMIUtilFileStd : public CMICmnBase {
+ // Static:
+public:
+ static char GetSlash();
- // Methods:
- public:
- /* ctor */ CMIUtilFileStd();
- //
- bool CreateWrite(const CMIUtilString &vFileNamePath, bool &vwrbNewCreated);
- bool Write(const CMIUtilString &vData);
- bool Write(const char *vpData, const MIuint vCharCnt);
- void Close();
- bool IsOk() const;
- bool IsFileExist(const CMIUtilString &vFileNamePath) const;
- const CMIUtilString &GetLineReturn() const;
- static CMIUtilString StripOffFileName(const CMIUtilString &vDirectoryPath);
+ // Methods:
+public:
+ /* ctor */ CMIUtilFileStd();
+ //
+ bool CreateWrite(const CMIUtilString &vFileNamePath, bool &vwrbNewCreated);
+ bool Write(const CMIUtilString &vData);
+ bool Write(const char *vpData, const MIuint vCharCnt);
+ void Close();
+ bool IsOk() const;
+ bool IsFileExist(const CMIUtilString &vFileNamePath) const;
+ const CMIUtilString &GetLineReturn() const;
+ static CMIUtilString StripOffFileName(const CMIUtilString &vDirectoryPath);
- // Overridden:
- public:
- // From CMICmnBase
- /* dtor */ ~CMIUtilFileStd() override;
+ // Overridden:
+public:
+ // From CMICmnBase
+ /* dtor */ ~CMIUtilFileStd() override;
- // Attributes:
- private:
- CMIUtilString m_fileNamePath;
- FILE *m_pFileHandle;
- CMIUtilString m_constCharNewLine;
- bool m_bFileError; // True = have a file error ATM, false = all ok
+ // Attributes:
+private:
+ CMIUtilString m_fileNamePath;
+ FILE *m_pFileHandle;
+ CMIUtilString m_constCharNewLine;
+ bool m_bFileError; // True = have a file error ATM, false = all ok
};
Modified: lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.cpp Tue Sep 6 15:57:50 2016
@@ -10,42 +10,38 @@
// In-house headers:
#include "MIUtilMapIdToVariant.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilMapIdToVariant constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilMapIdToVariant::CMIUtilMapIdToVariant()
-{
-}
+CMIUtilMapIdToVariant::CMIUtilMapIdToVariant() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilMapIdToVariant destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilMapIdToVariant::~CMIUtilMapIdToVariant()
-{
-}
+CMIUtilMapIdToVariant::~CMIUtilMapIdToVariant() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Remove at the data from *this container.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilMapIdToVariant::Clear()
-{
- m_mapKeyToVariantValue.clear();
-}
+void CMIUtilMapIdToVariant::Clear() { m_mapKeyToVariantValue.clear(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check an ID is present already in *this container.
// Type: Method.
// Args: vId - (R) Unique ID i.e. GUID.
@@ -53,30 +49,29 @@ CMIUtilMapIdToVariant::Clear()
// False - not found.
// Throws: None.
//--
-bool
-CMIUtilMapIdToVariant::HaveAlready(const CMIUtilString &vId) const
-{
- const MapKeyToVariantValue_t::const_iterator it = m_mapKeyToVariantValue.find(vId);
- if (it != m_mapKeyToVariantValue.end())
- return true;
+bool CMIUtilMapIdToVariant::HaveAlready(const CMIUtilString &vId) const {
+ const MapKeyToVariantValue_t::const_iterator it =
+ m_mapKeyToVariantValue.find(vId);
+ if (it != m_mapKeyToVariantValue.end())
+ return true;
- return false;
+ return false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Determine if *this container is currently holding any data.
// Type: Method.
// Args: None.
// Return: bool - True - Yes empty, false - one or more data object present.
// Throws: None.
//--
-bool
-CMIUtilMapIdToVariant::IsEmpty() const
-{
- return m_mapKeyToVariantValue.empty();
+bool CMIUtilMapIdToVariant::IsEmpty() const {
+ return m_mapKeyToVariantValue.empty();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check the ID is valid to be registered.
// Type: Method.
// Args: vId - (R) Unique ID i.e. GUID.
@@ -84,19 +79,19 @@ CMIUtilMapIdToVariant::IsEmpty() const
// False - not valid.
// Throws: None.
//--
-bool
-CMIUtilMapIdToVariant::IsValid(const CMIUtilString &vId) const
-{
- bool bValid = true;
+bool CMIUtilMapIdToVariant::IsValid(const CMIUtilString &vId) const {
+ bool bValid = true;
- if (vId.empty())
- bValid = false;
+ if (vId.empty())
+ bValid = false;
- return bValid;
+ return bValid;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Remove from *this contain a data object specified by ID. The data object
+//++
+//------------------------------------------------------------------------------------
+// Details: Remove from *this contain a data object specified by ID. The data
+// object
// when removed also calls its destructor should it have one.
// Type: Method.
// Args: vId - (R) Unique ID i.e. GUID.
@@ -104,14 +99,12 @@ CMIUtilMapIdToVariant::IsValid(const CMI
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilMapIdToVariant::Remove(const CMIUtilString &vId)
-{
- const MapKeyToVariantValue_t::const_iterator it = m_mapKeyToVariantValue.find(vId);
- if (it != m_mapKeyToVariantValue.end())
- {
- m_mapKeyToVariantValue.erase(it);
- }
+bool CMIUtilMapIdToVariant::Remove(const CMIUtilString &vId) {
+ const MapKeyToVariantValue_t::const_iterator it =
+ m_mapKeyToVariantValue.find(vId);
+ if (it != m_mapKeyToVariantValue.end()) {
+ m_mapKeyToVariantValue.erase(it);
+ }
- return MIstatus::success;
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilMapIdToVariant.h Tue Sep 6 15:57:50 2016
@@ -18,45 +18,49 @@
#include "MIUtilString.h"
#include "MIUtilVariant.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Map type container that hold general
// object types (by being a variant wrapper)
// objects by ID.
//--
-class CMIUtilMapIdToVariant : public CMICmnBase
-{
- // Methods:
- public:
- /* ctor */ CMIUtilMapIdToVariant();
-
- template <typename T> bool Add(const CMIUtilString &vId, const T &vData);
- void Clear();
- template <typename T> bool Get(const CMIUtilString &vId, T &vrwData, bool &vrwbFound) const;
- bool HaveAlready(const CMIUtilString &vId) const;
- bool IsEmpty() const;
- bool Remove(const CMIUtilString &vId);
-
- // Overridden:
- public:
- // From CMICmnBase
- /* dtor */ ~CMIUtilMapIdToVariant() override;
-
- // Typedefs:
- private:
- typedef std::map<CMIUtilString, CMIUtilVariant> MapKeyToVariantValue_t;
- typedef std::pair<CMIUtilString, CMIUtilVariant> MapPairKeyToVariantValue_t;
-
- // Methods:
- private:
- bool IsValid(const CMIUtilString &vId) const;
+class CMIUtilMapIdToVariant : public CMICmnBase {
+ // Methods:
+public:
+ /* ctor */ CMIUtilMapIdToVariant();
+
+ template <typename T> bool Add(const CMIUtilString &vId, const T &vData);
+ void Clear();
+ template <typename T>
+ bool Get(const CMIUtilString &vId, T &vrwData, bool &vrwbFound) const;
+ bool HaveAlready(const CMIUtilString &vId) const;
+ bool IsEmpty() const;
+ bool Remove(const CMIUtilString &vId);
+
+ // Overridden:
+public:
+ // From CMICmnBase
+ /* dtor */ ~CMIUtilMapIdToVariant() override;
+
+ // Typedefs:
+private:
+ typedef std::map<CMIUtilString, CMIUtilVariant> MapKeyToVariantValue_t;
+ typedef std::pair<CMIUtilString, CMIUtilVariant> MapPairKeyToVariantValue_t;
+
+ // Methods:
+private:
+ bool IsValid(const CMIUtilString &vId) const;
- // Attributes:
- MapKeyToVariantValue_t m_mapKeyToVariantValue;
+ // Attributes:
+ MapKeyToVariantValue_t m_mapKeyToVariantValue;
};
-//++ ------------------------------------------------------------------------------------
-// Details: Add to *this container a data object of general type identified by an ID.
-// If the data with that ID already exists in the container it is replace with
+//++
+//------------------------------------------------------------------------------------
+// Details: Add to *this container a data object of general type identified by
+// an ID.
+// If the data with that ID already exists in the container it is
+// replace with
// the new data specified.
// Type: Method.
// Args: T - The data object's variable type.
@@ -67,29 +71,28 @@ class CMIUtilMapIdToVariant : public CMI
// Throws: None.
//--
template <typename T>
-bool
-CMIUtilMapIdToVariant::Add(const CMIUtilString &vId, const T &vData)
-{
- if (!IsValid(vId))
- {
- SetErrorDescription(CMIUtilString::Format(MIRSRC(IDS_VARIANT_ERR_MAP_KEY_INVALID), vId.c_str()));
- return MIstatus::failure;
- }
-
- const bool bOk = HaveAlready(vId) ? Remove(vId) : MIstatus::success;
- if (bOk)
- {
- CMIUtilVariant data;
- data.Set<T>(vData);
- MapPairKeyToVariantValue_t pr(vId, data);
- m_mapKeyToVariantValue.insert(pr);
- }
+bool CMIUtilMapIdToVariant::Add(const CMIUtilString &vId, const T &vData) {
+ if (!IsValid(vId)) {
+ SetErrorDescription(CMIUtilString::Format(
+ MIRSRC(IDS_VARIANT_ERR_MAP_KEY_INVALID), vId.c_str()));
+ return MIstatus::failure;
+ }
+
+ const bool bOk = HaveAlready(vId) ? Remove(vId) : MIstatus::success;
+ if (bOk) {
+ CMIUtilVariant data;
+ data.Set<T>(vData);
+ MapPairKeyToVariantValue_t pr(vId, data);
+ m_mapKeyToVariantValue.insert(pr);
+ }
- return bOk;
+ return bOk;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Retrieve a data object from *this container identified by the specified ID.
+//++
+//------------------------------------------------------------------------------------
+// Details: Retrieve a data object from *this container identified by the
+// specified ID.
// Type: Method.
// Args: T - The data object's variable type.
// vId - (R) Unique ID i.e. GUID.
@@ -100,34 +103,30 @@ CMIUtilMapIdToVariant::Add(const CMIUtil
// Throws: None.
//--
template <typename T>
-bool
-CMIUtilMapIdToVariant::Get(const CMIUtilString &vId, T &vrwData, bool &vrwbFound) const
-{
- vrwbFound = false;
-
- if (!IsValid(vId))
- {
- SetErrorDescription(CMIUtilString::Format(MIRSRC(IDS_VARIANT_ERR_MAP_KEY_INVALID), vId.c_str()));
- return MIstatus::failure;
- }
-
- const MapKeyToVariantValue_t::const_iterator it = m_mapKeyToVariantValue.find(vId);
- if (it != m_mapKeyToVariantValue.end())
- {
- const CMIUtilVariant &rData = (*it).second;
- const T *pDataObj = rData.Get<T>();
- if (pDataObj != nullptr)
- {
- vrwbFound = true;
- vrwData = *pDataObj;
- return MIstatus::success;
- }
- else
- {
- SetErrorDescription(MIRSRC(IDS_VARIANT_ERR_USED_BASECLASS));
- return MIstatus::failure;
- }
+bool CMIUtilMapIdToVariant::Get(const CMIUtilString &vId, T &vrwData,
+ bool &vrwbFound) const {
+ vrwbFound = false;
+
+ if (!IsValid(vId)) {
+ SetErrorDescription(CMIUtilString::Format(
+ MIRSRC(IDS_VARIANT_ERR_MAP_KEY_INVALID), vId.c_str()));
+ return MIstatus::failure;
+ }
+
+ const MapKeyToVariantValue_t::const_iterator it =
+ m_mapKeyToVariantValue.find(vId);
+ if (it != m_mapKeyToVariantValue.end()) {
+ const CMIUtilVariant &rData = (*it).second;
+ const T *pDataObj = rData.Get<T>();
+ if (pDataObj != nullptr) {
+ vrwbFound = true;
+ vrwData = *pDataObj;
+ return MIstatus::success;
+ } else {
+ SetErrorDescription(MIRSRC(IDS_VARIANT_ERR_USED_BASECLASS));
+ return MIstatus::failure;
}
+ }
- return MIstatus::success;
+ return MIstatus::success;
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilParse.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilParse.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilParse.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilParse.cpp Tue Sep 6 15:57:50 2016
@@ -6,14 +6,15 @@
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
-
+
// Third party headers:
#include <memory>
// In-house headers:
#include "MIUtilParse.h"
-
-//++ ------------------------------------------------------------------------------------
+
+//++
+//------------------------------------------------------------------------------------
// Details: CRegexParser constructor.
// Type: Method.
// Args: regexStr - Pointer to the regular expression to compile.
@@ -21,25 +22,24 @@
// Throws: None.
//--
MIUtilParse::CRegexParser::CRegexParser(const char *regexStr)
- : m_isValid(llvm_regcomp(&m_emma, regexStr, REG_EXTENDED) == 0)
-{
-}
-
-//++ ------------------------------------------------------------------------------------
+ : m_isValid(llvm_regcomp(&m_emma, regexStr, REG_EXTENDED) == 0) {}
+
+//++
+//------------------------------------------------------------------------------------
// Details: CRegexParser destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-MIUtilParse::CRegexParser::~CRegexParser()
-{
- // Free up memory held within regex.
- if (m_isValid)
- llvm_regfree(&m_emma);
+MIUtilParse::CRegexParser::~CRegexParser() {
+ // Free up memory held within regex.
+ if (m_isValid)
+ llvm_regfree(&m_emma);
}
-
-//++ ------------------------------------------------------------------------------------
+
+//++
+//------------------------------------------------------------------------------------
// Details: CRegexParser regex executer.
// Match the input against the regular expression. Return an error
// if the number of matches is less than minMatches. If the default
@@ -54,22 +54,21 @@ MIUtilParse::CRegexParser::~CRegexParser
// false = minimum matches were not met or regex failed.
// Throws: None.
//--
-bool
-MIUtilParse::CRegexParser::Execute(const char *input, Match& match, size_t minMatches)
-{
- if (!m_isValid)
- return false;
-
- std::unique_ptr<llvm_regmatch_t[]> matches(new llvm_regmatch_t[match.m_maxMatches]); // Array of matches
-
- if (llvm_regexec(&m_emma, input, match.m_maxMatches, matches.get(), 0) != 0)
- return false;
-
- size_t i;
- for (i = 0; i < match.m_maxMatches && matches[i].rm_so >= 0; i++)
- {
- const int n = matches[i].rm_eo - matches[i].rm_so;
- match.m_matchStrs[i].assign(input + matches[i].rm_so, n);
- }
- return i >= minMatches;
+bool MIUtilParse::CRegexParser::Execute(const char *input, Match &match,
+ size_t minMatches) {
+ if (!m_isValid)
+ return false;
+
+ std::unique_ptr<llvm_regmatch_t[]> matches(
+ new llvm_regmatch_t[match.m_maxMatches]); // Array of matches
+
+ if (llvm_regexec(&m_emma, input, match.m_maxMatches, matches.get(), 0) != 0)
+ return false;
+
+ size_t i;
+ for (i = 0; i < match.m_maxMatches && matches[i].rm_so >= 0; i++) {
+ const int n = matches[i].rm_eo - matches[i].rm_so;
+ match.m_matchStrs[i].assign(input + matches[i].rm_so, n);
+ }
+ return i >= minMatches;
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilParse.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilParse.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilParse.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilParse.h Tue Sep 6 15:57:50 2016
@@ -6,88 +6,72 @@
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
-
+
#pragma once
-
+
// Third party headers:
#include "../lib/Support/regex_impl.h"
// In-house headers:
#include "MIUtilString.h"
-
-namespace MIUtilParse
-{
-
-//++ ============================================================================
+
+namespace MIUtilParse {
+
+//++
+//============================================================================
// Details: MI common code utility class. Used to parse the output
// returned from lldb commands using regex.
//--
-class CRegexParser
-{
+class CRegexParser {
+public:
+ // Helper class for keeping track of regex matches.
+ class Match {
+ friend CRegexParser;
+
public:
- // Helper class for keeping track of regex matches.
- class Match
- {
- friend CRegexParser;
- public:
- /* ctor */ explicit Match(size_t nmatches)
- : m_matchStrs(nmatches), m_maxMatches(nmatches)
- {
- }
- size_t
- GetMatchCount() const
- {
- return m_matchStrs.size();
- }
- CMIUtilString
- GetMatchAtIndex(size_t i) const
- {
- if (m_matchStrs.size() > i)
- return m_matchStrs[i];
- return CMIUtilString();
- }
- private:
- CMIUtilString::VecString_t m_matchStrs;
- const size_t m_maxMatches;
- };
-
- // Methods:
- // Compile the regular expression.
- /* ctor */ explicit CRegexParser(const char *regexStr);
-
- // Free the memory used by the regular expression.
- /* dtor */ ~CRegexParser();
-
- // No copies
- CRegexParser(const CRegexParser&) = delete;
- void operator=(CRegexParser&) = delete;
-
- // Return the match at the index.
- int
- GetMatchCount(const Match& match) const
- {
- if (m_isValid)
- return match.GetMatchCount();
- return 0;
- }
-
- bool
- IsValid() const
- {
- return m_isValid;
+ /* ctor */ explicit Match(size_t nmatches)
+ : m_matchStrs(nmatches), m_maxMatches(nmatches) {}
+ size_t GetMatchCount() const { return m_matchStrs.size(); }
+ CMIUtilString GetMatchAtIndex(size_t i) const {
+ if (m_matchStrs.size() > i)
+ return m_matchStrs[i];
+ return CMIUtilString();
}
-
- // Match the input against the regular expression. Return an error
- // if the number of matches is less than minMatches. If the default
- // minMatches value of 0 is passed, an error will be returned if
- // the number of matches is less than the maxMatches value used to
- // initialize Match.
- bool
- Execute(const char *input, Match& match, size_t minMatches = 0);
-
+
private:
- llvm_regex_t m_emma;
- const bool m_isValid;
-};
+ CMIUtilString::VecString_t m_matchStrs;
+ const size_t m_maxMatches;
+ };
+ // Methods:
+ // Compile the regular expression.
+ /* ctor */ explicit CRegexParser(const char *regexStr);
+
+ // Free the memory used by the regular expression.
+ /* dtor */ ~CRegexParser();
+
+ // No copies
+ CRegexParser(const CRegexParser &) = delete;
+ void operator=(CRegexParser &) = delete;
+
+ // Return the match at the index.
+ int GetMatchCount(const Match &match) const {
+ if (m_isValid)
+ return match.GetMatchCount();
+ return 0;
+ }
+
+ bool IsValid() const { return m_isValid; }
+
+ // Match the input against the regular expression. Return an error
+ // if the number of matches is less than minMatches. If the default
+ // minMatches value of 0 is passed, an error will be returned if
+ // the number of matches is less than the maxMatches value used to
+ // initialize Match.
+ bool Execute(const char *input, Match &match, size_t minMatches = 0);
+
+private:
+ llvm_regex_t m_emma;
+ const bool m_isValid;
+};
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilSingletonBase.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilSingletonBase.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilSingletonBase.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilSingletonBase.h Tue Sep 6 15:57:50 2016
@@ -9,8 +9,7 @@
#pragma once
-namespace MI
-{
+namespace MI {
// MI::ISingleton base class usage:
//
@@ -26,31 +25,29 @@ namespace MI
// bool Shutdown() override;
// };
-//++ ============================================================================
+//++
+//============================================================================
// Details: Base class for the singleton pattern.
// Gotchas: Derived class must specify MI::ISingleton<> as a friend class.
//--
-template <typename T> class ISingleton
-{
- // Statics:
- public:
- // Return an instance of the derived class
- static T &
- Instance()
- {
- // This will fail if the derived class has not
- // declared itself to be a friend of MI::ISingleton
- static T instance;
-
- return instance;
- }
-
- // Overrideable:
- public:
- virtual bool Initialize() = 0;
- virtual bool Shutdown() = 0;
- //
- /* dtor */ virtual ~ISingleton(){}
+template <typename T> class ISingleton {
+ // Statics:
+public:
+ // Return an instance of the derived class
+ static T &Instance() {
+ // This will fail if the derived class has not
+ // declared itself to be a friend of MI::ISingleton
+ static T instance;
+
+ return instance;
+ }
+
+ // Overrideable:
+public:
+ virtual bool Initialize() = 0;
+ virtual bool Shutdown() = 0;
+ //
+ /* dtor */ virtual ~ISingleton() {}
};
} // namespace MI
Modified: lldb/trunk/tools/lldb-mi/MIUtilSingletonHelper.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilSingletonHelper.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilSingletonHelper.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilSingletonHelper.h Tue Sep 6 15:57:50 2016
@@ -9,69 +9,74 @@
#pragma once
-namespace MI
-{
+namespace MI {
// In house headers:
-#include "MIUtilString.h"
#include "MICmnResources.h"
+#include "MIUtilString.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: Short cut helper function to simplify repeated initialisation of
// MI components (singletons) required by a client module.
// Type: Template method.
-// Args: vErrorResrcId - (R) The string resource ID error message identifier to place in errMsg.
-// vwrbOk - (RW) On input True = Try to initialize MI driver module.
-// On output True = MI driver module initialise successfully.
-// vwrErrMsg - (W) MI driver module initialise error description on failure.
+// Args: vErrorResrcId - (R) The string resource ID error message
+// identifier to place in errMsg.
+// vwrbOk - (RW) On input True = Try to initialize MI driver
+// module.
+// On output True = MI driver module initialise
+// successfully.
+// vwrErrMsg - (W) MI driver module initialise error description
+// on failure.
// Return: MIstatus::success - Functional succeeded.
// MIstatus::failure - Functional failed.
//--
template <typename T>
-bool
-ModuleInit(const MIint vErrorResrcId, bool &vwrbOk, CMIUtilString &vwrErrMsg)
-{
- if (vwrbOk && !T::Instance().Initialize())
- {
- vwrbOk = MIstatus::failure;
- vwrErrMsg = CMIUtilString::Format(MIRSRC(vErrorResrcId), T::Instance().GetErrorDescription().c_str());
- }
+bool ModuleInit(const MIint vErrorResrcId, bool &vwrbOk,
+ CMIUtilString &vwrErrMsg) {
+ if (vwrbOk && !T::Instance().Initialize()) {
+ vwrbOk = MIstatus::failure;
+ vwrErrMsg = CMIUtilString::Format(
+ MIRSRC(vErrorResrcId), T::Instance().GetErrorDescription().c_str());
+ }
- return vwrbOk;
+ return vwrbOk;
}
-//++ ============================================================================
+//++
+//============================================================================
// Details: Short cut helper function to simplify repeated shutdown of
// MI components (singletons) required by a client module.
// Type: Template method.
-// Args: vErrorResrcId - (R) The string resource ID error message identifier
+// Args: vErrorResrcId - (R) The string resource ID error message
+// identifier
// to place in errMsg.
// vwrbOk - (W) If not already false make false on module
// shutdown failure.
-// vwrErrMsg - (RW) Append to existing error description string MI
+// vwrErrMsg - (RW) Append to existing error description string
+// MI
// driver module initialise error description on
// failure.
// Return: True - Module shutdown succeeded.
// False - Module shutdown failed.
//--
template <typename T>
-bool
-ModuleShutdown(const MIint vErrorResrcId, bool &vwrbOk, CMIUtilString &vwrErrMsg)
-{
- bool bOk = MIstatus::success;
-
- if (!T::Instance().Shutdown())
- {
- const bool bMoreThanOneError(!vwrErrMsg.empty());
- bOk = MIstatus::failure;
- if (bMoreThanOneError)
- vwrErrMsg += ", ";
- vwrErrMsg += CMIUtilString::Format(MIRSRC(vErrorResrcId), T::Instance().GetErrorDescription().c_str());
- }
+bool ModuleShutdown(const MIint vErrorResrcId, bool &vwrbOk,
+ CMIUtilString &vwrErrMsg) {
+ bool bOk = MIstatus::success;
+
+ if (!T::Instance().Shutdown()) {
+ const bool bMoreThanOneError(!vwrErrMsg.empty());
+ bOk = MIstatus::failure;
+ if (bMoreThanOneError)
+ vwrErrMsg += ", ";
+ vwrErrMsg += CMIUtilString::Format(
+ MIRSRC(vErrorResrcId), T::Instance().GetErrorDescription().c_str());
+ }
- vwrbOk = bOk ? vwrbOk : MIstatus::failure;
+ vwrbOk = bOk ? vwrbOk : MIstatus::failure;
- return bOk;
+ return bOk;
}
} // namespace MI
Modified: lldb/trunk/tools/lldb-mi/MIUtilString.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilString.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilString.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilString.cpp Tue Sep 6 15:57:50 2016
@@ -18,81 +18,76 @@
// In-house headers:
#include "MIUtilString.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilString::CMIUtilString()
- : std::string()
-{
-}
+CMIUtilString::CMIUtilString() : std::string() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString constructor.
// Type: Method.
// Args: vpData - Pointer to UTF8 text data.
// Return: None.
// Throws: None.
//--
-CMIUtilString::CMIUtilString(const char *vpData)
- : std::string(vpData)
-{
-}
+CMIUtilString::CMIUtilString(const char *vpData) : std::string(vpData) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString constructor.
// Type: Method.
// Args: vpStr - Text data.
// Return: None.
// Throws: None.
//--
-CMIUtilString::CMIUtilString(const std::string& vrStr)
- : std::string(vrStr)
-{
-}
+CMIUtilString::CMIUtilString(const std::string &vrStr) : std::string(vrStr) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString assignment operator.
// Type: Method.
// Args: vpRhs - Pointer to UTF8 text data.
// Return: CMIUtilString & - *this string.
// Throws: None.
//--
-CMIUtilString &CMIUtilString::operator=(const char *vpRhs)
-{
- assign(vpRhs);
- return *this;
+CMIUtilString &CMIUtilString::operator=(const char *vpRhs) {
+ assign(vpRhs);
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString assignment operator.
// Type: Method.
// Args: vrRhs - The other string to copy from.
// Return: CMIUtilString & - *this string.
// Throws: None.
//--
-CMIUtilString &CMIUtilString::operator=(const std::string &vrRhs)
-{
- assign(vrRhs);
- return *this;
+CMIUtilString &CMIUtilString::operator=(const std::string &vrRhs) {
+ assign(vrRhs);
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilString destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilString::~CMIUtilString()
-{
-}
+CMIUtilString::~CMIUtilString() {}
-//++ ------------------------------------------------------------------------------------
-// Details: Perform a snprintf format style on a string data. A new string object is
+//++
+//------------------------------------------------------------------------------------
+// Details: Perform a snprintf format style on a string data. A new string
+// object is
// created and returned.
// Type: Static method.
// Args: vrFormat - (R) Format string data instruction.
@@ -100,57 +95,60 @@ CMIUtilString::~CMIUtilString()
// Return: CMIUtilString - Number of splits found in the string data.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::FormatPriv(const CMIUtilString &vrFormat, va_list vArgs)
-{
- CMIUtilString strResult;
- MIint nFinal = 0;
- MIint n = vrFormat.size();
-
- // IOR: mysterious crash in this function on some windows builds not able to duplicate
- // but found article which may be related. Crash occurs in vsnprintf() or va_copy()
- // Duplicate vArgs va_list argument pointer to ensure that it can be safely used in
- // a new frame
- // http://julipedia.meroh.net/2011/09/using-vacopy-to-safely-pass-ap.html
- va_list argsDup;
- va_copy(argsDup, vArgs);
-
- // Create a copy va_list to reset when we spin
- va_list argsCpy;
- va_copy(argsCpy, argsDup);
-
- if (n == 0)
- return strResult;
-
- n = n << 4; // Reserve 16 times as much the length of the vrFormat
-
- std::unique_ptr<char[]> pFormatted;
- while (1)
- {
- pFormatted.reset(new char[n + 1]); // +1 for safety margin
- ::strncpy(&pFormatted[0], vrFormat.c_str(), n);
-
- // We need to restore the variable argument list pointer to the start again
- // before running vsnprintf() more then once
- va_copy(argsDup, argsCpy);
-
- nFinal = ::vsnprintf(&pFormatted[0], n, vrFormat.c_str(), argsDup);
- if ((nFinal < 0) || (nFinal >= n))
- n += abs(nFinal - n + 1);
- else
- break;
- }
+CMIUtilString CMIUtilString::FormatPriv(const CMIUtilString &vrFormat,
+ va_list vArgs) {
+ CMIUtilString strResult;
+ MIint nFinal = 0;
+ MIint n = vrFormat.size();
+
+ // IOR: mysterious crash in this function on some windows builds not able to
+ // duplicate
+ // but found article which may be related. Crash occurs in vsnprintf() or
+ // va_copy()
+ // Duplicate vArgs va_list argument pointer to ensure that it can be safely
+ // used in
+ // a new frame
+ // http://julipedia.meroh.net/2011/09/using-vacopy-to-safely-pass-ap.html
+ va_list argsDup;
+ va_copy(argsDup, vArgs);
+
+ // Create a copy va_list to reset when we spin
+ va_list argsCpy;
+ va_copy(argsCpy, argsDup);
+
+ if (n == 0)
+ return strResult;
- va_end(argsCpy);
- va_end(argsDup);
+ n = n << 4; // Reserve 16 times as much the length of the vrFormat
- strResult = pFormatted.get();
+ std::unique_ptr<char[]> pFormatted;
+ while (1) {
+ pFormatted.reset(new char[n + 1]); // +1 for safety margin
+ ::strncpy(&pFormatted[0], vrFormat.c_str(), n);
- return strResult;
+ // We need to restore the variable argument list pointer to the start again
+ // before running vsnprintf() more then once
+ va_copy(argsDup, argsCpy);
+
+ nFinal = ::vsnprintf(&pFormatted[0], n, vrFormat.c_str(), argsDup);
+ if ((nFinal < 0) || (nFinal >= n))
+ n += abs(nFinal - n + 1);
+ else
+ break;
+ }
+
+ va_end(argsCpy);
+ va_end(argsDup);
+
+ strResult = pFormatted.get();
+
+ return strResult;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Perform a snprintf format style on a string data. A new string object is
+//++
+//------------------------------------------------------------------------------------
+// Details: Perform a snprintf format style on a string data. A new string
+// object is
// created and returned.
// Type: Static method.
// Args: vFormat - (R) Format string data instruction.
@@ -158,19 +156,19 @@ CMIUtilString::FormatPriv(const CMIUtilS
// Return: CMIUtilString - Number of splits found in the string data.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::Format(const CMIUtilString vFormating, ...)
-{
- va_list args;
- va_start(args, vFormating);
- CMIUtilString strResult = CMIUtilString::FormatPriv(vFormating, args);
- va_end(args);
-
- return strResult;
+CMIUtilString CMIUtilString::Format(const CMIUtilString vFormating, ...) {
+ va_list args;
+ va_start(args, vFormating);
+ CMIUtilString strResult = CMIUtilString::FormatPriv(vFormating, args);
+ va_end(args);
+
+ return strResult;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Perform a snprintf format style on a string data. A new string object is
+//++
+//------------------------------------------------------------------------------------
+// Details: Perform a snprintf format style on a string data. A new string
+// object is
// created and returned.
// Type: Static method.
// Args: vrFormat - (R) Format string data instruction.
@@ -178,14 +176,15 @@ CMIUtilString::Format(const CMIUtilStrin
// Return: CMIUtilString - Number of splits found in the string data.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::FormatValist(const CMIUtilString &vrFormating, va_list vArgs)
-{
- return CMIUtilString::FormatPriv(vrFormating, vArgs);
+CMIUtilString CMIUtilString::FormatValist(const CMIUtilString &vrFormating,
+ va_list vArgs) {
+ return CMIUtilString::FormatPriv(vrFormating, vArgs);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Splits string into array of strings using delimiter. If multiple delimiter
+//++
+//------------------------------------------------------------------------------------
+// Details: Splits string into array of strings using delimiter. If multiple
+// delimiter
// are found in sequence then they are not added to the list of splits.
// Type: Method.
// Args: vData - (R) String data to be split up.
@@ -194,47 +193,50 @@ CMIUtilString::FormatValist(const CMIUti
// Return: size_t - Number of splits found in the string data.
// Throws: None.
//--
-size_t
-CMIUtilString::Split(const CMIUtilString &vDelimiter, VecString_t &vwVecSplits) const
-{
- vwVecSplits.clear();
-
- if (this->empty() || vDelimiter.empty())
- return 0;
-
- const size_t nLen(length());
- size_t nOffset(0);
- do
- {
- // Find first occurrence which doesn't match to the delimiter
- const size_t nSectionPos(FindFirstNot(vDelimiter, nOffset));
- if (nSectionPos == std::string::npos)
- break;
-
- // Find next occurrence of the delimiter after section
- size_t nNextDelimiterPos(FindFirst(vDelimiter, nSectionPos));
- if (nNextDelimiterPos == std::string::npos)
- nNextDelimiterPos = nLen;
-
- // Extract string between delimiters
- const size_t nSectionLen(nNextDelimiterPos - nSectionPos);
- const std::string strSection(substr(nSectionPos, nSectionLen));
- vwVecSplits.push_back(strSection);
-
- // Next
- nOffset = nNextDelimiterPos + 1;
- }
- while (nOffset < nLen);
-
- return vwVecSplits.size();
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Splits string into array of strings using delimiter. However the string is
-// also considered for text surrounded by quotes. Text with quotes including the
-// delimiter is treated as a whole. If multiple delimiter are found in sequence
-// then they are not added to the list of splits. Quotes that are embedded in
-// the string as string formatted quotes are ignored (proceeded by a '\\') i.e.
+size_t CMIUtilString::Split(const CMIUtilString &vDelimiter,
+ VecString_t &vwVecSplits) const {
+ vwVecSplits.clear();
+
+ if (this->empty() || vDelimiter.empty())
+ return 0;
+
+ const size_t nLen(length());
+ size_t nOffset(0);
+ do {
+ // Find first occurrence which doesn't match to the delimiter
+ const size_t nSectionPos(FindFirstNot(vDelimiter, nOffset));
+ if (nSectionPos == std::string::npos)
+ break;
+
+ // Find next occurrence of the delimiter after section
+ size_t nNextDelimiterPos(FindFirst(vDelimiter, nSectionPos));
+ if (nNextDelimiterPos == std::string::npos)
+ nNextDelimiterPos = nLen;
+
+ // Extract string between delimiters
+ const size_t nSectionLen(nNextDelimiterPos - nSectionPos);
+ const std::string strSection(substr(nSectionPos, nSectionLen));
+ vwVecSplits.push_back(strSection);
+
+ // Next
+ nOffset = nNextDelimiterPos + 1;
+ } while (nOffset < nLen);
+
+ return vwVecSplits.size();
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Splits string into array of strings using delimiter. However the
+// string is
+// also considered for text surrounded by quotes. Text with quotes
+// including the
+// delimiter is treated as a whole. If multiple delimiter are found in
+// sequence
+// then they are not added to the list of splits. Quotes that are
+// embedded in
+// the string as string formatted quotes are ignored (proceeded by a
+// '\\') i.e.
// "\"MI GDB local C++.cpp\":88".
// Type: Method.
// Args: vData - (R) String data to be split up.
@@ -243,62 +245,59 @@ CMIUtilString::Split(const CMIUtilString
// Return: size_t - Number of splits found in the string data.
// Throws: None.
//--
-size_t
-CMIUtilString::SplitConsiderQuotes(const CMIUtilString &vDelimiter, VecString_t &vwVecSplits) const
-{
- vwVecSplits.clear();
-
- if (this->empty() || vDelimiter.empty())
- return 0;
-
- const size_t nLen(length());
- size_t nOffset(0);
- do
- {
- // Find first occurrence which doesn't match to the delimiter
- const size_t nSectionPos(FindFirstNot(vDelimiter, nOffset));
- if (nSectionPos == std::string::npos)
- break;
-
- // Find next occurrence of the delimiter after (quoted) section
- const bool bSkipQuotedText(true);
- bool bUnmatchedQuote(false);
- size_t nNextDelimiterPos(FindFirst(vDelimiter, bSkipQuotedText, bUnmatchedQuote, nSectionPos));
- if (bUnmatchedQuote)
- {
- vwVecSplits.clear();
- return 0;
- }
- if (nNextDelimiterPos == std::string::npos)
- nNextDelimiterPos = nLen;
-
- // Extract string between delimiters
- const size_t nSectionLen(nNextDelimiterPos - nSectionPos);
- const std::string strSection(substr(nSectionPos, nSectionLen));
- vwVecSplits.push_back(strSection);
+size_t CMIUtilString::SplitConsiderQuotes(const CMIUtilString &vDelimiter,
+ VecString_t &vwVecSplits) const {
+ vwVecSplits.clear();
+
+ if (this->empty() || vDelimiter.empty())
+ return 0;
+
+ const size_t nLen(length());
+ size_t nOffset(0);
+ do {
+ // Find first occurrence which doesn't match to the delimiter
+ const size_t nSectionPos(FindFirstNot(vDelimiter, nOffset));
+ if (nSectionPos == std::string::npos)
+ break;
+
+ // Find next occurrence of the delimiter after (quoted) section
+ const bool bSkipQuotedText(true);
+ bool bUnmatchedQuote(false);
+ size_t nNextDelimiterPos(
+ FindFirst(vDelimiter, bSkipQuotedText, bUnmatchedQuote, nSectionPos));
+ if (bUnmatchedQuote) {
+ vwVecSplits.clear();
+ return 0;
+ }
+ if (nNextDelimiterPos == std::string::npos)
+ nNextDelimiterPos = nLen;
+
+ // Extract string between delimiters
+ const size_t nSectionLen(nNextDelimiterPos - nSectionPos);
+ const std::string strSection(substr(nSectionPos, nSectionLen));
+ vwVecSplits.push_back(strSection);
+
+ // Next
+ nOffset = nNextDelimiterPos + 1;
+ } while (nOffset < nLen);
- // Next
- nOffset = nNextDelimiterPos + 1;
- }
- while (nOffset < nLen);
-
- return vwVecSplits.size();
+ return vwVecSplits.size();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Split string into lines using \n and return an array of strings.
// Type: Method.
// Args: vwVecSplits - (W) Container of splits found in string data.
// Return: size_t - Number of splits found in the string data.
// Throws: None.
//--
-size_t
-CMIUtilString::SplitLines(VecString_t &vwVecSplits) const
-{
- return Split("\n", vwVecSplits);
+size_t CMIUtilString::SplitLines(VecString_t &vwVecSplits) const {
+ return Split("\n", vwVecSplits);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Remove '\n' from the end of string if found. It does not alter
// *this string.
// Type: Method.
@@ -306,34 +305,34 @@ CMIUtilString::SplitLines(VecString_t &v
// Return: CMIUtilString - New version of the string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::StripCREndOfLine() const
-{
- const size_t nPos = rfind('\n');
- if (nPos == std::string::npos)
- return *this;
+CMIUtilString CMIUtilString::StripCREndOfLine() const {
+ const size_t nPos = rfind('\n');
+ if (nPos == std::string::npos)
+ return *this;
- const CMIUtilString strNew(substr(0, nPos));
+ const CMIUtilString strNew(substr(0, nPos));
- return strNew;
+ return strNew;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Remove all '\n' from the string and replace with a space. It does not alter
+//++
+//------------------------------------------------------------------------------------
+// Details: Remove all '\n' from the string and replace with a space. It does
+// not alter
// *this string.
// Type: Method.
// Args: None.
// Return: CMIUtilString - New version of the string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::StripCRAll() const
-{
- return FindAndReplace("\n", " ");
+CMIUtilString CMIUtilString::StripCRAll() const {
+ return FindAndReplace("\n", " ");
}
-//++ ------------------------------------------------------------------------------------
-// Details: Find and replace all matches of a sub string with another string. It does not
+//++
+//------------------------------------------------------------------------------------
+// Details: Find and replace all matches of a sub string with another string. It
+// does not
// alter *this string.
// Type: Method.
// Args: vFind - (R) The string to look for.
@@ -342,150 +341,145 @@ CMIUtilString::StripCRAll() const
// Throws: None.
//--
CMIUtilString
-CMIUtilString::FindAndReplace(const CMIUtilString &vFind, const CMIUtilString &vReplaceWith) const
-{
- if (vFind.empty() || this->empty())
- return *this;
-
- size_t nPos = find(vFind);
- if (nPos == std::string::npos)
- return *this;
-
- CMIUtilString strNew(*this);
- while (nPos != std::string::npos)
- {
- strNew.replace(nPos, vFind.length(), vReplaceWith);
- nPos += vReplaceWith.length();
- nPos = strNew.find(vFind, nPos);
- }
+CMIUtilString::FindAndReplace(const CMIUtilString &vFind,
+ const CMIUtilString &vReplaceWith) const {
+ if (vFind.empty() || this->empty())
+ return *this;
+
+ size_t nPos = find(vFind);
+ if (nPos == std::string::npos)
+ return *this;
- return strNew;
+ CMIUtilString strNew(*this);
+ while (nPos != std::string::npos) {
+ strNew.replace(nPos, vFind.length(), vReplaceWith);
+ nPos += vReplaceWith.length();
+ nPos = strNew.find(vFind, nPos);
+ }
+
+ return strNew;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check if *this string is a decimal number.
// Type: Method.
// Args: None.
// Return: bool - True = yes number, false not a number.
// Throws: None.
//--
-bool
-CMIUtilString::IsNumber() const
-{
- if (empty())
- return false;
+bool CMIUtilString::IsNumber() const {
+ if (empty())
+ return false;
- if ((at(0) == '-') && (length() == 1))
- return false;
+ if ((at(0) == '-') && (length() == 1))
+ return false;
- const size_t nPos = find_first_not_of("-.0123456789");
- if (nPos != std::string::npos)
- return false;
+ const size_t nPos = find_first_not_of("-.0123456789");
+ if (nPos != std::string::npos)
+ return false;
- return true;
+ return true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check if *this string is a hexadecimal number.
// Type: Method.
// Args: None.
// Return: bool - True = yes number, false not a number.
// Throws: None.
//--
-bool
-CMIUtilString::IsHexadecimalNumber() const
-{
- // Compare '0x..' prefix
- if ((strncmp(c_str(), "0x", 2) != 0) && (strncmp(c_str(), "0X", 2) != 0))
- return false;
-
- // Skip '0x..' prefix
- const size_t nPos = find_first_not_of("01234567890ABCDEFabcedf", 2);
- if (nPos != std::string::npos)
- return false;
-
- return true;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Extract the number from the string. The number can be either a hexadecimal or
+bool CMIUtilString::IsHexadecimalNumber() const {
+ // Compare '0x..' prefix
+ if ((strncmp(c_str(), "0x", 2) != 0) && (strncmp(c_str(), "0X", 2) != 0))
+ return false;
+
+ // Skip '0x..' prefix
+ const size_t nPos = find_first_not_of("01234567890ABCDEFabcedf", 2);
+ if (nPos != std::string::npos)
+ return false;
+
+ return true;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Extract the number from the string. The number can be either a
+// hexadecimal or
// natural number. It cannot contain other non-numeric characters.
// Type: Method.
// Args: vwrNumber - (W) Number extracted from the string.
// Return: bool - True = yes number, false not a number.
// Throws: None.
//--
-bool
-CMIUtilString::ExtractNumber(MIint64 &vwrNumber) const
-{
- vwrNumber = 0;
-
- if (!IsNumber())
- {
- if (ExtractNumberFromHexadecimal(vwrNumber))
- return true;
+bool CMIUtilString::ExtractNumber(MIint64 &vwrNumber) const {
+ vwrNumber = 0;
- return false;
- }
+ if (!IsNumber()) {
+ if (ExtractNumberFromHexadecimal(vwrNumber))
+ return true;
+
+ return false;
+ }
- std::stringstream ss(const_cast<CMIUtilString &>(*this));
- ss >> vwrNumber;
+ std::stringstream ss(const_cast<CMIUtilString &>(*this));
+ ss >> vwrNumber;
- return true;
+ return true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Extract the number from the hexadecimal string..
// Type: Method.
// Args: vwrNumber - (W) Number extracted from the string.
// Return: bool - True = yes number, false not a number.
// Throws: None.
//--
-bool
-CMIUtilString::ExtractNumberFromHexadecimal(MIint64 &vwrNumber) const
-{
- vwrNumber = 0;
+bool CMIUtilString::ExtractNumberFromHexadecimal(MIint64 &vwrNumber) const {
+ vwrNumber = 0;
- const size_t nPos = find_first_not_of("xX01234567890ABCDEFabcedf");
- if (nPos != std::string::npos)
- return false;
+ const size_t nPos = find_first_not_of("xX01234567890ABCDEFabcedf");
+ if (nPos != std::string::npos)
+ return false;
- errno = 0;
- const MIuint64 nNum = ::strtoull(this->c_str(), nullptr, 16);
- if (errno == ERANGE)
- return false;
+ errno = 0;
+ const MIuint64 nNum = ::strtoull(this->c_str(), nullptr, 16);
+ if (errno == ERANGE)
+ return false;
- vwrNumber = static_cast<MIint64>(nNum);
+ vwrNumber = static_cast<MIint64>(nNum);
- return true;
+ return true;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Determine if the text is all valid alpha numeric characters. Letters can be
+//++
+//------------------------------------------------------------------------------------
+// Details: Determine if the text is all valid alpha numeric characters. Letters
+// can be
// either upper or lower case.
// Type: Static method.
// Args: vpText - (R) The text data to examine.
// Return: bool - True = yes all alpha, false = one or more chars is non alpha.
// Throws: None.
//--
-bool
-CMIUtilString::IsAllValidAlphaAndNumeric(const char *vpText)
-{
- const size_t len = ::strlen(vpText);
- if (len == 0)
- return false;
-
- for (size_t i = 0; i < len; i++, vpText++)
- {
- const char c = *vpText;
- if (::isalnum((int)c) == 0)
- return false;
- }
+bool CMIUtilString::IsAllValidAlphaAndNumeric(const char *vpText) {
+ const size_t len = ::strlen(vpText);
+ if (len == 0)
+ return false;
+
+ for (size_t i = 0; i < len; i++, vpText++) {
+ const char c = *vpText;
+ if (::isalnum((int)c) == 0)
+ return false;
+ }
- return true;
+ return true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check if two strings share equal contents.
// Type: Method.
// Args: vrLhs - (R) String A.
@@ -493,491 +487,474 @@ CMIUtilString::IsAllValidAlphaAndNumeric
// Return: bool - True = yes equal, false - different.
// Throws: None.
//--
-bool
-CMIUtilString::Compare(const CMIUtilString &vrLhs, const CMIUtilString &vrRhs)
-{
- // Check the sizes match
- if (vrLhs.size() != vrRhs.size())
- return false;
+bool CMIUtilString::Compare(const CMIUtilString &vrLhs,
+ const CMIUtilString &vrRhs) {
+ // Check the sizes match
+ if (vrLhs.size() != vrRhs.size())
+ return false;
- return (::strncmp(vrLhs.c_str(), vrRhs.c_str(), vrLhs.size()) == 0);
+ return (::strncmp(vrLhs.c_str(), vrRhs.c_str(), vrLhs.size()) == 0);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Remove from either end of *this string the following: " \t\n\v\f\r".
// Type: Method.
// Args: None.
// Return: CMIUtilString - Trimmed string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::Trim() const
-{
- CMIUtilString strNew(*this);
- const char *pWhiteSpace = " \t\n\v\f\r";
- const size_t nPos = find_last_not_of(pWhiteSpace);
- if (nPos != std::string::npos)
- {
- strNew = substr(0, nPos + 1);
- }
- const size_t nPos2 = strNew.find_first_not_of(pWhiteSpace);
- if (nPos2 != std::string::npos)
- {
- strNew = strNew.substr(nPos2);
- }
+CMIUtilString CMIUtilString::Trim() const {
+ CMIUtilString strNew(*this);
+ const char *pWhiteSpace = " \t\n\v\f\r";
+ const size_t nPos = find_last_not_of(pWhiteSpace);
+ if (nPos != std::string::npos) {
+ strNew = substr(0, nPos + 1);
+ }
+ const size_t nPos2 = strNew.find_first_not_of(pWhiteSpace);
+ if (nPos2 != std::string::npos) {
+ strNew = strNew.substr(nPos2);
+ }
- return strNew;
+ return strNew;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Remove from either end of *this string the specified character.
// Type: Method.
// Args: None.
// Return: CMIUtilString - Trimmed string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::Trim(const char vChar) const
-{
- CMIUtilString strNew(*this);
- const size_t nLen = strNew.length();
- if (nLen > 1)
- {
- if ((strNew[0] == vChar) && (strNew[nLen - 1] == vChar))
- strNew = strNew.substr(1, nLen - 2);
- }
+CMIUtilString CMIUtilString::Trim(const char vChar) const {
+ CMIUtilString strNew(*this);
+ const size_t nLen = strNew.length();
+ if (nLen > 1) {
+ if ((strNew[0] == vChar) && (strNew[nLen - 1] == vChar))
+ strNew = strNew.substr(1, nLen - 2);
+ }
- return strNew;
+ return strNew;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Do a printf equivalent for printing a number in binary i.e. "b%llB".
// Type: Static method.
// Args: vnDecimal - (R) The number to represent in binary.
// Return: CMIUtilString - Binary number in text.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::FormatBinary(const MIuint64 vnDecimal)
-{
- CMIUtilString strBinaryNumber;
-
- const MIuint nConstBits = 64;
- MIuint nRem[nConstBits + 1];
- MIint i = 0;
- MIuint nLen = 0;
- MIuint64 nNum = vnDecimal;
- while ((nNum > 0) && (nLen < nConstBits))
- {
- nRem[i++] = nNum % 2;
- nNum = nNum >> 1;
- nLen++;
- }
- char pN[nConstBits + 1];
- MIuint j = 0;
- for (i = nLen; i > 0; --i, j++)
- {
- pN[j] = '0' + nRem[i - 1];
- }
- pN[j] = 0; // String NUL termination
-
- strBinaryNumber = CMIUtilString::Format("0b%s", &pN[0]);
-
- return strBinaryNumber;
-}
+CMIUtilString CMIUtilString::FormatBinary(const MIuint64 vnDecimal) {
+ CMIUtilString strBinaryNumber;
-//++ ------------------------------------------------------------------------------------
-// Details: Remove from a string doubled up characters so only one set left. Characters
-// are only removed if the previous character is already a same character.
+ const MIuint nConstBits = 64;
+ MIuint nRem[nConstBits + 1];
+ MIint i = 0;
+ MIuint nLen = 0;
+ MIuint64 nNum = vnDecimal;
+ while ((nNum > 0) && (nLen < nConstBits)) {
+ nRem[i++] = nNum % 2;
+ nNum = nNum >> 1;
+ nLen++;
+ }
+ char pN[nConstBits + 1];
+ MIuint j = 0;
+ for (i = nLen; i > 0; --i, j++) {
+ pN[j] = '0' + nRem[i - 1];
+ }
+ pN[j] = 0; // String NUL termination
+
+ strBinaryNumber = CMIUtilString::Format("0b%s", &pN[0]);
+
+ return strBinaryNumber;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Remove from a string doubled up characters so only one set left.
+// Characters
+// are only removed if the previous character is already a same
+// character.
// Type: Method.
-// Args: vChar - (R) The character to search for and remove adjacent duplicates.
+// Args: vChar - (R) The character to search for and remove adjacent
+// duplicates.
// Return: CMIUtilString - New version of the string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::RemoveRepeatedCharacters(const char vChar)
-{
- return RemoveRepeatedCharacters(0, vChar);
+CMIUtilString CMIUtilString::RemoveRepeatedCharacters(const char vChar) {
+ return RemoveRepeatedCharacters(0, vChar);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Recursively remove from a string doubled up characters so only one set left.
-// Characters are only removed if the previous character is already a same
+//++
+//------------------------------------------------------------------------------------
+// Details: Recursively remove from a string doubled up characters so only one
+// set left.
+// Characters are only removed if the previous character is already a
+// same
// character.
// Type: Method.
-// Args: vChar - (R) The character to search for and remove adjacent duplicates.
+// Args: vChar - (R) The character to search for and remove adjacent
+// duplicates.
// vnPos - Character position in the string.
// Return: CMIUtilString - New version of the string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::RemoveRepeatedCharacters(size_t vnPos, const char vChar)
-{
- const char cQuote = '"';
-
- // Look for first quote of two
- const size_t nPos = find(cQuote, vnPos);
- if (nPos == std::string::npos)
- return *this;
-
- const size_t nPosNext = nPos + 1;
- if (nPosNext > length())
- return *this;
-
- if (at(nPosNext) == cQuote)
- {
- *this = substr(0, nPos) + substr(nPosNext, length());
- RemoveRepeatedCharacters(nPosNext, vChar);
- }
+CMIUtilString CMIUtilString::RemoveRepeatedCharacters(size_t vnPos,
+ const char vChar) {
+ const char cQuote = '"';
+
+ // Look for first quote of two
+ const size_t nPos = find(cQuote, vnPos);
+ if (nPos == std::string::npos)
+ return *this;
+ const size_t nPosNext = nPos + 1;
+ if (nPosNext > length())
return *this;
+
+ if (at(nPosNext) == cQuote) {
+ *this = substr(0, nPos) + substr(nPosNext, length());
+ RemoveRepeatedCharacters(nPosNext, vChar);
+ }
+
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Is the text in *this string surrounded by quotes.
// Type: Method.
// Args: None.
// Return: bool - True = Yes string is quoted, false = no quoted.
// Throws: None.
//--
-bool
-CMIUtilString::IsQuoted() const
-{
- const char cQuote = '"';
+bool CMIUtilString::IsQuoted() const {
+ const char cQuote = '"';
- if (at(0) != cQuote)
- return false;
+ if (at(0) != cQuote)
+ return false;
- const size_t nLen = length();
- if ((nLen > 0) && (at(nLen - 1) != cQuote))
- return false;
+ const size_t nLen = length();
+ if ((nLen > 0) && (at(nLen - 1) != cQuote))
+ return false;
- return true;
+ return true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Find first occurrence in *this string which matches the pattern.
// Type: Method.
// Args: vrPattern - (R) The pattern to search for.
-// vnPos - The starting position at which to start searching. (Dflt = 0)
+// vnPos - The starting position at which to start searching.
+// (Dflt = 0)
// Return: size_t - The position of the first substring that match.
// Throws: None.
//--
-size_t
-CMIUtilString::FindFirst(const CMIUtilString &vrPattern, size_t vnPos /* = 0 */) const
-{
- return find(vrPattern, vnPos);
+size_t CMIUtilString::FindFirst(const CMIUtilString &vrPattern,
+ size_t vnPos /* = 0 */) const {
+ return find(vrPattern, vnPos);
}
-//++ ------------------------------------------------------------------------------------
-// Details: Find first occurrence in *this string which matches the pattern and isn't surrounded by quotes.
+//++
+//------------------------------------------------------------------------------------
+// Details: Find first occurrence in *this string which matches the pattern and
+// isn't surrounded by quotes.
// Type: Method.
// Args: vrPattern - (R) The pattern to search for.
-// vbSkipQuotedText - (R) True = don't look at quoted text, false = otherwise.
-// vrwbNotFoundClosedQuote - (W) True = parsing error: unmatched quote, false = otherwise.
-// vnPos - Position of the first character in the string to be considered in the search. (Dflt = 0)
-// Return: size_t - The position of the first substring that matches and isn't quoted.
-// Throws: None.
-//--
-size_t
-CMIUtilString::FindFirst(const CMIUtilString &vrPattern, const bool vbSkipQuotedText, bool &vrwbNotFoundClosedQuote,
- size_t vnPos /* = 0 */) const
-{
- vrwbNotFoundClosedQuote = false;
-
- if (!vbSkipQuotedText)
- return FindFirst(vrPattern, vnPos);
-
- const size_t nLen(length());
-
- size_t nPos = vnPos;
- do
- {
- const size_t nQuotePos(FindFirstQuote(nPos));
- const size_t nPatternPos(FindFirst(vrPattern, nPos));
- if (nQuotePos == std::string::npos)
- return nPatternPos;
-
- const size_t nQuoteClosedPos = FindFirstQuote(nQuotePos + 1);
- if (nQuoteClosedPos == std::string::npos)
- {
- vrwbNotFoundClosedQuote = true;
- return std::string::npos;
- }
+// vbSkipQuotedText - (R) True = don't look at quoted text,
+// false = otherwise.
+// vrwbNotFoundClosedQuote - (W) True = parsing error: unmatched
+// quote, false = otherwise.
+// vnPos - Position of the first character in the
+// string to be considered in the search. (Dflt = 0)
+// Return: size_t - The position of the first substring that matches and isn't
+// quoted.
+// Throws: None.
+//--
+size_t CMIUtilString::FindFirst(const CMIUtilString &vrPattern,
+ const bool vbSkipQuotedText,
+ bool &vrwbNotFoundClosedQuote,
+ size_t vnPos /* = 0 */) const {
+ vrwbNotFoundClosedQuote = false;
+
+ if (!vbSkipQuotedText)
+ return FindFirst(vrPattern, vnPos);
+
+ const size_t nLen(length());
- if ((nPatternPos == std::string::npos) || (nPatternPos < nQuotePos))
- return nPatternPos;
+ size_t nPos = vnPos;
+ do {
+ const size_t nQuotePos(FindFirstQuote(nPos));
+ const size_t nPatternPos(FindFirst(vrPattern, nPos));
+ if (nQuotePos == std::string::npos)
+ return nPatternPos;
- nPos = nQuoteClosedPos + 1;
+ const size_t nQuoteClosedPos = FindFirstQuote(nQuotePos + 1);
+ if (nQuoteClosedPos == std::string::npos) {
+ vrwbNotFoundClosedQuote = true;
+ return std::string::npos;
}
- while (nPos < nLen);
- return std::string::npos;
+ if ((nPatternPos == std::string::npos) || (nPatternPos < nQuotePos))
+ return nPatternPos;
+
+ nPos = nQuoteClosedPos + 1;
+ } while (nPos < nLen);
+
+ return std::string::npos;
}
-//++ ------------------------------------------------------------------------------------
-// Details: Find first occurrence in *this string which doesn't match the pattern.
+//++
+//------------------------------------------------------------------------------------
+// Details: Find first occurrence in *this string which doesn't match the
+// pattern.
// Type: Method.
// Args: vrPattern - (R) The pattern to search for.
-// vnPos - Position of the first character in the string to be considered in the search. (Dflt = 0)
+// vnPos - Position of the first character in the string to be
+// considered in the search. (Dflt = 0)
// Return: size_t - The position of the first character that doesn't match.
// Throws: None.
//--
-size_t
-CMIUtilString::FindFirstNot(const CMIUtilString &vrPattern, size_t vnPos /* = 0 */) const
-{
- const size_t nLen(length());
- const size_t nPatternLen(vrPattern.length());
-
- size_t nPatternPos(vnPos);
- do
- {
- const bool bMatchPattern(compare(nPatternPos, nPatternLen, vrPattern) == 0);
- if (!bMatchPattern)
- return nPatternPos;
- nPatternPos += nPatternLen;
- }
- while (nPatternPos < nLen);
+size_t CMIUtilString::FindFirstNot(const CMIUtilString &vrPattern,
+ size_t vnPos /* = 0 */) const {
+ const size_t nLen(length());
+ const size_t nPatternLen(vrPattern.length());
+
+ size_t nPatternPos(vnPos);
+ do {
+ const bool bMatchPattern(compare(nPatternPos, nPatternLen, vrPattern) == 0);
+ if (!bMatchPattern)
+ return nPatternPos;
+ nPatternPos += nPatternLen;
+ } while (nPatternPos < nLen);
- return std::string::npos;
+ return std::string::npos;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Find first occurrence of not escaped quotation mark in *this string.
// Type: Method.
-// Args: vnPos - Position of the first character in the string to be considered in the search.
+// Args: vnPos - Position of the first character in the string to be
+// considered in the search.
// Return: size_t - The position of the quotation mark.
// Throws: None.
//--
-size_t
-CMIUtilString::FindFirstQuote(size_t vnPos) const
-{
- const char cBckSlash('\\');
- const char cQuote('"');
- const size_t nLen(length());
-
- size_t nPos = vnPos;
- do
- {
- const size_t nBckSlashPos(find(cBckSlash, nPos));
- const size_t nQuotePos(find(cQuote, nPos));
- if ((nBckSlashPos == std::string::npos) || (nQuotePos == std::string::npos))
- return nQuotePos;
+size_t CMIUtilString::FindFirstQuote(size_t vnPos) const {
+ const char cBckSlash('\\');
+ const char cQuote('"');
+ const size_t nLen(length());
+
+ size_t nPos = vnPos;
+ do {
+ const size_t nBckSlashPos(find(cBckSlash, nPos));
+ const size_t nQuotePos(find(cQuote, nPos));
+ if ((nBckSlashPos == std::string::npos) || (nQuotePos == std::string::npos))
+ return nQuotePos;
+
+ if (nQuotePos < nBckSlashPos)
+ return nQuotePos;
+
+ // Skip 2 characters: First is '\', second is that which is escaped by '\'
+ nPos = nBckSlashPos + 2;
+ } while (nPos < nLen);
- if (nQuotePos < nBckSlashPos)
- return nQuotePos;
-
- // Skip 2 characters: First is '\', second is that which is escaped by '\'
- nPos = nBckSlashPos + 2;
- }
- while (nPos < nLen);
-
- return std::string::npos;
+ return std::string::npos;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Get escaped string from *this string.
// Type: Method.
// Args: None.
// Return: CMIUtilString - The escaped version of the initial string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::Escape(bool vbEscapeQuotes /* = false */) const
-{
- const size_t nLen(length());
- CMIUtilString strNew;
- strNew.reserve(nLen);
- for (size_t nIndex(0); nIndex < nLen; ++nIndex)
- {
- const char cUnescapedChar((*this)[nIndex]);
- if (cUnescapedChar == '"' && vbEscapeQuotes)
- strNew.append("\\\"");
- else
- strNew.append(ConvertToPrintableASCII((char)cUnescapedChar));
- }
- return strNew;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: Get string with backslashes in front of double quote '"' and backslash '\\'
+CMIUtilString CMIUtilString::Escape(bool vbEscapeQuotes /* = false */) const {
+ const size_t nLen(length());
+ CMIUtilString strNew;
+ strNew.reserve(nLen);
+ for (size_t nIndex(0); nIndex < nLen; ++nIndex) {
+ const char cUnescapedChar((*this)[nIndex]);
+ if (cUnescapedChar == '"' && vbEscapeQuotes)
+ strNew.append("\\\"");
+ else
+ strNew.append(ConvertToPrintableASCII((char)cUnescapedChar));
+ }
+ return strNew;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: Get string with backslashes in front of double quote '"' and
+// backslash '\\'
// characters.
// Type: Method.
// Args: None.
// Return: CMIUtilString - The wrapped version of the initial string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::AddSlashes() const
-{
- const char cBckSlash('\\');
- const size_t nLen(length());
- CMIUtilString strNew;
- strNew.reserve(nLen);
-
- size_t nOffset(0);
- while (nOffset < nLen)
- {
- const size_t nUnescapedCharPos(find_first_of("\"\\", nOffset));
- const bool bUnescapedCharNotFound(nUnescapedCharPos == std::string::npos);
- if (bUnescapedCharNotFound)
- {
- const size_t nAppendAll(std::string::npos);
- strNew.append(*this, nOffset, nAppendAll);
- break;
- }
- const size_t nAppendLen(nUnescapedCharPos - nOffset);
- strNew.append(*this, nOffset, nAppendLen);
- strNew.push_back(cBckSlash);
- const char cUnescapedChar((*this)[nUnescapedCharPos]);
- strNew.push_back(cUnescapedChar);
- nOffset = nUnescapedCharPos + 1;
- }
+CMIUtilString CMIUtilString::AddSlashes() const {
+ const char cBckSlash('\\');
+ const size_t nLen(length());
+ CMIUtilString strNew;
+ strNew.reserve(nLen);
+
+ size_t nOffset(0);
+ while (nOffset < nLen) {
+ const size_t nUnescapedCharPos(find_first_of("\"\\", nOffset));
+ const bool bUnescapedCharNotFound(nUnescapedCharPos == std::string::npos);
+ if (bUnescapedCharNotFound) {
+ const size_t nAppendAll(std::string::npos);
+ strNew.append(*this, nOffset, nAppendAll);
+ break;
+ }
+ const size_t nAppendLen(nUnescapedCharPos - nOffset);
+ strNew.append(*this, nOffset, nAppendLen);
+ strNew.push_back(cBckSlash);
+ const char cUnescapedChar((*this)[nUnescapedCharPos]);
+ strNew.push_back(cUnescapedChar);
+ nOffset = nUnescapedCharPos + 1;
+ }
- return strNew;
+ return strNew;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Remove backslashes added by CMIUtilString::AddSlashes.
// Type: Method.
// Args: None.
// Return: CMIUtilString - The initial version of wrapped string.
// Throws: None.
//--
-CMIUtilString
-CMIUtilString::StripSlashes() const
-{
- const char cBckSlash('\\');
- const size_t nLen(length());
- CMIUtilString strNew;
- strNew.reserve(nLen);
-
- size_t nOffset(0);
- while (nOffset < nLen)
- {
- const size_t nBckSlashPos(find(cBckSlash, nOffset));
- const bool bBckSlashNotFound(nBckSlashPos == std::string::npos);
- if (bBckSlashNotFound)
- {
- const size_t nAppendAll(std::string::npos);
- strNew.append(*this, nOffset, nAppendAll);
- break;
- }
- const size_t nAppendLen(nBckSlashPos - nOffset);
- strNew.append(*this, nOffset, nAppendLen);
- const bool bBckSlashIsLast(nBckSlashPos == nLen);
- if (bBckSlashIsLast)
- {
- strNew.push_back(cBckSlash);
- break;
- }
- const char cEscapedChar((*this)[nBckSlashPos + 1]);
- const size_t nEscapedCharPos(std::string("\"\\").find(cEscapedChar));
- const bool bEscapedCharNotFound(nEscapedCharPos == std::string::npos);
- if (bEscapedCharNotFound)
- strNew.push_back(cBckSlash);
- strNew.push_back(cEscapedChar);
- nOffset = nBckSlashPos + 2;
- }
-
- return strNew;
-}
-
-CMIUtilString
-CMIUtilString::ConvertToPrintableASCII(const char vChar, bool bEscapeQuotes)
-{
- switch (vChar)
- {
- case '\a':
- return "\\a";
- case '\b':
- return "\\b";
- case '\t':
- return "\\t";
- case '\n':
- return "\\n";
- case '\v':
- return "\\v";
- case '\f':
- return "\\f";
- case '\r':
- return "\\r";
- case '\033':
- return "\\e";
- case '\\':
- return "\\\\";
- case '"':
- if (bEscapeQuotes)
- return "\\\"";
- // fall thru
- default:
- if (::isprint(vChar))
- return Format("%c", vChar);
- else
- return Format("\\x%02" PRIx8, vChar);
- }
-}
-
-CMIUtilString
-CMIUtilString::ConvertCharValueToPrintableASCII(char vChar, bool bEscapeQuotes)
-{
- switch (vChar)
- {
- case '\a':
- return "\\a";
- case '\b':
- return "\\b";
- case '\t':
- return "\\t";
- case '\n':
- return "\\n";
- case '\v':
- return "\\v";
- case '\f':
- return "\\f";
- case '\r':
- return "\\r";
- case '\033':
- return "\\e";
- case '\\':
- return "\\\\";
- case '"':
- if (bEscapeQuotes)
- return "\\\"";
- // fall thru
- default:
- if (::isprint(vChar))
- return Format("%c", vChar);
- else
- return CMIUtilString();
- }
-}
-
-CMIUtilString
-CMIUtilString::ConvertToPrintableASCII(const char16_t vChar16, bool bEscapeQuotes)
-{
- if (vChar16 == (char16_t)(char)vChar16)
- {
- // Convert char16_t to char (if possible)
- CMIUtilString str = ConvertCharValueToPrintableASCII((char)vChar16, bEscapeQuotes);
- if (str.length() > 0)
- return str;
- }
- return Format("\\u%02" PRIx8 "%02" PRIx8,
- (vChar16 >> 8) & 0xff, vChar16 & 0xff);
-}
-
-CMIUtilString
-CMIUtilString::ConvertToPrintableASCII(const char32_t vChar32, bool bEscapeQuotes)
-{
- if (vChar32 == (char32_t)(char)vChar32)
- {
- // Convert char32_t to char (if possible)
- CMIUtilString str = ConvertCharValueToPrintableASCII((char)vChar32, bEscapeQuotes);
- if (str.length() > 0)
- return str;
- }
- return Format("\\U%02" PRIx8 "%02" PRIx8 "%02" PRIx8 "%02" PRIx8,
- (vChar32 >> 24) & 0xff, (vChar32 >> 16) & 0xff,
- (vChar32 >> 8) & 0xff, vChar32 & 0xff);
+CMIUtilString CMIUtilString::StripSlashes() const {
+ const char cBckSlash('\\');
+ const size_t nLen(length());
+ CMIUtilString strNew;
+ strNew.reserve(nLen);
+
+ size_t nOffset(0);
+ while (nOffset < nLen) {
+ const size_t nBckSlashPos(find(cBckSlash, nOffset));
+ const bool bBckSlashNotFound(nBckSlashPos == std::string::npos);
+ if (bBckSlashNotFound) {
+ const size_t nAppendAll(std::string::npos);
+ strNew.append(*this, nOffset, nAppendAll);
+ break;
+ }
+ const size_t nAppendLen(nBckSlashPos - nOffset);
+ strNew.append(*this, nOffset, nAppendLen);
+ const bool bBckSlashIsLast(nBckSlashPos == nLen);
+ if (bBckSlashIsLast) {
+ strNew.push_back(cBckSlash);
+ break;
+ }
+ const char cEscapedChar((*this)[nBckSlashPos + 1]);
+ const size_t nEscapedCharPos(std::string("\"\\").find(cEscapedChar));
+ const bool bEscapedCharNotFound(nEscapedCharPos == std::string::npos);
+ if (bEscapedCharNotFound)
+ strNew.push_back(cBckSlash);
+ strNew.push_back(cEscapedChar);
+ nOffset = nBckSlashPos + 2;
+ }
+
+ return strNew;
+}
+
+CMIUtilString CMIUtilString::ConvertToPrintableASCII(const char vChar,
+ bool bEscapeQuotes) {
+ switch (vChar) {
+ case '\a':
+ return "\\a";
+ case '\b':
+ return "\\b";
+ case '\t':
+ return "\\t";
+ case '\n':
+ return "\\n";
+ case '\v':
+ return "\\v";
+ case '\f':
+ return "\\f";
+ case '\r':
+ return "\\r";
+ case '\033':
+ return "\\e";
+ case '\\':
+ return "\\\\";
+ case '"':
+ if (bEscapeQuotes)
+ return "\\\"";
+ // fall thru
+ default:
+ if (::isprint(vChar))
+ return Format("%c", vChar);
+ else
+ return Format("\\x%02" PRIx8, vChar);
+ }
+}
+
+CMIUtilString
+CMIUtilString::ConvertCharValueToPrintableASCII(char vChar,
+ bool bEscapeQuotes) {
+ switch (vChar) {
+ case '\a':
+ return "\\a";
+ case '\b':
+ return "\\b";
+ case '\t':
+ return "\\t";
+ case '\n':
+ return "\\n";
+ case '\v':
+ return "\\v";
+ case '\f':
+ return "\\f";
+ case '\r':
+ return "\\r";
+ case '\033':
+ return "\\e";
+ case '\\':
+ return "\\\\";
+ case '"':
+ if (bEscapeQuotes)
+ return "\\\"";
+ // fall thru
+ default:
+ if (::isprint(vChar))
+ return Format("%c", vChar);
+ else
+ return CMIUtilString();
+ }
+}
+
+CMIUtilString CMIUtilString::ConvertToPrintableASCII(const char16_t vChar16,
+ bool bEscapeQuotes) {
+ if (vChar16 == (char16_t)(char)vChar16) {
+ // Convert char16_t to char (if possible)
+ CMIUtilString str =
+ ConvertCharValueToPrintableASCII((char)vChar16, bEscapeQuotes);
+ if (str.length() > 0)
+ return str;
+ }
+ return Format("\\u%02" PRIx8 "%02" PRIx8, (vChar16 >> 8) & 0xff,
+ vChar16 & 0xff);
+}
+
+CMIUtilString CMIUtilString::ConvertToPrintableASCII(const char32_t vChar32,
+ bool bEscapeQuotes) {
+ if (vChar32 == (char32_t)(char)vChar32) {
+ // Convert char32_t to char (if possible)
+ CMIUtilString str =
+ ConvertCharValueToPrintableASCII((char)vChar32, bEscapeQuotes);
+ if (str.length() > 0)
+ return str;
+ }
+ return Format("\\U%02" PRIx8 "%02" PRIx8 "%02" PRIx8 "%02" PRIx8,
+ (vChar32 >> 24) & 0xff, (vChar32 >> 16) & 0xff,
+ (vChar32 >> 8) & 0xff, vChar32 & 0xff);
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilString.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilString.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilString.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilString.h Tue Sep 6 15:57:50 2016
@@ -10,77 +10,84 @@
#pragma once
// Third party headers:
-#include <string>
-#include <vector>
#include <cinttypes>
#include <cstdarg>
+#include <string>
+#include <vector>
// In-house headers:
#include "MIDataTypes.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Used to help handle text.
// Derived from std::string
//--
-class CMIUtilString : public std::string
-{
- // Typedefs:
- public:
- typedef std::vector<CMIUtilString> VecString_t;
-
- // Static method:
- public:
- static CMIUtilString Format(const CMIUtilString vFormating, ...);
- static CMIUtilString FormatBinary(const MIuint64 vnDecimal);
- static CMIUtilString FormatValist(const CMIUtilString &vrFormating, va_list vArgs);
- static bool IsAllValidAlphaAndNumeric(const char *vpText);
- static bool Compare(const CMIUtilString &vrLhs, const CMIUtilString &vrRhs);
- static CMIUtilString ConvertToPrintableASCII(const char vChar, bool bEscapeQuotes = false);
- static CMIUtilString ConvertToPrintableASCII(const char16_t vChar16, bool bEscapeQuotes = false);
- static CMIUtilString ConvertToPrintableASCII(const char32_t vChar32, bool bEscapeQuotes = false);
-
- // Methods:
- public:
- /* ctor */ CMIUtilString();
- /* ctor */ CMIUtilString(const char *vpData);
- /* ctor */ CMIUtilString(const std::string& vrStr);
- //
- bool ExtractNumber(MIint64 &vwrNumber) const;
- CMIUtilString FindAndReplace(const CMIUtilString &vFind, const CMIUtilString &vReplaceWith) const;
- bool IsNumber() const;
- bool IsHexadecimalNumber() const;
- bool IsQuoted() const;
- CMIUtilString RemoveRepeatedCharacters(const char vChar);
- size_t Split(const CMIUtilString &vDelimiter, VecString_t &vwVecSplits) const;
- size_t SplitConsiderQuotes(const CMIUtilString &vDelimiter, VecString_t &vwVecSplits) const;
- size_t SplitLines(VecString_t &vwVecSplits) const;
- CMIUtilString StripCREndOfLine() const;
- CMIUtilString StripCRAll() const;
- CMIUtilString Trim() const;
- CMIUtilString Trim(const char vChar) const;
- size_t FindFirst(const CMIUtilString &vrPattern, size_t vnPos = 0) const;
- size_t FindFirst(const CMIUtilString &vrPattern, bool vbSkipQuotedText, bool &vrwbNotFoundClosedQuote,
- size_t vnPos = 0) const;
- size_t FindFirstNot(const CMIUtilString &vrPattern, size_t vnPos = 0) const;
- CMIUtilString Escape(bool vbEscapeQuotes = false) const;
- CMIUtilString AddSlashes() const;
- CMIUtilString StripSlashes() const;
- //
- CMIUtilString &operator=(const char *vpRhs);
- CMIUtilString &operator=(const std::string &vrRhs);
-
- // Overrideable:
- public:
- /* dtor */ virtual ~CMIUtilString();
-
- // Static method:
- private:
- static CMIUtilString FormatPriv(const CMIUtilString &vrFormat, va_list vArgs);
- static CMIUtilString ConvertCharValueToPrintableASCII(char vChar, bool bEscapeQuotes);
-
- // Methods:
- private:
- bool ExtractNumberFromHexadecimal(MIint64 &vwrNumber) const;
- CMIUtilString RemoveRepeatedCharacters(size_t vnPos, const char vChar);
- size_t FindFirstQuote(size_t vnPos) const;
+class CMIUtilString : public std::string {
+ // Typedefs:
+public:
+ typedef std::vector<CMIUtilString> VecString_t;
+
+ // Static method:
+public:
+ static CMIUtilString Format(const CMIUtilString vFormating, ...);
+ static CMIUtilString FormatBinary(const MIuint64 vnDecimal);
+ static CMIUtilString FormatValist(const CMIUtilString &vrFormating,
+ va_list vArgs);
+ static bool IsAllValidAlphaAndNumeric(const char *vpText);
+ static bool Compare(const CMIUtilString &vrLhs, const CMIUtilString &vrRhs);
+ static CMIUtilString ConvertToPrintableASCII(const char vChar,
+ bool bEscapeQuotes = false);
+ static CMIUtilString ConvertToPrintableASCII(const char16_t vChar16,
+ bool bEscapeQuotes = false);
+ static CMIUtilString ConvertToPrintableASCII(const char32_t vChar32,
+ bool bEscapeQuotes = false);
+
+ // Methods:
+public:
+ /* ctor */ CMIUtilString();
+ /* ctor */ CMIUtilString(const char *vpData);
+ /* ctor */ CMIUtilString(const std::string &vrStr);
+ //
+ bool ExtractNumber(MIint64 &vwrNumber) const;
+ CMIUtilString FindAndReplace(const CMIUtilString &vFind,
+ const CMIUtilString &vReplaceWith) const;
+ bool IsNumber() const;
+ bool IsHexadecimalNumber() const;
+ bool IsQuoted() const;
+ CMIUtilString RemoveRepeatedCharacters(const char vChar);
+ size_t Split(const CMIUtilString &vDelimiter, VecString_t &vwVecSplits) const;
+ size_t SplitConsiderQuotes(const CMIUtilString &vDelimiter,
+ VecString_t &vwVecSplits) const;
+ size_t SplitLines(VecString_t &vwVecSplits) const;
+ CMIUtilString StripCREndOfLine() const;
+ CMIUtilString StripCRAll() const;
+ CMIUtilString Trim() const;
+ CMIUtilString Trim(const char vChar) const;
+ size_t FindFirst(const CMIUtilString &vrPattern, size_t vnPos = 0) const;
+ size_t FindFirst(const CMIUtilString &vrPattern, bool vbSkipQuotedText,
+ bool &vrwbNotFoundClosedQuote, size_t vnPos = 0) const;
+ size_t FindFirstNot(const CMIUtilString &vrPattern, size_t vnPos = 0) const;
+ CMIUtilString Escape(bool vbEscapeQuotes = false) const;
+ CMIUtilString AddSlashes() const;
+ CMIUtilString StripSlashes() const;
+ //
+ CMIUtilString &operator=(const char *vpRhs);
+ CMIUtilString &operator=(const std::string &vrRhs);
+
+ // Overrideable:
+public:
+ /* dtor */ virtual ~CMIUtilString();
+
+ // Static method:
+private:
+ static CMIUtilString FormatPriv(const CMIUtilString &vrFormat, va_list vArgs);
+ static CMIUtilString ConvertCharValueToPrintableASCII(char vChar,
+ bool bEscapeQuotes);
+
+ // Methods:
+private:
+ bool ExtractNumberFromHexadecimal(MIint64 &vwrNumber) const;
+ CMIUtilString RemoveRepeatedCharacters(size_t vnPos, const char vChar);
+ size_t FindFirstQuote(size_t vnPos) const;
};
Modified: lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.cpp Tue Sep 6 15:57:50 2016
@@ -11,10 +11,11 @@
#include <assert.h>
// In-house headers:
-#include "MIUtilThreadBaseStd.h"
#include "MICmnThreadMgrStd.h"
+#include "MIUtilThreadBaseStd.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Constructor.
// Type: None.
// Args: None.
@@ -22,25 +23,23 @@
// Throws: None.
//--
CMIUtilThreadActiveObjBase::CMIUtilThreadActiveObjBase()
- : m_references(0)
- , m_bHasBeenKilled(false)
-{
-}
+ : m_references(0), m_bHasBeenKilled(false) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Destructor.
// Type: None.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilThreadActiveObjBase::~CMIUtilThreadActiveObjBase()
-{
- // Make sure our thread is not alive before we die
- m_thread.Join();
+CMIUtilThreadActiveObjBase::~CMIUtilThreadActiveObjBase() {
+ // Make sure our thread is not alive before we die
+ m_thread.Join();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Check if an object is already running.
// Type: Method.
// Args: None.
@@ -48,14 +47,13 @@ CMIUtilThreadActiveObjBase::~CMIUtilThre
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::ThreadIsActive()
-{
- // Create a new thread to occupy this threads Run() function
- return m_thread.IsActive();
+bool CMIUtilThreadActiveObjBase::ThreadIsActive() {
+ // Create a new thread to occupy this threads Run() function
+ return m_thread.IsActive();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Set up *this thread.
// Type: Method.
// Args: None.
@@ -63,14 +61,13 @@ CMIUtilThreadActiveObjBase::ThreadIsActi
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::ThreadExecute()
-{
- // Create a new thread to occupy this threads Run() function
- return m_thread.Start(ThreadEntry, this);
+bool CMIUtilThreadActiveObjBase::ThreadExecute() {
+ // Create a new thread to occupy this threads Run() function
+ return m_thread.Start(ThreadEntry, this);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Acquire a reference to CMIUtilThreadActiveObjBase.
// Type: Method.
// Args: None.
@@ -78,19 +75,18 @@ CMIUtilThreadActiveObjBase::ThreadExecut
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::Acquire()
-{
- // Access to this function is serial
- CMIUtilThreadLock serial(m_mutex);
+bool CMIUtilThreadActiveObjBase::Acquire() {
+ // Access to this function is serial
+ CMIUtilThreadLock serial(m_mutex);
- // >0 == *this thread is alive
- m_references++;
+ // >0 == *this thread is alive
+ m_references++;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release a reference to CMIUtilThreadActiveObjBase.
// Type: Method.
// Args: None.
@@ -98,19 +94,18 @@ CMIUtilThreadActiveObjBase::Acquire()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::Release()
-{
- // Access to this function is serial
- CMIUtilThreadLock serial(m_mutex);
+bool CMIUtilThreadActiveObjBase::Release() {
+ // Access to this function is serial
+ CMIUtilThreadLock serial(m_mutex);
- // 0 == kill off *this thread
- m_references--;
+ // 0 == kill off *this thread
+ m_references--;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Force this thread to stop, regardless of references
// Type: Method.
// Args: None.
@@ -118,19 +113,18 @@ CMIUtilThreadActiveObjBase::Release()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::ThreadKill()
-{
- // Access to this function is serial
- CMIUtilThreadLock serial(m_mutex);
+bool CMIUtilThreadActiveObjBase::ThreadKill() {
+ // Access to this function is serial
+ CMIUtilThreadLock serial(m_mutex);
- // Set this thread to killed status
- m_bHasBeenKilled = true;
+ // Set this thread to killed status
+ m_bHasBeenKilled = true;
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Proxy to thread join.
// Type: Method.
// Args: None.
@@ -138,73 +132,69 @@ CMIUtilThreadActiveObjBase::ThreadKill()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThreadActiveObjBase::ThreadJoin()
-{
- return m_thread.Join();
-}
+bool CMIUtilThreadActiveObjBase::ThreadJoin() { return m_thread.Join(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: This function is the entry point of this object thread.
// It is a trampoline to an instances operation manager.
// Type: Static method.
-// Args: vpThisClass - (R) From the system (our CMIUtilThreadActiveObjBase from the ctor).
+// Args: vpThisClass - (R) From the system (our CMIUtilThreadActiveObjBase
+// from the ctor).
// Return: MIuint - 0 = success.
// Throws: None.
//--
-MIuint
-CMIUtilThreadActiveObjBase::ThreadEntry(void *vpThisClass)
-{
- // The argument is a pointer to a CMIUtilThreadActiveObjBase class
- // as passed from the initialize function, so we can safely cast it.
- assert(vpThisClass != nullptr);
- CMIUtilThreadActiveObjBase *pActive = reinterpret_cast<CMIUtilThreadActiveObjBase *>(vpThisClass);
-
- // Start the management routine of this object
- pActive->ThreadManage();
-
- // Thread death
- return 0;
-}
-
-//++ ------------------------------------------------------------------------------------
-// Details: This function forms a small management routine, to handle the thread's running.
+MIuint CMIUtilThreadActiveObjBase::ThreadEntry(void *vpThisClass) {
+ // The argument is a pointer to a CMIUtilThreadActiveObjBase class
+ // as passed from the initialize function, so we can safely cast it.
+ assert(vpThisClass != nullptr);
+ CMIUtilThreadActiveObjBase *pActive =
+ reinterpret_cast<CMIUtilThreadActiveObjBase *>(vpThisClass);
+
+ // Start the management routine of this object
+ pActive->ThreadManage();
+
+ // Thread death
+ return 0;
+}
+
+//++
+//------------------------------------------------------------------------------------
+// Details: This function forms a small management routine, to handle the
+// thread's running.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilThreadActiveObjBase::ThreadManage()
-{
- bool bAlive = true;
+void CMIUtilThreadActiveObjBase::ThreadManage() {
+ bool bAlive = true;
- // Infinite loop
- while (bAlive)
+ // Infinite loop
+ while (bAlive) {
+ // Scope the lock while we access m_isDying
{
- // Scope the lock while we access m_isDying
- {
- // Lock down access to the interface
- CMIUtilThreadLock serial(m_mutex);
-
- // Quit the run loop if we are dying
- if (m_references == 0)
- break;
- }
- // Execute the run routine
- if (!ThreadRun(bAlive))
- // Thread's run function failed (MIstatus::failure)
- break;
+ // Lock down access to the interface
+ CMIUtilThreadLock serial(m_mutex);
- // We will die if we have been signaled to die
- bAlive &= !m_bHasBeenKilled;
+ // Quit the run loop if we are dying
+ if (m_references == 0)
+ break;
}
+ // Execute the run routine
+ if (!ThreadRun(bAlive))
+ // Thread's run function failed (MIstatus::failure)
+ break;
+
+ // We will die if we have been signaled to die
+ bAlive &= !m_bHasBeenKilled;
+ }
+
+ // Execute the finish routine just before we die
+ // to give the object a chance to clean up
+ ThreadFinish();
- // Execute the finish routine just before we die
- // to give the object a chance to clean up
- ThreadFinish();
-
- m_thread.Finish();
+ m_thread.Finish();
}
//---------------------------------------------------------------------------------------
@@ -212,25 +202,20 @@ CMIUtilThreadActiveObjBase::ThreadManage
//---------------------------------------------------------------------------------------
//
-CMIUtilThread::CMIUtilThread()
- : m_pThread(nullptr)
- , m_bIsActive(false)
-{
-}
+CMIUtilThread::CMIUtilThread() : m_pThread(nullptr), m_bIsActive(false) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilThread destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilThread::~CMIUtilThread()
-{
- Join();
-}
+CMIUtilThread::~CMIUtilThread() { Join(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Wait for thread to stop.
// Type: Method.
// Args: None.
@@ -238,56 +223,52 @@ CMIUtilThread::~CMIUtilThread()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThread::Join()
-{
- if (m_pThread != nullptr)
- {
- // Wait for this thread to die
- m_pThread->join();
+bool CMIUtilThread::Join() {
+ if (m_pThread != nullptr) {
+ // Wait for this thread to die
+ m_pThread->join();
- // Scope the thread lock while we modify the pointer
- {
- CMIUtilThreadLock _lock(m_mutex);
- delete m_pThread;
- m_pThread = nullptr;
- }
+ // Scope the thread lock while we modify the pointer
+ {
+ CMIUtilThreadLock _lock(m_mutex);
+ delete m_pThread;
+ m_pThread = nullptr;
}
+ }
- return MIstatus::success;
+ return MIstatus::success;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Is the thread doing work.
// Type: Method.
// Args: None.
// Return: bool - True = Yes active, false = not active.
// Throws: None.
//--
-bool
-CMIUtilThread::IsActive()
-{
- // Lock while we access the thread status
- CMIUtilThreadLock _lock(m_mutex);
- return m_bIsActive;
+bool CMIUtilThread::IsActive() {
+ // Lock while we access the thread status
+ CMIUtilThreadLock _lock(m_mutex);
+ return m_bIsActive;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Finish this thread
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilThread::Finish()
-{
- // Lock while we access the thread status
- CMIUtilThreadLock _lock(m_mutex);
- m_bIsActive = false;
+void CMIUtilThread::Finish() {
+ // Lock while we access the thread status
+ CMIUtilThreadLock _lock(m_mutex);
+ m_bIsActive = false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Set up *this thread.
// Type: Method.
// Args: vpFn (R) - Function pointer to thread's main function.
@@ -296,53 +277,46 @@ CMIUtilThread::Finish()
// MIstatus::failure - Functional failed.
// Throws: None.
//--
-bool
-CMIUtilThread::Start(FnThreadProc vpFn, void *vpArg)
-{
- // Lock while we access the thread pointer and status
- CMIUtilThreadLock _lock(m_mutex);
-
- // Create the std thread, which starts immediately and update its status
- m_pThread = new std::thread(vpFn, vpArg);
- m_bIsActive = true;
+bool CMIUtilThread::Start(FnThreadProc vpFn, void *vpArg) {
+ // Lock while we access the thread pointer and status
+ CMIUtilThreadLock _lock(m_mutex);
+
+ // Create the std thread, which starts immediately and update its status
+ m_pThread = new std::thread(vpFn, vpArg);
+ m_bIsActive = true;
- // We expect to always be able to create one
- assert(m_pThread != nullptr);
+ // We expect to always be able to create one
+ assert(m_pThread != nullptr);
- return MIstatus::success;
+ return MIstatus::success;
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Take resource.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilThreadMutex::Lock()
-{
- m_mutex.lock();
-}
+void CMIUtilThreadMutex::Lock() { m_mutex.lock(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release resource.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilThreadMutex::Unlock()
-{
- m_mutex.unlock();
-}
+void CMIUtilThreadMutex::Unlock() { m_mutex.unlock(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Take resource if available. Immediately return in either case.
// Type: Method.
// Args: None.
@@ -350,8 +324,4 @@ CMIUtilThreadMutex::Unlock()
// False - mutex could not be locked.
// Throws: None.
//--
-bool
-CMIUtilThreadMutex::TryLock()
-{
- return m_mutex.try_lock();
-}
+bool CMIUtilThreadMutex::TryLock() { return m_mutex.try_lock(); }
Modified: lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilThreadBaseStd.h Tue Sep 6 15:57:50 2016
@@ -13,147 +13,132 @@
#ifdef _MSC_VER
#include <eh.h>
#endif // _MSC_VER
-#include <thread>
#include <mutex>
+#include <thread>
// In-house headers:
#include "MIDataTypes.h"
#include "MIUtilString.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Handle thread mutual exclusion.
// Embed Mutexes in your Active Object and then use them through Locks.
//--
-class CMIUtilThreadMutex
-{
- // Methods:
- public:
- /* ctor */ CMIUtilThreadMutex(){}
- //
- void
- Lock(); // Wait until mutex can be obtained
- void
- Unlock(); // Release the mutex
- bool
- TryLock(); // Gain the lock if available
-
- // Overrideable:
- public:
- // From CMICmnBase
- /* dtor */ virtual ~CMIUtilThreadMutex(){}
-
- // Attributes:
- private:
- std::recursive_mutex m_mutex;
+class CMIUtilThreadMutex {
+ // Methods:
+public:
+ /* ctor */ CMIUtilThreadMutex() {}
+ //
+ void Lock(); // Wait until mutex can be obtained
+ void Unlock(); // Release the mutex
+ bool TryLock(); // Gain the lock if available
+
+ // Overrideable:
+public:
+ // From CMICmnBase
+ /* dtor */ virtual ~CMIUtilThreadMutex() {}
+
+ // Attributes:
+private:
+ std::recursive_mutex m_mutex;
};
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Thread object.
//--
-class CMIUtilThread
-{
- // Typedef:
- public:
- typedef MIuint (*FnThreadProc)(void *vpThisClass);
-
- // Methods:
- public:
- /* ctor */ CMIUtilThread();
- //
- bool
- Start(FnThreadProc vpFn, void *vpArg); // Start execution of this thread
- bool
- Join(); // Wait for this thread to stop
- bool
- IsActive(); // Returns true if this thread is running
- void
- Finish(); // Finish this thread
-
- // Overrideable:
- public:
- /* dtor */ virtual ~CMIUtilThread();
-
- // Methods:
- private:
- CMIUtilThreadMutex m_mutex;
- std::thread *m_pThread;
- bool m_bIsActive;
+class CMIUtilThread {
+ // Typedef:
+public:
+ typedef MIuint (*FnThreadProc)(void *vpThisClass);
+
+ // Methods:
+public:
+ /* ctor */ CMIUtilThread();
+ //
+ bool Start(FnThreadProc vpFn, void *vpArg); // Start execution of this thread
+ bool Join(); // Wait for this thread to stop
+ bool IsActive(); // Returns true if this thread is running
+ void Finish(); // Finish this thread
+
+ // Overrideable:
+public:
+ /* dtor */ virtual ~CMIUtilThread();
+
+ // Methods:
+private:
+ CMIUtilThreadMutex m_mutex;
+ std::thread *m_pThread;
+ bool m_bIsActive;
};
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Base class for a worker thread active
// object. Runs an 'captive thread'.
//--
-class CMIUtilThreadActiveObjBase
-{
- // Methods:
- public:
- /* ctor */ CMIUtilThreadActiveObjBase();
- //
- bool
- Acquire(); // Obtain a reference to this object
- bool
- Release(); // Release a reference to this object
- bool
- ThreadIsActive(); // Return true if this object is running
- bool
- ThreadJoin(); // Wait for this thread to stop running
- bool
- ThreadKill(); // Force this thread to stop, regardless of references
- bool
- ThreadExecute(); // Start this objects execution in another thread
- void ThreadManage();
-
- // Overrideable:
- public:
- /* dtor */ virtual ~CMIUtilThreadActiveObjBase();
- //
- // Each thread object must supple a unique name that can be used to locate it
- virtual const CMIUtilString &ThreadGetName() const = 0;
-
- // Statics:
- protected:
- static MIuint
- ThreadEntry(void *vpThisClass); // Thread entry point
-
- // Overrideable:
- protected:
- virtual bool
- ThreadRun(bool &vrIsAlive) = 0; // Call the main worker method
- virtual bool
- ThreadFinish() = 0; // Finish of what you were doing
-
- // Attributes:
- protected:
- volatile MIuint m_references; // Stores the current lifetime state of this thread, 0 = running, > 0 = shutting down
- volatile bool m_bHasBeenKilled; // Set to true when this thread has been killed
- CMIUtilThread m_thread; // The execution thread
- CMIUtilThreadMutex
- m_mutex; // This mutex allows us to safely communicate with this thread object across the interface from multiple threads
+class CMIUtilThreadActiveObjBase {
+ // Methods:
+public:
+ /* ctor */ CMIUtilThreadActiveObjBase();
+ //
+ bool Acquire(); // Obtain a reference to this object
+ bool Release(); // Release a reference to this object
+ bool ThreadIsActive(); // Return true if this object is running
+ bool ThreadJoin(); // Wait for this thread to stop running
+ bool ThreadKill(); // Force this thread to stop, regardless of references
+ bool ThreadExecute(); // Start this objects execution in another thread
+ void ThreadManage();
+
+ // Overrideable:
+public:
+ /* dtor */ virtual ~CMIUtilThreadActiveObjBase();
+ //
+ // Each thread object must supple a unique name that can be used to locate it
+ virtual const CMIUtilString &ThreadGetName() const = 0;
+
+ // Statics:
+protected:
+ static MIuint ThreadEntry(void *vpThisClass); // Thread entry point
+
+ // Overrideable:
+protected:
+ virtual bool ThreadRun(bool &vrIsAlive) = 0; // Call the main worker method
+ virtual bool ThreadFinish() = 0; // Finish of what you were doing
+
+ // Attributes:
+protected:
+ volatile MIuint m_references; // Stores the current lifetime state of this
+ // thread, 0 = running, > 0 = shutting down
+ volatile bool
+ m_bHasBeenKilled; // Set to true when this thread has been killed
+ CMIUtilThread m_thread; // The execution thread
+ CMIUtilThreadMutex m_mutex; // This mutex allows us to safely communicate with
+ // this thread object across the interface from
+ // multiple threads
};
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. Handle thread resource locking.
// Put Locks inside all the methods of your Active Object that access
// data shared with the captive thread.
//--
-class CMIUtilThreadLock
-{
- // Methods:
- public:
- /* ctor */
- CMIUtilThreadLock(CMIUtilThreadMutex &vMutex)
- : m_rMutex(vMutex)
- {
- m_rMutex.Lock();
- }
-
- // Overrideable:
- public:
- /* dtor */
- virtual ~CMIUtilThreadLock() { m_rMutex.Unlock(); }
-
- // Attributes:
- private:
- CMIUtilThreadMutex &m_rMutex;
+class CMIUtilThreadLock {
+ // Methods:
+public:
+ /* ctor */
+ CMIUtilThreadLock(CMIUtilThreadMutex &vMutex) : m_rMutex(vMutex) {
+ m_rMutex.Lock();
+ }
+
+ // Overrideable:
+public:
+ /* dtor */
+ virtual ~CMIUtilThreadLock() { m_rMutex.Unlock(); }
+
+ // Attributes:
+private:
+ CMIUtilThreadMutex &m_rMutex;
};
Modified: lldb/trunk/tools/lldb-mi/MIUtilVariant.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilVariant.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilVariant.cpp (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilVariant.cpp Tue Sep 6 15:57:50 2016
@@ -10,93 +10,94 @@
// In-house headers:
#include "MIUtilVariant.h"
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase::CDataObjectBase()
-{
-}
+CMIUtilVariant::CDataObjectBase::CDataObjectBase() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase copy constructor.
// Type: Method.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase::CDataObjectBase(const CDataObjectBase &vrOther)
-{
- MIunused(vrOther);
+CMIUtilVariant::CDataObjectBase::CDataObjectBase(
+ const CDataObjectBase &vrOther) {
+ MIunused(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase copy constructor.
// Type: Method.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase::CDataObjectBase(CDataObjectBase &vrOther)
-{
- MIunused(vrOther);
+CMIUtilVariant::CDataObjectBase::CDataObjectBase(CDataObjectBase &vrOther) {
+ MIunused(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase move constructor.
// Type: Method.
// Args: vrwOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase::CDataObjectBase(CDataObjectBase &&vrwOther)
-{
- MIunused(vrwOther);
+CMIUtilVariant::CDataObjectBase::CDataObjectBase(CDataObjectBase &&vrwOther) {
+ MIunused(vrwOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase destructor.
// Type: Overrideable.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase::~CDataObjectBase()
-{
- Destroy();
-}
+CMIUtilVariant::CDataObjectBase::~CDataObjectBase() { Destroy(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase copy assignment.
// Type: Method.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase &CMIUtilVariant::CDataObjectBase::operator=(const CDataObjectBase &vrOther)
-{
- Copy(vrOther);
- return *this;
+CMIUtilVariant::CDataObjectBase &CMIUtilVariant::CDataObjectBase::
+operator=(const CDataObjectBase &vrOther) {
+ Copy(vrOther);
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObjectBase move assignment.
// Type: Method.
// Args: vrwOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CDataObjectBase &CMIUtilVariant::CDataObjectBase::operator=(CDataObjectBase &&vrwOther)
-{
- Copy(vrwOther);
- vrwOther.Destroy();
- return *this;
+CMIUtilVariant::CDataObjectBase &CMIUtilVariant::CDataObjectBase::
+operator=(CDataObjectBase &&vrwOther) {
+ Copy(vrwOther);
+ vrwOther.Destroy();
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Create a new copy of *this class.
// Type: Overrideable.
// Args: None.
@@ -104,58 +105,56 @@ CMIUtilVariant::CDataObjectBase &CMIUtil
// Throws: None.
//--
CMIUtilVariant::CDataObjectBase *
-CMIUtilVariant::CDataObjectBase::CreateCopyOfSelf()
-{
- // Override to implement copying of variant's data object
- return new CDataObjectBase();
+CMIUtilVariant::CDataObjectBase::CreateCopyOfSelf() {
+ // Override to implement copying of variant's data object
+ return new CDataObjectBase();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Determine if *this object is a derived from CDataObjectBase.
// Type: Overrideable.
// Args: None.
-// Return: bool - True = *this is derived from CDataObjectBase, false = *this is instance of the this base class.
+// Return: bool - True = *this is derived from CDataObjectBase, false =
+// *this is instance of the this base class.
// Throws: None.
//--
-bool
-CMIUtilVariant::CDataObjectBase::GetIsDerivedClass() const
-{
- // Override to in the derived class and return true
- return false;
+bool CMIUtilVariant::CDataObjectBase::GetIsDerivedClass() const {
+ // Override to in the derived class and return true
+ return false;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Perform a bitwise copy of *this object.
// Type: Overrideable.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilVariant::CDataObjectBase::Copy(const CDataObjectBase &vrOther)
-{
- // Override to implement
- MIunused(vrOther);
+void CMIUtilVariant::CDataObjectBase::Copy(const CDataObjectBase &vrOther) {
+ // Override to implement
+ MIunused(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release any resources used by *this object.
// Type: Overrideable.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilVariant::CDataObjectBase::Destroy()
-{
- // Do nothing - override to implement
+void CMIUtilVariant::CDataObjectBase::Destroy() {
+ // Do nothing - override to implement
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject copy constructor.
// Type: Method.
// Args: T - The object's type.
@@ -163,14 +162,15 @@ CMIUtilVariant::CDataObjectBase::Destroy
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject(const CDataObject &vrOther)
-{
- if (this == &vrOther)
- return;
- Copy(vrOther);
+template <typename T>
+CMIUtilVariant::CDataObject<T>::CDataObject(const CDataObject &vrOther) {
+ if (this == &vrOther)
+ return;
+ Copy(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject copy constructor.
// Type: Method.
// Args: T - The object's type.
@@ -178,14 +178,15 @@ template <typename T> CMIUtilVariant::CD
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject(CDataObject &vrOther)
-{
- if (this == &vrOther)
- return;
- Copy(vrOther);
+template <typename T>
+CMIUtilVariant::CDataObject<T>::CDataObject(CDataObject &vrOther) {
+ if (this == &vrOther)
+ return;
+ Copy(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject move constructor.
// Type: Method.
// Args: T - The object's type.
@@ -193,15 +194,16 @@ template <typename T> CMIUtilVariant::CD
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject(CDataObject &&vrwOther)
-{
- if (this == &vrwOther)
- return;
- Copy(vrwOther);
- vrwOther.Destroy();
+template <typename T>
+CMIUtilVariant::CDataObject<T>::CDataObject(CDataObject &&vrwOther) {
+ if (this == &vrwOther)
+ return;
+ Copy(vrwOther);
+ vrwOther.Destroy();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject copy assignment.
// Type: Method.
// Args: T - The object's type.
@@ -209,15 +211,17 @@ template <typename T> CMIUtilVariant::CD
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T> &CMIUtilVariant::CDataObject<T>::operator=(const CDataObject &vrOther)
-{
- if (this == &vrOther)
- return *this;
- Copy(vrOther);
+template <typename T>
+CMIUtilVariant::CDataObject<T> &CMIUtilVariant::CDataObject<T>::
+operator=(const CDataObject &vrOther) {
+ if (this == &vrOther)
return *this;
+ Copy(vrOther);
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject move assignment.
// Type: Method.
// Args: T - The object's type.
@@ -225,32 +229,32 @@ template <typename T> CMIUtilVariant::CD
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T> &CMIUtilVariant::CDataObject<T>::operator=(CDataObject &&vrwOther)
-{
- if (this == &vrwOther)
- return *this;
- Copy(vrwOther);
- vrwOther.Destroy();
+template <typename T>
+CMIUtilVariant::CDataObject<T> &CMIUtilVariant::CDataObject<T>::
+operator=(CDataObject &&vrwOther) {
+ if (this == &vrwOther)
return *this;
+ Copy(vrwOther);
+ vrwOther.Destroy();
+ return *this;
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant constructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::CMIUtilVariant()
- : m_pDataObject(nullptr)
-{
-}
+CMIUtilVariant::CMIUtilVariant() : m_pDataObject(nullptr) {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant copy constructor.
// Type: Method.
// Args: vrOther - (R) The other object.
@@ -258,15 +262,15 @@ CMIUtilVariant::CMIUtilVariant()
// Throws: None.
//--
CMIUtilVariant::CMIUtilVariant(const CMIUtilVariant &vrOther)
- : m_pDataObject(nullptr)
-{
- if (this == &vrOther)
- return;
+ : m_pDataObject(nullptr) {
+ if (this == &vrOther)
+ return;
- Copy(vrOther);
+ Copy(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant copy constructor.
// Type: Method.
// Args: vrOther - (R) The other object.
@@ -274,15 +278,15 @@ CMIUtilVariant::CMIUtilVariant(const CMI
// Throws: None.
//--
CMIUtilVariant::CMIUtilVariant(CMIUtilVariant &vrOther)
- : m_pDataObject(nullptr)
-{
- if (this == &vrOther)
- return;
+ : m_pDataObject(nullptr) {
+ if (this == &vrOther)
+ return;
- Copy(vrOther);
+ Copy(vrOther);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant move constructor.
// Type: Method.
// Args: vrwOther - (R) The other object.
@@ -290,89 +294,83 @@ CMIUtilVariant::CMIUtilVariant(CMIUtilVa
// Throws: None.
//--
CMIUtilVariant::CMIUtilVariant(CMIUtilVariant &&vrwOther)
- : m_pDataObject(nullptr)
-{
- if (this == &vrwOther)
- return;
+ : m_pDataObject(nullptr) {
+ if (this == &vrwOther)
+ return;
- Copy(vrwOther);
- vrwOther.Destroy();
+ Copy(vrwOther);
+ vrwOther.Destroy();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant destructor.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant::~CMIUtilVariant()
-{
- Destroy();
-}
+CMIUtilVariant::~CMIUtilVariant() { Destroy(); }
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant copy assignment.
// Type: Method.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant &CMIUtilVariant::operator=(const CMIUtilVariant &vrOther)
-{
- if (this == &vrOther)
- return *this;
-
- Copy(vrOther);
+CMIUtilVariant &CMIUtilVariant::operator=(const CMIUtilVariant &vrOther) {
+ if (this == &vrOther)
return *this;
+
+ Copy(vrOther);
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CMIUtilVariant move assignment.
// Type: Method.
// Args: vrwOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-CMIUtilVariant &CMIUtilVariant::operator=(CMIUtilVariant &&vrwOther)
-{
- if (this == &vrwOther)
- return *this;
-
- Copy(vrwOther);
- vrwOther.Destroy();
+CMIUtilVariant &CMIUtilVariant::operator=(CMIUtilVariant &&vrwOther) {
+ if (this == &vrwOther)
return *this;
+
+ Copy(vrwOther);
+ vrwOther.Destroy();
+ return *this;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release the resources used by *this object.
// Type: Method.
// Args: None.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilVariant::Destroy()
-{
- if (m_pDataObject != nullptr)
- delete m_pDataObject;
- m_pDataObject = nullptr;
+void CMIUtilVariant::Destroy() {
+ if (m_pDataObject != nullptr)
+ delete m_pDataObject;
+ m_pDataObject = nullptr;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Bitwise copy another data object to *this variant object.
// Type: Method.
// Args: vrOther - (R) The other object.
// Return: None.
// Throws: None.
//--
-void
-CMIUtilVariant::Copy(const CMIUtilVariant &vrOther)
-{
- Destroy();
-
- if (vrOther.m_pDataObject != nullptr)
- {
- m_pDataObject = vrOther.m_pDataObject->CreateCopyOfSelf();
- }
+void CMIUtilVariant::Copy(const CMIUtilVariant &vrOther) {
+ Destroy();
+
+ if (vrOther.m_pDataObject != nullptr) {
+ m_pDataObject = vrOther.m_pDataObject->CreateCopyOfSelf();
+ }
}
Modified: lldb/trunk/tools/lldb-mi/MIUtilVariant.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/MIUtilVariant.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/MIUtilVariant.h (original)
+++ lldb/trunk/tools/lldb-mi/MIUtilVariant.h Tue Sep 6 15:57:50 2016
@@ -12,128 +12,127 @@
// In-house headers:
#include "MIDataTypes.h"
-//++ ============================================================================
+//++
+//============================================================================
// Details: MI common code utility class. The class implements behaviour of a
// variant object which holds any data object of type T. A copy of the
// data object specified is made and stored in *this wrapper. When the
// *this object is destroyed the data object hold within calls its
// destructor should it have one.
//--
-class CMIUtilVariant
-{
+class CMIUtilVariant {
+ // Methods:
+public:
+ /* ctor */ CMIUtilVariant();
+ /* ctor */ CMIUtilVariant(const CMIUtilVariant &vrOther);
+ /* ctor */ CMIUtilVariant(CMIUtilVariant &vrOther);
+ /* ctor */ CMIUtilVariant(CMIUtilVariant &&vrwOther);
+ /* dtor */ ~CMIUtilVariant();
+
+ template <typename T> void Set(const T &vArg);
+ template <typename T> T *Get() const;
+
+ CMIUtilVariant &operator=(const CMIUtilVariant &vrOther);
+ CMIUtilVariant &operator=(CMIUtilVariant &&vrwOther);
+
+ // Classes:
+private:
+ //++ ----------------------------------------------------------------------
+ // Details: Base class wrapper to hold the variant's data object when
+ // assigned to it by the Set() function. Do not use the
+ // CDataObjectBase
+ // to create objects, use only CDataObjectBase derived objects,
+ // see CDataObject() class.
+ //--
+ class CDataObjectBase {
// Methods:
public:
- /* ctor */ CMIUtilVariant();
- /* ctor */ CMIUtilVariant(const CMIUtilVariant &vrOther);
- /* ctor */ CMIUtilVariant(CMIUtilVariant &vrOther);
- /* ctor */ CMIUtilVariant(CMIUtilVariant &&vrwOther);
- /* dtor */ ~CMIUtilVariant();
+ /* ctor */ CDataObjectBase();
+ /* ctor */ CDataObjectBase(const CDataObjectBase &vrOther);
+ /* ctor */ CDataObjectBase(CDataObjectBase &vrOther);
+ /* ctor */ CDataObjectBase(CDataObjectBase &&vrwOther);
+ //
+ CDataObjectBase &operator=(const CDataObjectBase &vrOther);
+ CDataObjectBase &operator=(CDataObjectBase &&vrwOther);
- template <typename T> void Set(const T &vArg);
- template <typename T> T *Get() const;
+ // Overrideable:
+ public:
+ virtual ~CDataObjectBase();
+ virtual CDataObjectBase *CreateCopyOfSelf();
+ virtual bool GetIsDerivedClass() const;
+
+ // Overrideable:
+ protected:
+ virtual void Copy(const CDataObjectBase &vrOther);
+ virtual void Destroy();
+ };
+
+ //++ ----------------------------------------------------------------------
+ // Details: Derived from CDataObjectBase, this class is the wrapper for the
+ // data object as it has an aggregate of type T which is a copy
+ // of the data object assigned to the variant object.
+ //--
+ template <typename T> class CDataObject : public CDataObjectBase {
+ // Methods:
+ public:
+ /* ctor */ CDataObject();
+ /* ctor */ CDataObject(const T &vArg);
+ /* ctor */ CDataObject(const CDataObject &vrOther);
+ /* ctor */ CDataObject(CDataObject &vrOther);
+ /* ctor */ CDataObject(CDataObject &&vrwOther);
+ //
+ CDataObject &operator=(const CDataObject &vrOther);
+ CDataObject &operator=(CDataObject &&vrwOther);
+ //
+ T &GetDataObject();
- CMIUtilVariant &operator=(const CMIUtilVariant &vrOther);
- CMIUtilVariant &operator=(CMIUtilVariant &&vrwOther);
+ // Overridden:
+ public:
+ // From CDataObjectBase
+ ~CDataObject() override;
+ CDataObjectBase *CreateCopyOfSelf() override;
+ bool GetIsDerivedClass() const override;
- // Classes:
+ // Overrideable:
private:
- //++ ----------------------------------------------------------------------
- // Details: Base class wrapper to hold the variant's data object when
- // assigned to it by the Set() function. Do not use the CDataObjectBase
- // to create objects, use only CDataObjectBase derived objects,
- // see CDataObject() class.
- //--
- class CDataObjectBase
- {
- // Methods:
- public:
- /* ctor */ CDataObjectBase();
- /* ctor */ CDataObjectBase(const CDataObjectBase &vrOther);
- /* ctor */ CDataObjectBase(CDataObjectBase &vrOther);
- /* ctor */ CDataObjectBase(CDataObjectBase &&vrwOther);
- //
- CDataObjectBase &operator=(const CDataObjectBase &vrOther);
- CDataObjectBase &operator=(CDataObjectBase &&vrwOther);
-
- // Overrideable:
- public:
- virtual ~CDataObjectBase();
- virtual CDataObjectBase *CreateCopyOfSelf();
- virtual bool GetIsDerivedClass() const;
-
- // Overrideable:
- protected:
- virtual void Copy(const CDataObjectBase &vrOther);
- virtual void Destroy();
- };
-
- //++ ----------------------------------------------------------------------
- // Details: Derived from CDataObjectBase, this class is the wrapper for the
- // data object as it has an aggregate of type T which is a copy
- // of the data object assigned to the variant object.
- //--
- template <typename T> class CDataObject : public CDataObjectBase
- {
- // Methods:
- public:
- /* ctor */ CDataObject();
- /* ctor */ CDataObject(const T &vArg);
- /* ctor */ CDataObject(const CDataObject &vrOther);
- /* ctor */ CDataObject(CDataObject &vrOther);
- /* ctor */ CDataObject(CDataObject &&vrwOther);
- //
- CDataObject &operator=(const CDataObject &vrOther);
- CDataObject &operator=(CDataObject &&vrwOther);
- //
- T &GetDataObject();
-
- // Overridden:
- public:
- // From CDataObjectBase
- ~CDataObject() override;
- CDataObjectBase *CreateCopyOfSelf() override;
- bool GetIsDerivedClass() const override;
-
- // Overrideable:
- private:
- virtual void Duplicate(const CDataObject &vrOther);
-
- // Overridden:
- private:
- // From CDataObjectBase
- void Destroy() override;
-
- // Attributes:
- private:
- T m_dataObj;
- };
+ virtual void Duplicate(const CDataObject &vrOther);
- // Methods
+ // Overridden:
private:
- void Destroy();
- void Copy(const CMIUtilVariant &vrOther);
+ // From CDataObjectBase
+ void Destroy() override;
// Attributes:
private:
- CDataObjectBase *m_pDataObject;
+ T m_dataObj;
+ };
+
+ // Methods
+private:
+ void Destroy();
+ void Copy(const CMIUtilVariant &vrOther);
+
+ // Attributes:
+private:
+ CDataObjectBase *m_pDataObject;
};
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject constructor.
// Type: Method.
// Args: T - The object's type.
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject()
-{
-}
+template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject() {}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject constructor.
// Type: Method.
// Args: T - The object's type.
@@ -141,38 +140,37 @@ template <typename T> CMIUtilVariant::CD
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::CDataObject(const T &vArg)
-{
- m_dataObj = vArg;
+template <typename T>
+CMIUtilVariant::CDataObject<T>::CDataObject(const T &vArg) {
+ m_dataObj = vArg;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: CDataObject destructor.
// Type: Overridden.
// Args: T - The object's type.
// Return: None.
// Throws: None.
//--
-template <typename T> CMIUtilVariant::CDataObject<T>::~CDataObject()
-{
- Destroy();
+template <typename T> CMIUtilVariant::CDataObject<T>::~CDataObject() {
+ Destroy();
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the data object hold by *this object wrapper.
// Type: Method.
// Args: T - The object's type.
// Return: T & - Reference to the data object.
// Throws: None.
//--
-template <typename T>
-T &
-CMIUtilVariant::CDataObject<T>::GetDataObject()
-{
- return m_dataObj;
+template <typename T> T &CMIUtilVariant::CDataObject<T>::GetDataObject() {
+ return m_dataObj;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Create a new copy of *this class.
// Type: Overridden.
// Args: T - The object's type.
@@ -181,14 +179,14 @@ CMIUtilVariant::CDataObject<T>::GetDataO
//--
template <typename T>
CMIUtilVariant::CDataObjectBase *
-CMIUtilVariant::CDataObject<T>::CreateCopyOfSelf()
-{
- CDataObject *pCopy = new CDataObject<T>(m_dataObj);
+CMIUtilVariant::CDataObject<T>::CreateCopyOfSelf() {
+ CDataObject *pCopy = new CDataObject<T>(m_dataObj);
- return pCopy;
+ return pCopy;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Determine if *this object is a derived from CDataObjectBase.
// Type: Overridden.
// Args: T - The object's type.
@@ -197,13 +195,12 @@ CMIUtilVariant::CDataObject<T>::CreateCo
// Throws: None.
//--
template <typename T>
-bool
-CMIUtilVariant::CDataObject<T>::GetIsDerivedClass() const
-{
- return true;
+bool CMIUtilVariant::CDataObject<T>::GetIsDerivedClass() const {
+ return true;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Perform a bitwise copy of *this object.
// Type: Overrideable.
// Args: T - The object's type.
@@ -212,32 +209,29 @@ CMIUtilVariant::CDataObject<T>::GetIsDer
// Throws: None.
//--
template <typename T>
-void
-CMIUtilVariant::CDataObject<T>::Duplicate(const CDataObject &vrOther)
-{
- CDataObjectBase::Copy(vrOther);
- m_dataObj = vrOther.m_dataObj;
+void CMIUtilVariant::CDataObject<T>::Duplicate(const CDataObject &vrOther) {
+ CDataObjectBase::Copy(vrOther);
+ m_dataObj = vrOther.m_dataObj;
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Release any resources used by *this object.
// Type: Overridden.
// Args: None.
// Return: None.
// Throws: None.
//--
-template <typename T>
-void
-CMIUtilVariant::CDataObject<T>::Destroy()
-{
- CDataObjectBase::Destroy();
+template <typename T> void CMIUtilVariant::CDataObject<T>::Destroy() {
+ CDataObjectBase::Destroy();
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Assign to the variant an object of a specified type.
// Type: Template method.
// Args: T - The object's type.
@@ -245,30 +239,26 @@ CMIUtilVariant::CDataObject<T>::Destroy(
// Return: None.
// Throws: None.
//--
-template <typename T>
-void
-CMIUtilVariant::Set(const T &vArg)
-{
- m_pDataObject = new CDataObject<T>(vArg);
+template <typename T> void CMIUtilVariant::Set(const T &vArg) {
+ m_pDataObject = new CDataObject<T>(vArg);
}
-//++ ------------------------------------------------------------------------------------
+//++
+//------------------------------------------------------------------------------------
// Details: Retrieve the data object from *this variant.
// Type: Template method.
// Args: T - The object's type.
-// Return: T * - Pointer the data object, NULL = data object not assigned to *this variant.
+// Return: T * - Pointer the data object, NULL = data object not assigned to
+// *this variant.
// Throws: None.
//--
-template <typename T>
-T *
-CMIUtilVariant::Get() const
-{
- if ((m_pDataObject != nullptr) && m_pDataObject->GetIsDerivedClass())
- {
- CDataObject<T> *pDataObj = static_cast<CDataObject<T> *>(m_pDataObject);
- return &pDataObj->GetDataObject();
- }
-
- // Do not use a CDataObjectBase object, use only CDataObjectBase derived objects
- return nullptr;
+template <typename T> T *CMIUtilVariant::Get() const {
+ if ((m_pDataObject != nullptr) && m_pDataObject->GetIsDerivedClass()) {
+ CDataObject<T> *pDataObj = static_cast<CDataObject<T> *>(m_pDataObject);
+ return &pDataObj->GetDataObject();
+ }
+
+ // Do not use a CDataObjectBase object, use only CDataObjectBase derived
+ // objects
+ return nullptr;
}
Modified: lldb/trunk/tools/lldb-mi/Platform.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-mi/Platform.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-mi/Platform.h (original)
+++ lldb/trunk/tools/lldb-mi/Platform.h Tue Sep 6 15:57:50 2016
@@ -10,23 +10,21 @@
#if defined(_MSC_VER)
-#include <io.h>
#include <eh.h>
#include <inttypes.h>
-#include <signal.h>
-#include <lldb/Host/windows/Windows.h>
+#include <io.h>
#include <lldb/Host/HostGetOpt.h>
+#include <lldb/Host/windows/Windows.h>
+#include <signal.h>
// This is not used by MI
-struct timeval
-{
- long tv_sec;
- long tv_usec;
+struct timeval {
+ long tv_sec;
+ long tv_usec;
};
-struct winsize
-{
- long ws_col;
+struct winsize {
+ long ws_col;
};
typedef unsigned char cc_t;
@@ -43,16 +41,15 @@ typedef unsigned int tcflag_t;
#define TCSANOW 0
#define NCCS 32
-struct termios
-{
- tcflag_t c_iflag; // input mode flags
- tcflag_t c_oflag; // output mode flags
- tcflag_t c_cflag; // control mode flags
- tcflag_t c_lflag; // local mode flags
- cc_t c_line; // line discipline
- cc_t c_cc[NCCS]; // control characters
- speed_t c_ispeed; // input speed
- speed_t c_ospeed; // output speed
+struct termios {
+ tcflag_t c_iflag; // input mode flags
+ tcflag_t c_oflag; // output mode flags
+ tcflag_t c_cflag; // control mode flags
+ tcflag_t c_lflag; // local mode flags
+ cc_t c_line; // line discipline
+ cc_t c_cc[NCCS]; // control characters
+ speed_t c_ispeed; // input speed
+ speed_t c_ospeed; // output speed
};
typedef long pid_t;
@@ -63,7 +60,8 @@ typedef long pid_t;
extern int ioctl(int d, int request, ...);
extern int kill(pid_t pid, int sig);
-extern int tcsetattr(int fd, int optional_actions, const struct termios *termios_p);
+extern int tcsetattr(int fd, int optional_actions,
+ const struct termios *termios_p);
extern int tcgetattr(int fildes, struct termios *termios_p);
// signal handler function pointer type
@@ -71,13 +69,13 @@ typedef void (*sighandler_t)(int);
// CODETAG_IOR_SIGNALS
// signal.h
-#define SIGQUIT 3 // Terminal quit signal
-#define SIGKILL 9 // Kill (cannot be caught or ignored)
-#define SIGPIPE 13 // Write on a pipe with no one to read it
-#define SIGCONT 18 // Continue executing, if stopped.
-#define SIGTSTP 20 // Terminal stop signal
-#define SIGSTOP 23 // Stop executing (cannot be caught or ignored)
-#define SIGWINCH 28 // (== SIGVTALRM)
+#define SIGQUIT 3 // Terminal quit signal
+#define SIGKILL 9 // Kill (cannot be caught or ignored)
+#define SIGPIPE 13 // Write on a pipe with no one to read it
+#define SIGCONT 18 // Continue executing, if stopped.
+#define SIGTSTP 20 // Terminal stop signal
+#define SIGSTOP 23 // Stop executing (cannot be caught or ignored)
+#define SIGWINCH 28 // (== SIGVTALRM)
#else
Modified: lldb/trunk/tools/lldb-perf/common/clang/lldb_perf_clang.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/common/clang/lldb_perf_clang.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/common/clang/lldb_perf_clang.cpp (original)
+++ lldb/trunk/tools/lldb-perf/common/clang/lldb_perf_clang.cpp Tue Sep 6 15:57:50 2016
@@ -7,107 +7,99 @@
//
//===----------------------------------------------------------------------===//
-#include "lldb-perf/lib/Timer.h"
-#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
+#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Results.h"
#include "lldb-perf/lib/TestCase.h"
+#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Xcode.h"
#include "llvm/ADT/STLExtras.h"
-#include <iostream>
-#include <unistd.h>
#include <fstream>
#include <getopt.h>
+#include <iostream>
+#include <unistd.h>
using namespace lldb_perf;
#define NUM_EXPR_ITERATIONS 3
-class ClangTest : public TestCase
-{
+class ClangTest : public TestCase {
public:
- ClangTest () :
- TestCase(),
- m_time_create_target ([this] () -> void
- {
- m_memory_change_create_target.Start();
- m_target = m_debugger.CreateTarget(m_exe_path.c_str());
- m_memory_change_create_target.Stop();
- }, "time-create-target", "The time it takes to create a target."),
- m_time_set_bp_main([this] () -> void
- {
- m_memory_change_break_main.Start();
- m_target.BreakpointCreateByName("main");
- m_memory_change_break_main.Stop();
- }, "time-set-break-main", "Elapsed time it takes to set a breakpoint at 'main' by name."),
- m_memory_change_create_target (),
- m_memory_change_break_main (),
- m_memory_total (),
- m_time_launch_stop_main(),
- m_time_total (),
- m_expr_first_evaluate([this] (SBFrame frame) -> void
- {
- frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()").GetError();
- }, "time-expr", "Elapsed time it takes to evaluate an expression for the first time."),
- m_expr_frame_zero ([this] (SBFrame frame) -> void
- {
- frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()").GetError();
- }, "time-expr-frame-zero", "Elapsed time it takes to evaluate an expression 3 times at frame zero."),
- m_expr_frame_non_zero ([this] (SBFrame frame) -> void
- {
- frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()").GetError();
- }, "time-expr-frame-non-zero", "Elapsed time it takes to evaluate an expression 3 times at a non-zero frame."),
- m_exe_path(),
- m_out_path(),
- m_launch_info (NULL),
- m_use_dsym (false)
- {
- }
+ ClangTest()
+ : TestCase(),
+ m_time_create_target(
+ [this]() -> void {
+ m_memory_change_create_target.Start();
+ m_target = m_debugger.CreateTarget(m_exe_path.c_str());
+ m_memory_change_create_target.Stop();
+ },
+ "time-create-target", "The time it takes to create a target."),
+ m_time_set_bp_main(
+ [this]() -> void {
+ m_memory_change_break_main.Start();
+ m_target.BreakpointCreateByName("main");
+ m_memory_change_break_main.Stop();
+ },
+ "time-set-break-main",
+ "Elapsed time it takes to set a breakpoint at 'main' by name."),
+ m_memory_change_create_target(), m_memory_change_break_main(),
+ m_memory_total(), m_time_launch_stop_main(), m_time_total(),
+ m_expr_first_evaluate(
+ [this](SBFrame frame) -> void {
+ frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()")
+ .GetError();
+ },
+ "time-expr", "Elapsed time it takes to evaluate an expression for "
+ "the first time."),
+ m_expr_frame_zero(
+ [this](SBFrame frame) -> void {
+ frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()")
+ .GetError();
+ },
+ "time-expr-frame-zero", "Elapsed time it takes to evaluate an "
+ "expression 3 times at frame zero."),
+ m_expr_frame_non_zero(
+ [this](SBFrame frame) -> void {
+ frame.EvaluateExpression("Diags.DiagArgumentsStr[0].size()")
+ .GetError();
+ },
+ "time-expr-frame-non-zero", "Elapsed time it takes to evaluate an "
+ "expression 3 times at a non-zero "
+ "frame."),
+ m_exe_path(), m_out_path(), m_launch_info(NULL), m_use_dsym(false) {}
+
+ virtual ~ClangTest() {}
+
+ virtual bool Setup(int &argc, const char **&argv) {
+ if (m_exe_path.empty())
+ return false;
+ m_launch_info.SetArguments(argv, false);
+ return true;
+ }
+
+ void DoTest() {}
+
+ virtual void TestStep(int counter, ActionWanted &next_action) {
+ char temp_source_path[PATH_MAX] = "/tmp/main.XXXXXX.cpp";
+
+ switch (counter) {
+ case 0: {
+ // Xcode::RunCommand(m_debugger,"log enable -f /tmp/packets.txt gdb-remote
+ // packets",true);
+
+ m_memory_total.Start();
+ m_time_total.Start();
+
+ // Time creating the target
+ m_time_create_target();
- virtual
- ~ClangTest ()
- {
- }
-
- virtual bool
- Setup (int& argc, const char**& argv)
- {
- if (m_exe_path.empty())
- return false;
- m_launch_info.SetArguments(argv, false);
- return true;
- }
-
- void
- DoTest ()
- {
- }
-
- virtual void
- TestStep (int counter, ActionWanted &next_action)
- {
- char temp_source_path[PATH_MAX] = "/tmp/main.XXXXXX.cpp";
+ m_time_set_bp_main();
- switch (counter)
- {
- case 0:
- {
- //Xcode::RunCommand(m_debugger,"log enable -f /tmp/packets.txt gdb-remote packets",true);
-
- m_memory_total.Start();
- m_time_total.Start();
-
- // Time creating the target
- m_time_create_target();
-
- m_time_set_bp_main();
-
- int fd = mkstemps(temp_source_path, 4);
-
- if (fd >= 0)
- {
- const char *source_content = R"(
-#include <stdio.h>
+ int fd = mkstemps(temp_source_path, 4);
+
+ if (fd >= 0) {
+ const char *source_content = R"(
#include <stdint.h>
+#include <stdio.h>
#include <vector>
namespace {
@@ -132,331 +124,299 @@ int main (int argc, char const *argv[],
return 0;
}
)";
- write (fd, source_content, strlen(source_content));
- close(fd);
- }
- else
- {
- const char *error_cstr = strerror(errno);
- fprintf (stderr, "error: failed to created temporary source file: '%s' (%s)", temp_source_path, error_cstr);
- exit(2);
- }
-
- m_time_launch_stop_main.Start();
- const char *clang_argv[] = {
- "-cc1",
- "-triple", "x86_64-apple-macosx10.8.0",
- "-emit-obj",
- "-mrelax-all",
- "-disable-free",
- "-disable-llvm-verifier",
- "-main-file-name", "main.cpp",
- "-mrelocation-model", "pic",
- "-pic-level", "2",
- "-mdisable-fp-elim",
- "-masm-verbose",
- "-munwind-tables",
- "-target-cpu", "core2",
- "-target-linker-version", "132.10.1",
- "-v",
- "-g",
- "-O0",
- "-fdeprecated-macro",
- "-ferror-limit", "19",
- "-fmessage-length", "298",
- "-stack-protector", "1",
- "-mstackrealign",
- "-fblocks",
- "-fobjc-runtime=macosx-10.8.0",
- "-fobjc-dispatch-method=mixed",
- "-fencode-extended-block-signature",
- "-fcxx-exceptions",
- "-fexceptions",
- "-fdiagnostics-show-option",
- "-fcolor-diagnostics",
- "-backend-option",
- "-vectorize-loops",
- "-o", "/tmp/main.o",
- "-x", "c++",
- NULL,
- NULL };
- clang_argv[llvm::array_lengthof(clang_argv)-2] = temp_source_path;
- SBLaunchInfo launch_info(clang_argv);
- Launch (launch_info);
- next_action.None(); // Don't continue or do anything, just wait for next event...
- }
- break;
- case 1:
- {
- m_time_launch_stop_main.Stop();
- m_time_total.Stop();
- SBFrame frame (m_thread.GetFrameAtIndex(0));
-
- // Time the first expression evaluation
- m_expr_first_evaluate(frame);
-
- SBValue result;
- for (size_t i=0; i<NUM_EXPR_ITERATIONS; ++i)
- {
- m_expr_frame_zero(frame);
- }
- m_target.BreakpointCreateByName("DeclContext::lookup");
- next_action.Continue();
- }
- break;
- case 2:
- {
- SBFrame frame (m_thread.GetFrameAtIndex(21));
- SBValue result;
- for (size_t i=0; i<NUM_EXPR_ITERATIONS; ++i)
- {
- m_expr_frame_non_zero(frame);
- }
- next_action.Continue();
- }
- break;
- default:
- m_memory_total.Stop();
- next_action.Kill();
- break;
- }
- }
-
- void
- WriteResults (Results &results)
- {
- Results::Dictionary& results_dict = results.GetDictionary();
-
- m_time_set_bp_main.WriteAverageAndStandardDeviation(results);
- results_dict.Add ("memory-change-create-target",
- "Memory increase that occurs due to creating the target.",
- m_memory_change_create_target.GetDeltaValue().GetResult(NULL, NULL));
-
- results_dict.Add ("memory-change-break-main",
- "Memory increase that occurs due to setting a breakpoint at main by name.",
- m_memory_change_break_main.GetDeltaValue().GetResult(NULL, NULL));
-
- m_time_create_target.WriteAverageAndStandardDeviation(results);
- m_expr_first_evaluate.WriteAverageAndStandardDeviation(results);
- m_expr_frame_zero.WriteAverageAndStandardDeviation(results);
- m_expr_frame_non_zero.WriteAverageAndStandardDeviation(results);
- results_dict.Add ("memory-total-break-main",
- "The total memory that the current process is using after setting the first breakpoint.",
- m_memory_total.GetStopValue().GetResult(NULL, NULL));
-
- results_dict.AddDouble("time-launch-stop-main",
- "The time it takes to launch the process and stop at main.",
- m_time_launch_stop_main.GetDeltaValue());
-
- results_dict.AddDouble("time-total",
- "The time it takes to create the target, set breakpoint at main, launch clang and hit the breakpoint at main.",
- m_time_total.GetDeltaValue());
- results.Write(GetResultFilePath());
- }
-
-
-
- const char *
- GetExecutablePath () const
- {
- if (m_exe_path.empty())
- return NULL;
- return m_exe_path.c_str();
- }
+ write(fd, source_content, strlen(source_content));
+ close(fd);
+ } else {
+ const char *error_cstr = strerror(errno);
+ fprintf(stderr,
+ "error: failed to created temporary source file: '%s' (%s)",
+ temp_source_path, error_cstr);
+ exit(2);
+ }
+
+ m_time_launch_stop_main.Start();
+ const char *clang_argv[] = {"-cc1",
+ "-triple",
+ "x86_64-apple-macosx10.8.0",
+ "-emit-obj",
+ "-mrelax-all",
+ "-disable-free",
+ "-disable-llvm-verifier",
+ "-main-file-name",
+ "main.cpp",
+ "-mrelocation-model",
+ "pic",
+ "-pic-level",
+ "2",
+ "-mdisable-fp-elim",
+ "-masm-verbose",
+ "-munwind-tables",
+ "-target-cpu",
+ "core2",
+ "-target-linker-version",
+ "132.10.1",
+ "-v",
+ "-g",
+ "-O0",
+ "-fdeprecated-macro",
+ "-ferror-limit",
+ "19",
+ "-fmessage-length",
+ "298",
+ "-stack-protector",
+ "1",
+ "-mstackrealign",
+ "-fblocks",
+ "-fobjc-runtime=macosx-10.8.0",
+ "-fobjc-dispatch-method=mixed",
+ "-fencode-extended-block-signature",
+ "-fcxx-exceptions",
+ "-fexceptions",
+ "-fdiagnostics-show-option",
+ "-fcolor-diagnostics",
+ "-backend-option",
+ "-vectorize-loops",
+ "-o",
+ "/tmp/main.o",
+ "-x",
+ "c++",
+ NULL,
+ NULL};
+ clang_argv[llvm::array_lengthof(clang_argv) - 2] = temp_source_path;
+ SBLaunchInfo launch_info(clang_argv);
+ Launch(launch_info);
+ next_action
+ .None(); // Don't continue or do anything, just wait for next event...
+ } break;
+ case 1: {
+ m_time_launch_stop_main.Stop();
+ m_time_total.Stop();
+ SBFrame frame(m_thread.GetFrameAtIndex(0));
+
+ // Time the first expression evaluation
+ m_expr_first_evaluate(frame);
+
+ SBValue result;
+ for (size_t i = 0; i < NUM_EXPR_ITERATIONS; ++i) {
+ m_expr_frame_zero(frame);
+ }
+ m_target.BreakpointCreateByName("DeclContext::lookup");
+ next_action.Continue();
+ } break;
+ case 2: {
+ SBFrame frame(m_thread.GetFrameAtIndex(21));
+ SBValue result;
+ for (size_t i = 0; i < NUM_EXPR_ITERATIONS; ++i) {
+ m_expr_frame_non_zero(frame);
+ }
+ next_action.Continue();
+ } break;
+ default:
+ m_memory_total.Stop();
+ next_action.Kill();
+ break;
+ }
+ }
+
+ void WriteResults(Results &results) {
+ Results::Dictionary &results_dict = results.GetDictionary();
+
+ m_time_set_bp_main.WriteAverageAndStandardDeviation(results);
+ results_dict.Add(
+ "memory-change-create-target",
+ "Memory increase that occurs due to creating the target.",
+ m_memory_change_create_target.GetDeltaValue().GetResult(NULL, NULL));
+
+ results_dict.Add(
+ "memory-change-break-main", "Memory increase that occurs due to "
+ "setting a breakpoint at main by name.",
+ m_memory_change_break_main.GetDeltaValue().GetResult(NULL, NULL));
+
+ m_time_create_target.WriteAverageAndStandardDeviation(results);
+ m_expr_first_evaluate.WriteAverageAndStandardDeviation(results);
+ m_expr_frame_zero.WriteAverageAndStandardDeviation(results);
+ m_expr_frame_non_zero.WriteAverageAndStandardDeviation(results);
+ results_dict.Add("memory-total-break-main",
+ "The total memory that the current process is using after "
+ "setting the first breakpoint.",
+ m_memory_total.GetStopValue().GetResult(NULL, NULL));
+
+ results_dict.AddDouble(
+ "time-launch-stop-main",
+ "The time it takes to launch the process and stop at main.",
+ m_time_launch_stop_main.GetDeltaValue());
+
+ results_dict.AddDouble(
+ "time-total", "The time it takes to create the target, set breakpoint "
+ "at main, launch clang and hit the breakpoint at main.",
+ m_time_total.GetDeltaValue());
+ results.Write(GetResultFilePath());
+ }
+
+ const char *GetExecutablePath() const {
+ if (m_exe_path.empty())
+ return NULL;
+ return m_exe_path.c_str();
+ }
+
+ const char *GetResultFilePath() const {
+ if (m_out_path.empty())
+ return NULL;
+ return m_out_path.c_str();
+ }
+
+ void SetExecutablePath(const char *path) {
+ if (path && path[0])
+ m_exe_path = path;
+ else
+ m_exe_path.clear();
+ }
+
+ void SetResultFilePath(const char *path) {
+ if (path && path[0])
+ m_out_path = path;
+ else
+ m_out_path.clear();
+ }
- const char *
- GetResultFilePath () const
- {
- if (m_out_path.empty())
- return NULL;
- return m_out_path.c_str();
- }
+ void SetUseDSYM(bool b) { m_use_dsym = b; }
- void
- SetExecutablePath (const char *path)
- {
- if (path && path[0])
- m_exe_path = path;
- else
- m_exe_path.clear();
- }
-
- void
- SetResultFilePath (const char *path)
- {
- if (path && path[0])
- m_out_path = path;
- else
- m_out_path.clear();
- }
-
- void
- SetUseDSYM (bool b)
- {
- m_use_dsym = b;
- }
-
-
-
private:
- // C++ formatters
- TimeMeasurement<std::function<void()>> m_time_create_target;
- TimeMeasurement<std::function<void()>> m_time_set_bp_main;
- MemoryGauge m_memory_change_create_target;
- MemoryGauge m_memory_change_break_main;
- MemoryGauge m_memory_total;
- TimeGauge m_time_launch_stop_main;
- TimeGauge m_time_total;
- TimeMeasurement<std::function<void(SBFrame)>> m_expr_first_evaluate;
- TimeMeasurement<std::function<void(SBFrame)>> m_expr_frame_zero;
- TimeMeasurement<std::function<void(SBFrame)>> m_expr_frame_non_zero;
- std::string m_exe_path;
- std::string m_out_path;
- SBLaunchInfo m_launch_info;
- bool m_use_dsym;
-
+ // C++ formatters
+ TimeMeasurement<std::function<void()>> m_time_create_target;
+ TimeMeasurement<std::function<void()>> m_time_set_bp_main;
+ MemoryGauge m_memory_change_create_target;
+ MemoryGauge m_memory_change_break_main;
+ MemoryGauge m_memory_total;
+ TimeGauge m_time_launch_stop_main;
+ TimeGauge m_time_total;
+ TimeMeasurement<std::function<void(SBFrame)>> m_expr_first_evaluate;
+ TimeMeasurement<std::function<void(SBFrame)>> m_expr_frame_zero;
+ TimeMeasurement<std::function<void(SBFrame)>> m_expr_frame_non_zero;
+ std::string m_exe_path;
+ std::string m_out_path;
+ SBLaunchInfo m_launch_info;
+ bool m_use_dsym;
};
+struct Options {
+ std::string clang_path;
+ std::string out_file;
+ bool verbose;
+ bool use_dsym;
+ bool error;
+ bool print_help;
-struct Options
-{
- std::string clang_path;
- std::string out_file;
- bool verbose;
- bool use_dsym;
- bool error;
- bool print_help;
-
- Options() :
- verbose (false),
- error (false),
- print_help (false)
- {
- }
+ Options() : verbose(false), error(false), print_help(false) {}
};
static struct option g_long_options[] = {
- { "verbose", no_argument, NULL, 'v' },
- { "clang", required_argument, NULL, 'c' },
- { "out-file", required_argument, NULL, 'o' },
- { "dsym", no_argument, NULL, 'd' },
- { NULL, 0, NULL, 0 }
-};
-
-
-std::string
-GetShortOptionString (struct option *long_options)
-{
- std::string option_string;
- for (int i = 0; long_options[i].name != NULL; ++i)
- {
- if (long_options[i].flag == NULL)
- {
- option_string.push_back ((char) long_options[i].val);
- switch (long_options[i].has_arg)
- {
- default:
- case no_argument:
- break;
- case required_argument:
- option_string.push_back (':');
- break;
- case optional_argument:
- option_string.append (2, ':');
- break;
- }
- }
+ {"verbose", no_argument, NULL, 'v'},
+ {"clang", required_argument, NULL, 'c'},
+ {"out-file", required_argument, NULL, 'o'},
+ {"dsym", no_argument, NULL, 'd'},
+ {NULL, 0, NULL, 0}};
+
+std::string GetShortOptionString(struct option *long_options) {
+ std::string option_string;
+ for (int i = 0; long_options[i].name != NULL; ++i) {
+ if (long_options[i].flag == NULL) {
+ option_string.push_back((char)long_options[i].val);
+ switch (long_options[i].has_arg) {
+ default:
+ case no_argument:
+ break;
+ case required_argument:
+ option_string.push_back(':');
+ break;
+ case optional_argument:
+ option_string.append(2, ':');
+ break;
+ }
}
- return option_string;
+ }
+ return option_string;
}
-int main(int argc, const char * argv[])
-{
+int main(int argc, const char *argv[]) {
+
+ // Prepare for & make calls to getopt_long_only.
- // Prepare for & make calls to getopt_long_only.
-
- std::string short_option_string (GetShortOptionString(g_long_options));
-
- ClangTest test;
+ std::string short_option_string(GetShortOptionString(g_long_options));
- Options option_data;
- bool done = false;
+ ClangTest test;
+
+ Options option_data;
+ bool done = false;
#if __GLIBC__
- optind = 0;
+ optind = 0;
#else
- optreset = 1;
- optind = 1;
+ optreset = 1;
+ optind = 1;
#endif
- while (!done)
- {
- int long_options_index = -1;
- const int short_option = ::getopt_long_only (argc,
- const_cast<char **>(argv),
- short_option_string.c_str(),
- g_long_options,
- &long_options_index);
-
- switch (short_option)
- {
- case 0:
- // Already handled
- break;
-
- case -1:
- done = true;
- break;
-
- case '?':
- option_data.print_help = true;
- break;
-
- case 'h':
- option_data.print_help = true;
- break;
-
- case 'v':
- option_data.verbose = true;
- break;
-
- case 'c':
- {
- SBFileSpec file(optarg);
- if (file.Exists())
- test.SetExecutablePath(optarg);
- else
- fprintf(stderr, "error: file specified in --clang (-c) option doesn't exist: '%s'\n", optarg);
- }
- break;
-
- case 'o':
- test.SetResultFilePath(optarg);
- break;
-
- case 'd':
- test.SetUseDSYM(true);
- break;
-
- default:
- option_data.error = true;
- option_data.print_help = true;
- fprintf (stderr, "error: unrecognized option %c\n", short_option);
- break;
- }
- }
-
+ while (!done) {
+ int long_options_index = -1;
+ const int short_option = ::getopt_long_only(
+ argc, const_cast<char **>(argv), short_option_string.c_str(),
+ g_long_options, &long_options_index);
+
+ switch (short_option) {
+ case 0:
+ // Already handled
+ break;
+
+ case -1:
+ done = true;
+ break;
+
+ case '?':
+ option_data.print_help = true;
+ break;
+
+ case 'h':
+ option_data.print_help = true;
+ break;
+
+ case 'v':
+ option_data.verbose = true;
+ break;
+
+ case 'c': {
+ SBFileSpec file(optarg);
+ if (file.Exists())
+ test.SetExecutablePath(optarg);
+ else
+ fprintf(stderr, "error: file specified in --clang (-c) option doesn't "
+ "exist: '%s'\n",
+ optarg);
+ } break;
+
+ case 'o':
+ test.SetResultFilePath(optarg);
+ break;
+
+ case 'd':
+ test.SetUseDSYM(true);
+ break;
+
+ default:
+ option_data.error = true;
+ option_data.print_help = true;
+ fprintf(stderr, "error: unrecognized option %c\n", short_option);
+ break;
+ }
+ }
+
+ if (test.GetExecutablePath() == NULL) {
+ // --clang is mandatory
+ option_data.print_help = true;
+ option_data.error = true;
+ fprintf(stderr, "error: the '--clang=PATH' option is mandatory\n");
+ }
- if (test.GetExecutablePath() == NULL)
- {
- // --clang is mandatory
- option_data.print_help = true;
- option_data.error = true;
- fprintf (stderr, "error: the '--clang=PATH' option is mandatory\n");
- }
-
- if (option_data.print_help)
- {
- puts(R"(
+ if (option_data.print_help) {
+ puts(R"(
NAME
lldb_perf_clang -- a tool that measures LLDB peformance while debugging clang.
@@ -467,18 +427,16 @@ DESCRIPTION
Runs a set of static timing and memory tasks against clang and outputs results
to a plist file.
)");
- }
- if (option_data.error)
- {
- exit(1);
- }
-
- // Update argc and argv after parsing options
- argc -= optind;
- argv += optind;
-
- test.SetVerbose(true);
- TestCase::Run(test, argc, argv);
- return 0;
+ }
+ if (option_data.error) {
+ exit(1);
+ }
+
+ // Update argc and argv after parsing options
+ argc -= optind;
+ argv += optind;
+
+ test.SetVerbose(true);
+ TestCase::Run(test, argc, argv);
+ return 0;
}
-
Modified: lldb/trunk/tools/lldb-perf/common/clang/main.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/common/clang/main.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/common/clang/main.cpp (original)
+++ lldb/trunk/tools/lldb-perf/common/clang/main.cpp Tue Sep 6 15:57:50 2016
@@ -1,24 +1,20 @@
-#include <stdio.h>
#include <stdint.h>
+#include <stdio.h>
#include <vector>
namespace {
- struct Foo
- {
- int i; int j;
- };
- void doit (const Foo &foo)
- {
- printf ("doit(%i)\n", foo.i);
- }
+struct Foo {
+ int i;
+ int j;
+};
+void doit(const Foo &foo) { printf("doit(%i)\n", foo.i); }
}
-int main (int argc, char const *argv[], char const *envp[])
-{
- std::vector<int> ints;
- for (int i=0;i<10;++i)
- ints.push_back(i);
- printf ("hello world\n");
- Foo foo = { 12, 13 };
- doit (foo);
- return 0;
+int main(int argc, char const *argv[], char const *envp[]) {
+ std::vector<int> ints;
+ for (int i = 0; i < 10; ++i)
+ ints.push_back(i);
+ printf("hello world\n");
+ Foo foo = {12, 13};
+ doit(foo);
+ return 0;
}
Modified: lldb/trunk/tools/lldb-perf/common/stepping/lldb-perf-stepping.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/common/stepping/lldb-perf-stepping.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/common/stepping/lldb-perf-stepping.cpp (original)
+++ lldb/trunk/tools/lldb-perf/common/stepping/lldb-perf-stepping.cpp Tue Sep 6 15:57:50 2016
@@ -1,305 +1,259 @@
#include <CoreFoundation/CoreFoundation.h>
-#include "lldb-perf/lib/Timer.h"
-#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
+#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/TestCase.h"
+#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Xcode.h"
-#include <unistd.h>
-#include <string>
#include <getopt.h>
+#include <string>
+#include <unistd.h>
using namespace lldb_perf;
-class StepTest : public TestCase
-{
- typedef void (*no_function) (void);
-
+class StepTest : public TestCase {
+ typedef void (*no_function)(void);
+
public:
- StepTest(bool use_single_stepping = false) :
- m_main_source("stepping-testcase.cpp"),
+ StepTest(bool use_single_stepping = false)
+ : m_main_source("stepping-testcase.cpp"),
m_use_single_stepping(use_single_stepping),
- m_time_measurements(nullptr)
- {
- }
-
- virtual
- ~StepTest() {}
-
- virtual bool
- Setup (int& argc, const char**& argv)
- {
- TestCase::Setup (argc, argv);
-
- // Toggle the fast stepping command on or off as required.
- const char *single_step_cmd = "settings set target.use-fast-stepping false";
- const char *fast_step_cmd = "settings set target.use-fast-stepping true";
- const char *cmd_to_use;
-
- if (m_use_single_stepping)
- cmd_to_use = single_step_cmd;
- else
- cmd_to_use = fast_step_cmd;
-
- SBCommandReturnObject return_object;
- m_debugger.GetCommandInterpreter().HandleCommand(cmd_to_use,
- return_object);
- if (!return_object.Succeeded())
- {
- if (return_object.GetError() != NULL)
- printf ("Got an error running settings set: %s.\n", return_object.GetError());
- else
- printf ("Failed running settings set, no error.\n");
- }
-
- m_target = m_debugger.CreateTarget(m_app_path.c_str());
- m_first_bp = m_target.BreakpointCreateBySourceRegex("Here is some code to stop at originally.", m_main_source);
-
- const char* file_arg = m_app_path.c_str();
- const char* empty = nullptr;
- const char* args[] = {file_arg, empty};
- SBLaunchInfo launch_info (args);
-
- return Launch (launch_info);
- }
+ m_time_measurements(nullptr) {}
- void
- WriteResults (Results &results)
- {
- // Gotta turn off the last timer now.
- m_individual_step_times.push_back(m_time_measurements.Stop());
-
- size_t num_time_measurements = m_individual_step_times.size();
-
- Results::Dictionary& results_dict = results.GetDictionary();
- const char *short_format_string = "step-time-%0.2d";
- const size_t short_size = strlen(short_format_string) + 5;
- char short_buffer[short_size];
- const char *long_format_string = "The time it takes for step %d in the step sequence.";
- const size_t long_size = strlen(long_format_string) + 5;
- char long_buffer[long_size];
-
- for (size_t i = 0; i < num_time_measurements; i++)
- {
- snprintf (short_buffer, short_size, short_format_string, i);
- snprintf (long_buffer, long_size, long_format_string, i);
-
- results_dict.AddDouble(short_buffer,
- long_buffer,
- m_individual_step_times[i]);
-
- }
- results_dict.AddDouble ("total-time", "Total time spent stepping.", m_time_measurements.GetMetric().GetSum());
- results_dict.AddDouble ("stddev-time", "StdDev of time spent stepping.", m_time_measurements.GetMetric().GetStandardDeviation());
+ virtual ~StepTest() {}
- results.Write(m_out_path.c_str());
- }
-
+ virtual bool Setup(int &argc, const char **&argv) {
+ TestCase::Setup(argc, argv);
- const char *
- GetExecutablePath () const
- {
- if (m_app_path.empty())
- return NULL;
- return m_app_path.c_str();
- }
+ // Toggle the fast stepping command on or off as required.
+ const char *single_step_cmd = "settings set target.use-fast-stepping false";
+ const char *fast_step_cmd = "settings set target.use-fast-stepping true";
+ const char *cmd_to_use;
+
+ if (m_use_single_stepping)
+ cmd_to_use = single_step_cmd;
+ else
+ cmd_to_use = fast_step_cmd;
+
+ SBCommandReturnObject return_object;
+ m_debugger.GetCommandInterpreter().HandleCommand(cmd_to_use, return_object);
+ if (!return_object.Succeeded()) {
+ if (return_object.GetError() != NULL)
+ printf("Got an error running settings set: %s.\n",
+ return_object.GetError());
+ else
+ printf("Failed running settings set, no error.\n");
+ }
+
+ m_target = m_debugger.CreateTarget(m_app_path.c_str());
+ m_first_bp = m_target.BreakpointCreateBySourceRegex(
+ "Here is some code to stop at originally.", m_main_source);
+
+ const char *file_arg = m_app_path.c_str();
+ const char *empty = nullptr;
+ const char *args[] = {file_arg, empty};
+ SBLaunchInfo launch_info(args);
+
+ return Launch(launch_info);
+ }
+
+ void WriteResults(Results &results) {
+ // Gotta turn off the last timer now.
+ m_individual_step_times.push_back(m_time_measurements.Stop());
+
+ size_t num_time_measurements = m_individual_step_times.size();
+
+ Results::Dictionary &results_dict = results.GetDictionary();
+ const char *short_format_string = "step-time-%0.2d";
+ const size_t short_size = strlen(short_format_string) + 5;
+ char short_buffer[short_size];
+ const char *long_format_string =
+ "The time it takes for step %d in the step sequence.";
+ const size_t long_size = strlen(long_format_string) + 5;
+ char long_buffer[long_size];
+
+ for (size_t i = 0; i < num_time_measurements; i++) {
+ snprintf(short_buffer, short_size, short_format_string, i);
+ snprintf(long_buffer, long_size, long_format_string, i);
+
+ results_dict.AddDouble(short_buffer, long_buffer,
+ m_individual_step_times[i]);
+ }
+ results_dict.AddDouble("total-time", "Total time spent stepping.",
+ m_time_measurements.GetMetric().GetSum());
+ results_dict.AddDouble(
+ "stddev-time", "StdDev of time spent stepping.",
+ m_time_measurements.GetMetric().GetStandardDeviation());
+
+ results.Write(m_out_path.c_str());
+ }
+
+ const char *GetExecutablePath() const {
+ if (m_app_path.empty())
+ return NULL;
+ return m_app_path.c_str();
+ }
+
+ const char *GetResultFilePath() const {
+ if (m_out_path.empty())
+ return NULL;
+ return m_out_path.c_str();
+ }
+
+ void SetExecutablePath(const char *path) {
+ if (path && path[0])
+ m_app_path = path;
+ else
+ m_app_path.clear();
+ }
+
+ void SetResultFilePath(const char *path) {
+ if (path && path[0])
+ m_out_path = path;
+ else
+ m_out_path.clear();
+ }
- const char *
- GetResultFilePath () const
- {
- if (m_out_path.empty())
- return NULL;
- return m_out_path.c_str();
- }
+ void SetUseSingleStep(bool use_it) { m_use_single_stepping = use_it; }
- void
- SetExecutablePath (const char *path)
- {
- if (path && path[0])
- m_app_path = path;
- else
- m_app_path.clear();
- }
-
- void
- SetResultFilePath (const char *path)
- {
- if (path && path[0])
- m_out_path = path;
- else
- m_out_path.clear();
- }
-
- void
- SetUseSingleStep (bool use_it)
- {
- m_use_single_stepping = use_it;
- }
private:
- virtual void
- TestStep (int counter, ActionWanted &next_action)
- {
- if (counter > 0)
- {
- m_individual_step_times.push_back(m_time_measurements.Stop());
-
- }
-
- // Disable the breakpoint, just in case it gets multiple locations we don't want that confusing the stepping.
- if (counter == 0)
- m_first_bp.SetEnabled(false);
-
- next_action.StepOver(m_process.GetThreadAtIndex(0));
- m_time_measurements.Start();
-
-
- }
-
- SBBreakpoint m_first_bp;
- SBFileSpec m_main_source;
- TimeMeasurement<no_function> m_time_measurements;
- std::vector<double> m_individual_step_times;
- bool m_use_single_stepping;
- std::string m_app_path;
- std::string m_out_path;
-
-
+ virtual void TestStep(int counter, ActionWanted &next_action) {
+ if (counter > 0) {
+ m_individual_step_times.push_back(m_time_measurements.Stop());
+ }
+
+ // Disable the breakpoint, just in case it gets multiple locations we don't
+ // want that confusing the stepping.
+ if (counter == 0)
+ m_first_bp.SetEnabled(false);
+
+ next_action.StepOver(m_process.GetThreadAtIndex(0));
+ m_time_measurements.Start();
+ }
+
+ SBBreakpoint m_first_bp;
+ SBFileSpec m_main_source;
+ TimeMeasurement<no_function> m_time_measurements;
+ std::vector<double> m_individual_step_times;
+ bool m_use_single_stepping;
+ std::string m_app_path;
+ std::string m_out_path;
};
-struct Options
-{
- std::string test_file_path;
- std::string out_file;
- bool verbose;
- bool fast_step;
- bool error;
- bool print_help;
-
- Options() :
- verbose (false),
- fast_step (true),
- error (false),
- print_help (false)
- {
- }
-};
+struct Options {
+ std::string test_file_path;
+ std::string out_file;
+ bool verbose;
+ bool fast_step;
+ bool error;
+ bool print_help;
-static struct option g_long_options[] = {
- { "verbose", no_argument, NULL, 'v' },
- { "single-step", no_argument, NULL, 's' },
- { "test-file", required_argument, NULL, 't' },
- { "out-file", required_argument, NULL, 'o' },
- { NULL, 0, NULL, 0 }
+ Options()
+ : verbose(false), fast_step(true), error(false), print_help(false) {}
};
-
-std::string
-GetShortOptionString (struct option *long_options)
-{
- std::string option_string;
- for (int i = 0; long_options[i].name != NULL; ++i)
- {
- if (long_options[i].flag == NULL)
- {
- option_string.push_back ((char) long_options[i].val);
- switch (long_options[i].has_arg)
- {
- default:
- case no_argument:
- break;
- case required_argument:
- option_string.push_back (':');
- break;
- case optional_argument:
- option_string.append (2, ':');
- break;
- }
- }
+static struct option g_long_options[] = {
+ {"verbose", no_argument, NULL, 'v'},
+ {"single-step", no_argument, NULL, 's'},
+ {"test-file", required_argument, NULL, 't'},
+ {"out-file", required_argument, NULL, 'o'},
+ {NULL, 0, NULL, 0}};
+
+std::string GetShortOptionString(struct option *long_options) {
+ std::string option_string;
+ for (int i = 0; long_options[i].name != NULL; ++i) {
+ if (long_options[i].flag == NULL) {
+ option_string.push_back((char)long_options[i].val);
+ switch (long_options[i].has_arg) {
+ default:
+ case no_argument:
+ break;
+ case required_argument:
+ option_string.push_back(':');
+ break;
+ case optional_argument:
+ option_string.append(2, ':');
+ break;
+ }
}
- return option_string;
+ }
+ return option_string;
}
-int main(int argc, const char * argv[])
-{
+int main(int argc, const char *argv[]) {
- // Prepare for & make calls to getopt_long_only.
-
- std::string short_option_string (GetShortOptionString(g_long_options));
-
- StepTest test;
+ // Prepare for & make calls to getopt_long_only.
- Options option_data;
- bool done = false;
+ std::string short_option_string(GetShortOptionString(g_long_options));
+
+ StepTest test;
+
+ Options option_data;
+ bool done = false;
#if __GLIBC__
- optind = 0;
+ optind = 0;
#else
- optreset = 1;
- optind = 1;
+ optreset = 1;
+ optind = 1;
#endif
- while (!done)
- {
- int long_options_index = -1;
- const int short_option = ::getopt_long_only (argc,
- const_cast<char **>(argv),
- short_option_string.c_str(),
- g_long_options,
- &long_options_index);
-
- switch (short_option)
- {
- case 0:
- // Already handled
- break;
-
- case -1:
- done = true;
- break;
-
- case '?':
- option_data.print_help = true;
- break;
-
- case 'h':
- option_data.print_help = true;
- break;
-
- case 'v':
- option_data.verbose = true;
- break;
-
- case 's':
- option_data.fast_step = false;
- test.SetUseSingleStep(true);
- break;
-
- case 't':
- {
- SBFileSpec file(optarg);
- if (file.Exists())
- test.SetExecutablePath(optarg);
- else
- fprintf(stderr, "error: file specified in --test-file (-t) option doesn't exist: '%s'\n", optarg);
- }
- break;
-
- case 'o':
- test.SetResultFilePath(optarg);
- break;
-
- default:
- option_data.error = true;
- option_data.print_help = true;
- fprintf (stderr, "error: unrecognized option %c\n", short_option);
- break;
- }
+ while (!done) {
+ int long_options_index = -1;
+ const int short_option = ::getopt_long_only(
+ argc, const_cast<char **>(argv), short_option_string.c_str(),
+ g_long_options, &long_options_index);
+
+ switch (short_option) {
+ case 0:
+ // Already handled
+ break;
+
+ case -1:
+ done = true;
+ break;
+
+ case '?':
+ option_data.print_help = true;
+ break;
+
+ case 'h':
+ option_data.print_help = true;
+ break;
+
+ case 'v':
+ option_data.verbose = true;
+ break;
+
+ case 's':
+ option_data.fast_step = false;
+ test.SetUseSingleStep(true);
+ break;
+
+ case 't': {
+ SBFileSpec file(optarg);
+ if (file.Exists())
+ test.SetExecutablePath(optarg);
+ else
+ fprintf(stderr, "error: file specified in --test-file (-t) option "
+ "doesn't exist: '%s'\n",
+ optarg);
+ } break;
+
+ case 'o':
+ test.SetResultFilePath(optarg);
+ break;
+
+ default:
+ option_data.error = true;
+ option_data.print_help = true;
+ fprintf(stderr, "error: unrecognized option %c\n", short_option);
+ break;
}
+ }
-
- if (option_data.print_help)
- {
- puts(R"(
+ if (option_data.print_help) {
+ puts(R"(
NAME
lldb-perf-stepping -- a tool that measures LLDB peformance of simple stepping operations.
@@ -310,26 +264,24 @@ DESCRIPTION
Runs a set of stepping operations, timing each step and outputs results
to a plist file.
)");
- exit(0);
- }
- if (option_data.error)
- {
- exit(1);
- }
-
- if (test.GetExecutablePath() == NULL)
- {
- // --clang is mandatory
- option_data.print_help = true;
- option_data.error = true;
- fprintf (stderr, "error: the '--test-file=PATH' option is mandatory\n");
- }
-
- // Update argc and argv after parsing options
- argc -= optind;
- argv += optind;
-
- test.SetVerbose(true);
- TestCase::Run(test, argc, argv);
- return 0;
+ exit(0);
+ }
+ if (option_data.error) {
+ exit(1);
+ }
+
+ if (test.GetExecutablePath() == NULL) {
+ // --clang is mandatory
+ option_data.print_help = true;
+ option_data.error = true;
+ fprintf(stderr, "error: the '--test-file=PATH' option is mandatory\n");
+ }
+
+ // Update argc and argv after parsing options
+ argc -= optind;
+ argv += optind;
+
+ test.SetVerbose(true);
+ TestCase::Run(test, argc, argv);
+ return 0;
}
Modified: lldb/trunk/tools/lldb-perf/common/stepping/stepping-testcase.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/common/stepping/stepping-testcase.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/common/stepping/stepping-testcase.cpp (original)
+++ lldb/trunk/tools/lldb-perf/common/stepping/stepping-testcase.cpp Tue Sep 6 15:57:50 2016
@@ -1,42 +1,35 @@
#include <stdio.h>
-#include <vector>
#include <string>
+#include <vector>
+
+struct struct_for_copying {
+ struct_for_copying(int in_int, double in_double, const char *in_string)
+ : int_value(in_int), double_value(in_double), string_value(in_string) {}
+ struct_for_copying() { struct_for_copying(0, 0, ""); }
-struct struct_for_copying
-{
- struct_for_copying (int in_int, double in_double, const char *in_string) :
- int_value(in_int),
- double_value(in_double),
- string_value (in_string)
- {
-
- }
- struct_for_copying()
- {
- struct_for_copying (0, 0, "");
- }
-
- int int_value;
- double double_value;
- std::string string_value;
+ int int_value;
+ double double_value;
+ std::string string_value;
};
-int main (int argc, char **argv)
-{
- struct_for_copying input_struct (150 * argc, 10.0 * argc, argv[0]);
- struct_for_copying output_struct;
- int some_int = 44;
- double some_double = 34.5;
- double other_double;
- size_t vector_size;
- std::vector<struct_for_copying> my_vector;
-
- printf ("Here is some code to stop at originally. Got: %d, %p.\n", argc, argv);
- output_struct = input_struct;
- other_double = (some_double * some_int)/((double) argc);
- other_double = other_double > 0 ? some_double/other_double : some_double > 0 ? other_double/some_double : 10.0;
- my_vector.push_back (input_struct);
- vector_size = my_vector.size();
-
- return vector_size == 0 ? 0 : 1;
+int main(int argc, char **argv) {
+ struct_for_copying input_struct(150 * argc, 10.0 * argc, argv[0]);
+ struct_for_copying output_struct;
+ int some_int = 44;
+ double some_double = 34.5;
+ double other_double;
+ size_t vector_size;
+ std::vector<struct_for_copying> my_vector;
+
+ printf("Here is some code to stop at originally. Got: %d, %p.\n", argc,
+ argv);
+ output_struct = input_struct;
+ other_double = (some_double * some_int) / ((double)argc);
+ other_double = other_double > 0
+ ? some_double / other_double
+ : some_double > 0 ? other_double / some_double : 10.0;
+ my_vector.push_back(input_struct);
+ vector_size = my_vector.size();
+
+ return vector_size == 0 ? 0 : 1;
}
Modified: lldb/trunk/tools/lldb-perf/darwin/formatters/fmts_tester.mm
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/darwin/formatters/fmts_tester.mm?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/darwin/formatters/fmts_tester.mm (original)
+++ lldb/trunk/tools/lldb-perf/darwin/formatters/fmts_tester.mm Tue Sep 6 15:57:50 2016
@@ -7,73 +7,76 @@
//
//===----------------------------------------------------------------------===//
-
#import <Cocoa/Cocoa.h>
-#include <vector>
#include <list>
#include <map>
#include <string>
+#include <vector>
-int main()
-{
- NSArray* nsarray = @[@1, at 2,@"hello world", at 3, at 4,@"foobar"];
- NSMutableArray* nsmutablearray = [[NSMutableArray alloc] initWithCapacity:5];
- [nsmutablearray addObject:@1];
- [nsmutablearray addObject:@2];
- [nsmutablearray addObject:@"hello world"];
- [nsmutablearray addObject:@3];
- [nsmutablearray addObject:@4];
- [nsmutablearray addObject:@"foobar"];
- NSDictionary* nsdictionary = @{@1 : @1, @2 : @2, @"hello" : @"world", @3 : @3};
- NSMutableDictionary* nsmutabledictionary = [[NSMutableDictionary alloc] initWithCapacity:5];
- [nsmutabledictionary setObject:@1 forKey:@1];
- [nsmutabledictionary setObject:@2 forKey:@2];
- [nsmutabledictionary setObject:@"hello" forKey:@"world"];
- [nsmutabledictionary setObject:@3 forKey:@3];
- NSString* str0 = @"Hello world";
- NSString* str1 = @"Hello ℥";
- NSString* str2 = @"Hello world";
- NSString* str3 = @"Hello ℥";
- NSString* str4 = @"Hello world";
- NSDate* me = [NSDate dateWithNaturalLanguageString:@"April 10, 1985"];
- NSDate* cutie = [NSDate dateWithNaturalLanguageString:@"January 29, 1983"];
- NSDate* mom = [NSDate dateWithNaturalLanguageString:@"May 24, 1959"];
- NSDate* dad = [NSDate dateWithNaturalLanguageString:@"October 29, 1954"];
- NSDate* today = [NSDate dateWithNaturalLanguageString:@"March 14, 2013"];
- NSArray* bundles = [NSBundle allBundles];
- NSArray* frameworks = [NSBundle allFrameworks];
- NSSet* nsset = [NSSet setWithArray:nsarray];
- NSMutableSet* nsmutableset = [NSMutableSet setWithCapacity:5];
- [nsmutableset addObject:@1];
- [nsmutableset addObject:@2];
- [nsmutableset addObject:@"hello world"];
- [nsmutableset addObject:@3];
- [nsmutableset addObject:@4];
- [nsmutableset addObject:@"foobar"];
- std::vector<int> vector;
- vector.push_back(1);
- vector.push_back(2);
- vector.push_back(3);
- vector.push_back(4);
- vector.push_back(5);
- std::list<int> list;
- list.push_back(1);
- list.push_back(2);
- list.push_back(3);
- list.push_back(4);
- list.push_back(5);
- std::map<int,int> map;
- map[1] = 1;
- map[2] = 2;
- map[3] = 3;
- map[4] = 4;
- map[5] = 5;
- std::string sstr0("Hello world");
- std::string sstr1("Hello world");
- std::string sstr2("Hello world");
- std::string sstr3("Hello world");
- std::string sstr4("Hello world");
- int x = 0;
- for (;;)
- x++;
+int main() {
+ NSArray *nsarray = @[ @1, @2, @"hello world", @3, @4, @"foobar" ];
+ NSMutableArray *nsmutablearray = [[NSMutableArray alloc] initWithCapacity:5];
+ [nsmutablearray addObject:@1];
+ [nsmutablearray addObject:@2];
+ [nsmutablearray addObject:@"hello world"];
+ [nsmutablearray addObject:@3];
+ [nsmutablearray addObject:@4];
+ [nsmutablearray addObject:@"foobar"];
+ NSDictionary *nsdictionary =
+ @{ @1 : @1,
+ @2 : @2,
+ @"hello" : @"world",
+ @3 : @3 };
+ NSMutableDictionary *nsmutabledictionary =
+ [[NSMutableDictionary alloc] initWithCapacity:5];
+ [nsmutabledictionary setObject:@1 forKey:@1];
+ [nsmutabledictionary setObject:@2 forKey:@2];
+ [nsmutabledictionary setObject:@"hello" forKey:@"world"];
+ [nsmutabledictionary setObject:@3 forKey:@3];
+ NSString *str0 = @"Hello world";
+ NSString *str1 = @"Hello ℥";
+ NSString *str2 = @"Hello world";
+ NSString *str3 = @"Hello ℥";
+ NSString *str4 = @"Hello world";
+ NSDate *me = [NSDate dateWithNaturalLanguageString:@"April 10, 1985"];
+ NSDate *cutie = [NSDate dateWithNaturalLanguageString:@"January 29, 1983"];
+ NSDate *mom = [NSDate dateWithNaturalLanguageString:@"May 24, 1959"];
+ NSDate *dad = [NSDate dateWithNaturalLanguageString:@"October 29, 1954"];
+ NSDate *today = [NSDate dateWithNaturalLanguageString:@"March 14, 2013"];
+ NSArray *bundles = [NSBundle allBundles];
+ NSArray *frameworks = [NSBundle allFrameworks];
+ NSSet *nsset = [NSSet setWithArray:nsarray];
+ NSMutableSet *nsmutableset = [NSMutableSet setWithCapacity:5];
+ [nsmutableset addObject:@1];
+ [nsmutableset addObject:@2];
+ [nsmutableset addObject:@"hello world"];
+ [nsmutableset addObject:@3];
+ [nsmutableset addObject:@4];
+ [nsmutableset addObject:@"foobar"];
+ std::vector<int> vector;
+ vector.push_back(1);
+ vector.push_back(2);
+ vector.push_back(3);
+ vector.push_back(4);
+ vector.push_back(5);
+ std::list<int> list;
+ list.push_back(1);
+ list.push_back(2);
+ list.push_back(3);
+ list.push_back(4);
+ list.push_back(5);
+ std::map<int, int> map;
+ map[1] = 1;
+ map[2] = 2;
+ map[3] = 3;
+ map[4] = 4;
+ map[5] = 5;
+ std::string sstr0("Hello world");
+ std::string sstr1("Hello world");
+ std::string sstr2("Hello world");
+ std::string sstr3("Hello world");
+ std::string sstr4("Hello world");
+ int x = 0;
+ for (;;)
+ x++;
}
\ No newline at end of file
Modified: lldb/trunk/tools/lldb-perf/darwin/formatters/formatters.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/darwin/formatters/formatters.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/darwin/formatters/formatters.cpp (original)
+++ lldb/trunk/tools/lldb-perf/darwin/formatters/formatters.cpp Tue Sep 6 15:57:50 2016
@@ -9,238 +9,260 @@
#include <CoreFoundation/CoreFoundation.h>
-#include "lldb-perf/lib/Timer.h"
-#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
+#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/TestCase.h"
+#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Xcode.h"
+#include <fstream>
#include <iostream>
#include <unistd.h>
-#include <fstream>
using namespace lldb_perf;
-class FormattersTest : public TestCase
-{
+class FormattersTest : public TestCase {
public:
- FormattersTest () : TestCase()
- {
- m_dump_std_vector_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "std-vector", "time to dump an std::vector");
- m_dump_std_list_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "std-list", "time to dump an std::list");
- m_dump_std_map_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "std-map", "time to dump an std::map");
-
- // use this in manual mode
- m_dump_std_string_measurement = CreateTimeMeasurement([] () -> void {
- }, "std-string", "time to dump an std::string");
-
- m_dump_nsstring_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,0,false);
- }, "ns-string", "time to dump an NSString");
-
- m_dump_nsarray_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "ns-array", "time to dump an NSArray");
-
- m_dump_nsdictionary_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "ns-dictionary", "time to dump an NSDictionary");
-
- m_dump_nsset_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "ns-set", "time to dump an NSSet");
-
- m_dump_nsbundle_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,1,false);
- }, "ns-bundle", "time to dump an NSBundle");
-
- m_dump_nsdate_measurement = CreateTimeMeasurement([] (SBValue value) -> void {
- lldb_perf::Xcode::FetchVariable (value,0,false);
- }, "ns-date", "time to dump an NSDate");
+ FormattersTest() : TestCase() {
+ m_dump_std_vector_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "std-vector", "time to dump an std::vector");
+ m_dump_std_list_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "std-list", "time to dump an std::list");
+ m_dump_std_map_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "std-map", "time to dump an std::map");
+
+ // use this in manual mode
+ m_dump_std_string_measurement = CreateTimeMeasurement(
+ []() -> void {}, "std-string", "time to dump an std::string");
+
+ m_dump_nsstring_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 0, false);
+ },
+ "ns-string", "time to dump an NSString");
+
+ m_dump_nsarray_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "ns-array", "time to dump an NSArray");
+
+ m_dump_nsdictionary_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "ns-dictionary", "time to dump an NSDictionary");
+
+ m_dump_nsset_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "ns-set", "time to dump an NSSet");
+
+ m_dump_nsbundle_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 1, false);
+ },
+ "ns-bundle", "time to dump an NSBundle");
+
+ m_dump_nsdate_measurement = CreateTimeMeasurement(
+ [](SBValue value) -> void {
+ lldb_perf::Xcode::FetchVariable(value, 0, false);
+ },
+ "ns-date", "time to dump an NSDate");
+ }
+
+ virtual ~FormattersTest() {}
+
+ virtual bool Setup(int &argc, const char **&argv) {
+ m_app_path.assign(argv[1]);
+ m_out_path.assign(argv[2]);
+ m_target = m_debugger.CreateTarget(m_app_path.c_str());
+ m_target.BreakpointCreateByName("main");
+ SBLaunchInfo launch_info(argv);
+ return Launch(launch_info);
+ }
+
+ void DoTest() {
+ SBFrame frame_zero(m_thread.GetFrameAtIndex(0));
+
+ m_dump_nsarray_measurement(
+ frame_zero.FindVariable("nsarray", lldb::eDynamicCanRunTarget));
+ m_dump_nsarray_measurement(
+ frame_zero.FindVariable("nsmutablearray", lldb::eDynamicCanRunTarget));
+
+ m_dump_nsdictionary_measurement(
+ frame_zero.FindVariable("nsdictionary", lldb::eDynamicCanRunTarget));
+ m_dump_nsdictionary_measurement(frame_zero.FindVariable(
+ "nsmutabledictionary", lldb::eDynamicCanRunTarget));
+
+ m_dump_nsstring_measurement(
+ frame_zero.FindVariable("str0", lldb::eDynamicCanRunTarget));
+ m_dump_nsstring_measurement(
+ frame_zero.FindVariable("str1", lldb::eDynamicCanRunTarget));
+ m_dump_nsstring_measurement(
+ frame_zero.FindVariable("str2", lldb::eDynamicCanRunTarget));
+ m_dump_nsstring_measurement(
+ frame_zero.FindVariable("str3", lldb::eDynamicCanRunTarget));
+ m_dump_nsstring_measurement(
+ frame_zero.FindVariable("str4", lldb::eDynamicCanRunTarget));
+
+ m_dump_nsdate_measurement(
+ frame_zero.FindVariable("me", lldb::eDynamicCanRunTarget));
+ m_dump_nsdate_measurement(
+ frame_zero.FindVariable("cutie", lldb::eDynamicCanRunTarget));
+ m_dump_nsdate_measurement(
+ frame_zero.FindVariable("mom", lldb::eDynamicCanRunTarget));
+ m_dump_nsdate_measurement(
+ frame_zero.FindVariable("dad", lldb::eDynamicCanRunTarget));
+ m_dump_nsdate_measurement(
+ frame_zero.FindVariable("today", lldb::eDynamicCanRunTarget));
+
+ m_dump_nsbundle_measurement(
+ frame_zero.FindVariable("bundles", lldb::eDynamicCanRunTarget));
+ m_dump_nsbundle_measurement(
+ frame_zero.FindVariable("frameworks", lldb::eDynamicCanRunTarget));
+
+ m_dump_nsset_measurement(
+ frame_zero.FindVariable("nsset", lldb::eDynamicCanRunTarget));
+ m_dump_nsset_measurement(
+ frame_zero.FindVariable("nsmutableset", lldb::eDynamicCanRunTarget));
+
+ m_dump_std_vector_measurement(
+ frame_zero.FindVariable("vector", lldb::eDynamicCanRunTarget));
+ m_dump_std_list_measurement(
+ frame_zero.FindVariable("list", lldb::eDynamicCanRunTarget));
+ m_dump_std_map_measurement(
+ frame_zero.FindVariable("map", lldb::eDynamicCanRunTarget));
+
+ auto sstr0 = frame_zero.FindVariable("sstr0", lldb::eDynamicCanRunTarget);
+ auto sstr1 = frame_zero.FindVariable("sstr1", lldb::eDynamicCanRunTarget);
+ auto sstr2 = frame_zero.FindVariable("sstr2", lldb::eDynamicCanRunTarget);
+ auto sstr3 = frame_zero.FindVariable("sstr3", lldb::eDynamicCanRunTarget);
+ auto sstr4 = frame_zero.FindVariable("sstr4", lldb::eDynamicCanRunTarget);
+
+ m_dump_std_string_measurement.Start();
+ Xcode::FetchVariable(sstr0, 0, false);
+ m_dump_std_string_measurement.Stop();
+
+ m_dump_std_string_measurement.Start();
+ Xcode::FetchVariable(sstr1, 0, false);
+ m_dump_std_string_measurement.Stop();
+
+ m_dump_std_string_measurement.Start();
+ Xcode::FetchVariable(sstr2, 0, false);
+ m_dump_std_string_measurement.Stop();
+
+ m_dump_std_string_measurement.Start();
+ Xcode::FetchVariable(sstr3, 0, false);
+ m_dump_std_string_measurement.Stop();
+
+ m_dump_std_string_measurement.Start();
+ Xcode::FetchVariable(sstr4, 0, false);
+ m_dump_std_string_measurement.Stop();
+ }
+
+ virtual void TestStep(int counter, ActionWanted &next_action) {
+ switch (counter) {
+ case 0:
+ m_target.BreakpointCreateByLocation("fmts_tester.mm", 78);
+ next_action.Continue();
+ break;
+ case 1:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 2:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 3:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 4:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 5:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 6:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 7:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 8:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 9:
+ DoTest();
+ next_action.Continue();
+ break;
+ case 10:
+ DoTest();
+ next_action.Continue();
+ break;
+ default:
+ next_action.Kill();
+ break;
}
+ }
+
+ virtual void WriteResults(Results &results) {
+ m_dump_std_vector_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_std_list_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_std_map_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_std_string_measurement.WriteAverageAndStandardDeviation(results);
+
+ m_dump_nsstring_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_nsarray_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_nsdictionary_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_nsset_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_nsbundle_measurement.WriteAverageAndStandardDeviation(results);
+ m_dump_nsdate_measurement.WriteAverageAndStandardDeviation(results);
+ results.Write(m_out_path.c_str());
+ }
- virtual
- ~FormattersTest ()
- {
- }
-
- virtual bool
- Setup (int& argc, const char**& argv)
- {
- m_app_path.assign(argv[1]);
- m_out_path.assign(argv[2]);
- m_target = m_debugger.CreateTarget(m_app_path.c_str());
- m_target.BreakpointCreateByName("main");
- SBLaunchInfo launch_info(argv);
- return Launch (launch_info);
- }
-
- void
- DoTest ()
- {
- SBFrame frame_zero(m_thread.GetFrameAtIndex(0));
-
- m_dump_nsarray_measurement(frame_zero.FindVariable("nsarray", lldb::eDynamicCanRunTarget));
- m_dump_nsarray_measurement(frame_zero.FindVariable("nsmutablearray", lldb::eDynamicCanRunTarget));
-
- m_dump_nsdictionary_measurement(frame_zero.FindVariable("nsdictionary", lldb::eDynamicCanRunTarget));
- m_dump_nsdictionary_measurement(frame_zero.FindVariable("nsmutabledictionary", lldb::eDynamicCanRunTarget));
-
- m_dump_nsstring_measurement(frame_zero.FindVariable("str0", lldb::eDynamicCanRunTarget));
- m_dump_nsstring_measurement(frame_zero.FindVariable("str1", lldb::eDynamicCanRunTarget));
- m_dump_nsstring_measurement(frame_zero.FindVariable("str2", lldb::eDynamicCanRunTarget));
- m_dump_nsstring_measurement(frame_zero.FindVariable("str3", lldb::eDynamicCanRunTarget));
- m_dump_nsstring_measurement(frame_zero.FindVariable("str4", lldb::eDynamicCanRunTarget));
-
- m_dump_nsdate_measurement(frame_zero.FindVariable("me", lldb::eDynamicCanRunTarget));
- m_dump_nsdate_measurement(frame_zero.FindVariable("cutie", lldb::eDynamicCanRunTarget));
- m_dump_nsdate_measurement(frame_zero.FindVariable("mom", lldb::eDynamicCanRunTarget));
- m_dump_nsdate_measurement(frame_zero.FindVariable("dad", lldb::eDynamicCanRunTarget));
- m_dump_nsdate_measurement(frame_zero.FindVariable("today", lldb::eDynamicCanRunTarget));
-
- m_dump_nsbundle_measurement(frame_zero.FindVariable("bundles", lldb::eDynamicCanRunTarget));
- m_dump_nsbundle_measurement(frame_zero.FindVariable("frameworks", lldb::eDynamicCanRunTarget));
-
- m_dump_nsset_measurement(frame_zero.FindVariable("nsset", lldb::eDynamicCanRunTarget));
- m_dump_nsset_measurement(frame_zero.FindVariable("nsmutableset", lldb::eDynamicCanRunTarget));
-
- m_dump_std_vector_measurement(frame_zero.FindVariable("vector", lldb::eDynamicCanRunTarget));
- m_dump_std_list_measurement(frame_zero.FindVariable("list", lldb::eDynamicCanRunTarget));
- m_dump_std_map_measurement(frame_zero.FindVariable("map", lldb::eDynamicCanRunTarget));
-
- auto sstr0 = frame_zero.FindVariable("sstr0", lldb::eDynamicCanRunTarget);
- auto sstr1 = frame_zero.FindVariable("sstr1", lldb::eDynamicCanRunTarget);
- auto sstr2 = frame_zero.FindVariable("sstr2", lldb::eDynamicCanRunTarget);
- auto sstr3 = frame_zero.FindVariable("sstr3", lldb::eDynamicCanRunTarget);
- auto sstr4 = frame_zero.FindVariable("sstr4", lldb::eDynamicCanRunTarget);
-
- m_dump_std_string_measurement.Start();
- Xcode::FetchVariable(sstr0,0,false);
- m_dump_std_string_measurement.Stop();
-
- m_dump_std_string_measurement.Start();
- Xcode::FetchVariable(sstr1,0,false);
- m_dump_std_string_measurement.Stop();
-
- m_dump_std_string_measurement.Start();
- Xcode::FetchVariable(sstr2,0,false);
- m_dump_std_string_measurement.Stop();
-
- m_dump_std_string_measurement.Start();
- Xcode::FetchVariable(sstr3,0,false);
- m_dump_std_string_measurement.Stop();
-
- m_dump_std_string_measurement.Start();
- Xcode::FetchVariable(sstr4,0,false);
- m_dump_std_string_measurement.Stop();
-
- }
-
- virtual void
- TestStep (int counter, ActionWanted &next_action)
- {
- switch (counter)
- {
- case 0:
- m_target.BreakpointCreateByLocation("fmts_tester.mm", 78);
- next_action.Continue();
- break;
- case 1:
- DoTest ();
- next_action.Continue();
- break;
- case 2:
- DoTest ();
- next_action.Continue();
- break;
- case 3:
- DoTest ();
- next_action.Continue();
- break;
- case 4:
- DoTest ();
- next_action.Continue();
- break;
- case 5:
- DoTest ();
- next_action.Continue();
- break;
- case 6:
- DoTest ();
- next_action.Continue();
- break;
- case 7:
- DoTest ();
- next_action.Continue();
- break;
- case 8:
- DoTest ();
- next_action.Continue();
- break;
- case 9:
- DoTest ();
- next_action.Continue();
- break;
- case 10:
- DoTest ();
- next_action.Continue();
- break;
- default:
- next_action.Kill();
- break;
- }
- }
-
- virtual void
- WriteResults (Results &results)
- {
- m_dump_std_vector_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_std_list_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_std_map_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_std_string_measurement.WriteAverageAndStandardDeviation(results);
-
- m_dump_nsstring_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_nsarray_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_nsdictionary_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_nsset_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_nsbundle_measurement.WriteAverageAndStandardDeviation(results);
- m_dump_nsdate_measurement.WriteAverageAndStandardDeviation(results);
- results.Write(m_out_path.c_str());
- }
-
private:
- // C++ formatters
- TimeMeasurement<std::function<void(SBValue)>> m_dump_std_vector_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_std_list_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_std_map_measurement;
- TimeMeasurement<std::function<void()>> m_dump_std_string_measurement;
-
- // Cocoa formatters
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsstring_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsarray_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsdictionary_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsset_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsbundle_measurement;
- TimeMeasurement<std::function<void(SBValue)>> m_dump_nsdate_measurement;
-
- // useful files
- std::string m_app_path;
- std::string m_out_path;
+ // C++ formatters
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_std_vector_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_std_list_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_std_map_measurement;
+ TimeMeasurement<std::function<void()>> m_dump_std_string_measurement;
+
+ // Cocoa formatters
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsstring_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsarray_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsdictionary_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsset_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsbundle_measurement;
+ TimeMeasurement<std::function<void(SBValue)>> m_dump_nsdate_measurement;
+
+ // useful files
+ std::string m_app_path;
+ std::string m_out_path;
};
// argv[1] == path to app
// argv[2] == path to result
-int main(int argc, const char * argv[])
-{
- FormattersTest frmtest;
- frmtest.SetVerbose(true);
- TestCase::Run(frmtest,argc,argv);
- return 0;
+int main(int argc, const char *argv[]) {
+ FormattersTest frmtest;
+ frmtest.SetVerbose(true);
+ TestCase::Run(frmtest, argc, argv);
+ return 0;
}
-
Modified: lldb/trunk/tools/lldb-perf/darwin/sketch/sketch.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/darwin/sketch/sketch.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/darwin/sketch/sketch.cpp (original)
+++ lldb/trunk/tools/lldb-perf/darwin/sketch/sketch.cpp Tue Sep 6 15:57:50 2016
@@ -9,152 +9,141 @@
#include <CoreFoundation/CoreFoundation.h>
-#include "lldb-perf/lib/Timer.h"
-#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
+#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/TestCase.h"
+#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Xcode.h"
-#include <iostream>
-#include <unistd.h>
#include <fstream>
#include <getopt.h>
+#include <iostream>
+#include <unistd.h>
using namespace lldb_perf;
static struct option g_long_options[] = {
- { "verbose", no_argument, NULL, 'v' },
- { "sketch", required_argument, NULL, 'c' },
- { "foobar", required_argument, NULL, 'f' },
- { "out-file", required_argument, NULL, 'o' },
- { NULL, 0, NULL, 0 }
-};
+ {"verbose", no_argument, NULL, 'v'},
+ {"sketch", required_argument, NULL, 'c'},
+ {"foobar", required_argument, NULL, 'f'},
+ {"out-file", required_argument, NULL, 'o'},
+ {NULL, 0, NULL, 0}};
-class SketchTest : public TestCase
-{
+class SketchTest : public TestCase {
public:
- SketchTest () :
- m_fetch_frames_measurement ([this] () -> void
- {
- Xcode::FetchFrames (GetProcess(),false,false);
- }, "fetch-frames", "time to dump backtrace for every frame in every thread"),
- m_file_line_bp_measurement([this] (const char* file, uint32_t line) -> void
- {
- Xcode::CreateFileLineBreakpoint(GetTarget(), file, line);
- }, "file-line-bkpt", "time to set a breakpoint given a file and line"),
- m_fetch_modules_measurement ([this] () -> void
- {
- Xcode::FetchModules(GetTarget());
- }, "fetch-modules", "time to get info for all modules in the process"),
- m_fetch_vars_measurement([this] (int depth) -> void
- {
- SBProcess process (GetProcess());
- auto threads_count = process.GetNumThreads();
- for (size_t thread_num = 0; thread_num < threads_count; thread_num++)
- {
- SBThread thread(process.GetThreadAtIndex(thread_num));
- SBFrame frame(thread.GetFrameAtIndex(0));
- Xcode::FetchVariables(frame,depth,GetVerbose());
- }
- }, "fetch-vars", "time to dump variables for the topmost frame in every thread"),
- m_run_expr_measurement([this] (SBFrame frame, const char* expr) -> void
- {
- SBValue value(frame.EvaluateExpression(expr, lldb::eDynamicCanRunTarget));
- Xcode::FetchVariable (value, 0, GetVerbose());
- }, "run-expr", "time to evaluate an expression and display the result")
- {
- m_app_path.clear();
- m_out_path.clear();
- m_doc_path.clear();
- m_print_help = false;
- }
-
- virtual
- ~SketchTest ()
- {
+ SketchTest()
+ : m_fetch_frames_measurement(
+ [this]() -> void {
+ Xcode::FetchFrames(GetProcess(), false, false);
+ },
+ "fetch-frames",
+ "time to dump backtrace for every frame in every thread"),
+ m_file_line_bp_measurement(
+ [this](const char *file, uint32_t line) -> void {
+ Xcode::CreateFileLineBreakpoint(GetTarget(), file, line);
+ },
+ "file-line-bkpt", "time to set a breakpoint given a file and line"),
+ m_fetch_modules_measurement(
+ [this]() -> void { Xcode::FetchModules(GetTarget()); },
+ "fetch-modules", "time to get info for all modules in the process"),
+ m_fetch_vars_measurement(
+ [this](int depth) -> void {
+ SBProcess process(GetProcess());
+ auto threads_count = process.GetNumThreads();
+ for (size_t thread_num = 0; thread_num < threads_count;
+ thread_num++) {
+ SBThread thread(process.GetThreadAtIndex(thread_num));
+ SBFrame frame(thread.GetFrameAtIndex(0));
+ Xcode::FetchVariables(frame, depth, GetVerbose());
+ }
+ },
+ "fetch-vars",
+ "time to dump variables for the topmost frame in every thread"),
+ m_run_expr_measurement(
+ [this](SBFrame frame, const char *expr) -> void {
+ SBValue value(
+ frame.EvaluateExpression(expr, lldb::eDynamicCanRunTarget));
+ Xcode::FetchVariable(value, 0, GetVerbose());
+ },
+ "run-expr",
+ "time to evaluate an expression and display the result") {
+ m_app_path.clear();
+ m_out_path.clear();
+ m_doc_path.clear();
+ m_print_help = false;
+ }
+
+ virtual ~SketchTest() {}
+
+ virtual bool ParseOption(int short_option, const char *optarg) {
+ switch (short_option) {
+ case 0:
+ return false;
+
+ case -1:
+ return false;
+
+ case '?':
+ case 'h':
+ m_print_help = true;
+ break;
+
+ case 'v':
+ SetVerbose(true);
+ break;
+
+ case 'c': {
+ SBFileSpec file(optarg);
+ if (file.Exists())
+ SetExecutablePath(optarg);
+ else
+ fprintf(stderr, "error: file specified in --sketch (-c) option doesn't "
+ "exist: '%s'\n",
+ optarg);
+ } break;
+
+ case 'f': {
+ SBFileSpec file(optarg);
+ if (file.Exists())
+ SetDocumentPath(optarg);
+ else
+ fprintf(stderr, "error: file specified in --foobar (-f) option doesn't "
+ "exist: '%s'\n",
+ optarg);
+ } break;
+
+ case 'o':
+ SetResultFilePath(optarg);
+ break;
+
+ default:
+ m_print_help = true;
+ fprintf(stderr, "error: unrecognized option %c\n", short_option);
+ break;
+ }
+ return true;
+ }
+
+ virtual struct option *GetLongOptions() { return g_long_options; }
+
+ virtual bool Setup(int &argc, const char **&argv) {
+ TestCase::Setup(argc, argv);
+ bool error = false;
+
+ if (GetExecutablePath() == NULL) {
+ // --sketch is mandatory
+ error = true;
+ fprintf(stderr, "error: the '--sketch=PATH' option is mandatory\n");
+ }
+
+ if (GetDocumentPath() == NULL) {
+ // --foobar is mandatory
+ error = true;
+ fprintf(stderr, "error: the '--foobar=PATH' option is mandatory\n");
}
-
- virtual bool
- ParseOption (int short_option, const char* optarg)
- {
- switch (short_option)
- {
- case 0:
- return false;
-
- case -1:
- return false;
-
- case '?':
- case 'h':
- m_print_help = true;
- break;
-
- case 'v':
- SetVerbose(true);
- break;
-
- case 'c':
- {
- SBFileSpec file(optarg);
- if (file.Exists())
- SetExecutablePath(optarg);
- else
- fprintf(stderr, "error: file specified in --sketch (-c) option doesn't exist: '%s'\n", optarg);
- }
- break;
-
- case 'f':
- {
- SBFileSpec file(optarg);
- if (file.Exists())
- SetDocumentPath(optarg);
- else
- fprintf(stderr, "error: file specified in --foobar (-f) option doesn't exist: '%s'\n", optarg);
- }
- break;
-
- case 'o':
- SetResultFilePath(optarg);
- break;
-
- default:
- m_print_help = true;
- fprintf (stderr, "error: unrecognized option %c\n", short_option);
- break;
- }
- return true;
- }
-
- virtual struct option*
- GetLongOptions ()
- {
- return g_long_options;
- }
-
- virtual bool
- Setup (int& argc, const char**& argv)
- {
- TestCase::Setup(argc,argv);
- bool error = false;
-
- if (GetExecutablePath() == NULL)
- {
- // --sketch is mandatory
- error = true;
- fprintf (stderr, "error: the '--sketch=PATH' option is mandatory\n");
- }
-
- if (GetDocumentPath() == NULL)
- {
- // --foobar is mandatory
- error = true;
- fprintf (stderr, "error: the '--foobar=PATH' option is mandatory\n");
- }
-
- if (error || GetPrintHelp())
- {
- puts(R"(
+
+ if (error || GetPrintHelp()) {
+ puts(R"(
NAME
lldb_perf_sketch -- a tool that measures LLDB peformance while debugging sketch.
@@ -165,216 +154,177 @@ public:
Runs a set of static timing and memory tasks against sketch and outputs results
to a plist file.
)");
- }
-
- if (error)
- {
- exit(1);
- }
- lldb::SBLaunchInfo launch_info = GetLaunchInfo();
- m_target = m_debugger.CreateTarget(m_app_path.c_str());
- m_file_line_bp_measurement("SKTDocument.m",245);
- m_file_line_bp_measurement("SKTDocument.m",283);
- m_file_line_bp_measurement("SKTText.m",326);
- return Launch (launch_info);
- }
-
- lldb::SBLaunchInfo
- GetLaunchInfo ()
- {
- const char* file_arg = m_doc_path.c_str();
- const char* persist_arg = "-ApplePersistenceIgnoreState";
- const char* persist_skip = "YES";
- const char* empty = nullptr;
- const char* args[] = {file_arg,persist_arg,persist_skip,empty};
- return SBLaunchInfo(args);
- }
-
- void
- DoTest ()
- {
- m_fetch_frames_measurement();
- m_fetch_modules_measurement();
- m_fetch_vars_measurement(1);
- }
-
- virtual void
- TestStep (int counter, ActionWanted &next_action)
- {
- static int launch = 1;
- switch (counter % 10)
- {
- case 0:
- {
- DoTest ();
- if (counter == 0)
- m_file_line_bp_measurement("SKTDocument.m",254);
- next_action.Continue();
- }
- break;
-
- case 1:
- {
- DoTest ();
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"properties");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"[properties description]");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"typeName");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"data");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"[data description]");
- next_action.Continue();
- }
- break;
-
- case 2:
- {
- DoTest ();
- next_action.Continue();
- }
- break;
-
- case 3:
- {
- DoTest ();
- next_action.StepOver(m_thread);
- }
- break;
-
- case 4:
- {
- DoTest ();
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"layoutManager");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"contents");
- next_action.StepOver(m_thread);
- }
- break;
-
- case 5:
- {
- DoTest ();
- next_action.StepOver(m_thread);
- }
- break;
-
- case 6:
- {
- DoTest ();
- next_action.StepOver(m_thread);
- }
- break;
-
- case 7:
- {
- DoTest ();
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"@\"an NSString\"");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"[(id)@\"an NSString\" description]");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"@[@1, at 2, at 3]");
- next_action.StepOut(m_thread);
- }
- break;
-
- case 8:
- {
- DoTest ();
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"[graphics description]");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"[selectionIndexes description]");
- m_run_expr_measurement(m_thread.GetFrameAtIndex(0),"(BOOL)NSIntersectsRect(rect, graphicDrawingBounds)");
- }
- next_action.CallNext();
- break;
- case 9:
- if (++launch < 10)
- next_action.Relaunch(GetLaunchInfo());
- else
- next_action.Kill();
- break;
-
-
- default:
- {
- next_action.Kill();
- }
- break;
- }
- }
-
- virtual void
- WriteResults (Results &results)
- {
- m_fetch_frames_measurement.WriteAverageAndStandardDeviation(results);
- m_file_line_bp_measurement.WriteAverageAndStandardDeviation(results);
- m_fetch_modules_measurement.WriteAverageAndStandardDeviation(results);
- m_fetch_vars_measurement.WriteAverageAndStandardDeviation(results);
- m_run_expr_measurement.WriteAverageAndStandardDeviation(results);
- results.Write(GetResultFilePath());
- }
-
- void
- SetExecutablePath (const char* str)
- {
- if (str)
- m_app_path.assign(str);
- }
-
- const char*
- GetExecutablePath ()
- {
- if (m_app_path.empty())
- return NULL;
- return m_app_path.c_str();
- }
-
- void
- SetDocumentPath (const char* str)
- {
- if (str)
- m_doc_path.assign(str);
- }
-
- const char*
- GetDocumentPath ()
- {
- if (m_doc_path.empty())
- return NULL;
- return m_doc_path.c_str();
}
-
- void
- SetResultFilePath (const char* str)
- {
- if (str)
- m_out_path.assign(str);
- }
-
- const char*
- GetResultFilePath ()
- {
- if (m_out_path.empty())
- return "/dev/stdout";
- return m_out_path.c_str();
+ if (error) {
+ exit(1);
}
-
- bool
- GetPrintHelp ()
- {
- return m_print_help;
- }
-
+ lldb::SBLaunchInfo launch_info = GetLaunchInfo();
+ m_target = m_debugger.CreateTarget(m_app_path.c_str());
+ m_file_line_bp_measurement("SKTDocument.m", 245);
+ m_file_line_bp_measurement("SKTDocument.m", 283);
+ m_file_line_bp_measurement("SKTText.m", 326);
+ return Launch(launch_info);
+ }
+
+ lldb::SBLaunchInfo GetLaunchInfo() {
+ const char *file_arg = m_doc_path.c_str();
+ const char *persist_arg = "-ApplePersistenceIgnoreState";
+ const char *persist_skip = "YES";
+ const char *empty = nullptr;
+ const char *args[] = {file_arg, persist_arg, persist_skip, empty};
+ return SBLaunchInfo(args);
+ }
+
+ void DoTest() {
+ m_fetch_frames_measurement();
+ m_fetch_modules_measurement();
+ m_fetch_vars_measurement(1);
+ }
+
+ virtual void TestStep(int counter, ActionWanted &next_action) {
+ static int launch = 1;
+ switch (counter % 10) {
+ case 0: {
+ DoTest();
+ if (counter == 0)
+ m_file_line_bp_measurement("SKTDocument.m", 254);
+ next_action.Continue();
+ } break;
+
+ case 1: {
+ DoTest();
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "properties");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0),
+ "[properties description]");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "typeName");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "data");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "[data description]");
+ next_action.Continue();
+ } break;
+
+ case 2: {
+ DoTest();
+ next_action.Continue();
+ } break;
+
+ case 3: {
+ DoTest();
+ next_action.StepOver(m_thread);
+ } break;
+
+ case 4: {
+ DoTest();
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "layoutManager");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "contents");
+ next_action.StepOver(m_thread);
+ } break;
+
+ case 5: {
+ DoTest();
+ next_action.StepOver(m_thread);
+ } break;
+
+ case 6: {
+ DoTest();
+ next_action.StepOver(m_thread);
+ } break;
+
+ case 7: {
+ DoTest();
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "@\"an NSString\"");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0),
+ "[(id)@\"an NSString\" description]");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0), "@[@1, at 2, at 3]");
+ next_action.StepOut(m_thread);
+ } break;
+
+ case 8: {
+ DoTest();
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0),
+ "[graphics description]");
+ m_run_expr_measurement(m_thread.GetFrameAtIndex(0),
+ "[selectionIndexes description]");
+ m_run_expr_measurement(
+ m_thread.GetFrameAtIndex(0),
+ "(BOOL)NSIntersectsRect(rect, graphicDrawingBounds)");
+ }
+ next_action.CallNext();
+ break;
+ case 9:
+ if (++launch < 10)
+ next_action.Relaunch(GetLaunchInfo());
+ else
+ next_action.Kill();
+ break;
+
+ default: { next_action.Kill(); } break;
+ }
+ }
+
+ virtual void WriteResults(Results &results) {
+ m_fetch_frames_measurement.WriteAverageAndStandardDeviation(results);
+ m_file_line_bp_measurement.WriteAverageAndStandardDeviation(results);
+ m_fetch_modules_measurement.WriteAverageAndStandardDeviation(results);
+ m_fetch_vars_measurement.WriteAverageAndStandardDeviation(results);
+ m_run_expr_measurement.WriteAverageAndStandardDeviation(results);
+ results.Write(GetResultFilePath());
+ }
+
+ void SetExecutablePath(const char *str) {
+ if (str)
+ m_app_path.assign(str);
+ }
+
+ const char *GetExecutablePath() {
+ if (m_app_path.empty())
+ return NULL;
+ return m_app_path.c_str();
+ }
+
+ void SetDocumentPath(const char *str) {
+ if (str)
+ m_doc_path.assign(str);
+ }
+
+ const char *GetDocumentPath() {
+ if (m_doc_path.empty())
+ return NULL;
+ return m_doc_path.c_str();
+ }
+
+ void SetResultFilePath(const char *str) {
+ if (str)
+ m_out_path.assign(str);
+ }
+
+ const char *GetResultFilePath() {
+ if (m_out_path.empty())
+ return "/dev/stdout";
+ return m_out_path.c_str();
+ }
+
+ bool GetPrintHelp() { return m_print_help; }
+
private:
- Measurement<lldb_perf::TimeGauge, std::function<void()>> m_fetch_frames_measurement;
- Measurement<lldb_perf::TimeGauge, std::function<void(const char*, uint32_t)>> m_file_line_bp_measurement;
- Measurement<lldb_perf::TimeGauge, std::function<void()>> m_fetch_modules_measurement;
- Measurement<lldb_perf::TimeGauge, std::function<void(int)>> m_fetch_vars_measurement;
- Measurement<lldb_perf::TimeGauge, std::function<void(SBFrame, const char*)>> m_run_expr_measurement;
-
- std::string m_app_path;
- std::string m_doc_path;
- std::string m_out_path;
- bool m_print_help;
+ Measurement<lldb_perf::TimeGauge, std::function<void()>>
+ m_fetch_frames_measurement;
+ Measurement<lldb_perf::TimeGauge, std::function<void(const char *, uint32_t)>>
+ m_file_line_bp_measurement;
+ Measurement<lldb_perf::TimeGauge, std::function<void()>>
+ m_fetch_modules_measurement;
+ Measurement<lldb_perf::TimeGauge, std::function<void(int)>>
+ m_fetch_vars_measurement;
+ Measurement<lldb_perf::TimeGauge, std::function<void(SBFrame, const char *)>>
+ m_run_expr_measurement;
+
+ std::string m_app_path;
+ std::string m_doc_path;
+ std::string m_out_path;
+ bool m_print_help;
};
-int main(int argc, const char * argv[])
-{
- SketchTest test;
- return TestCase::Run(test, argc, argv);
+int main(int argc, const char *argv[]) {
+ SketchTest test;
+ return TestCase::Run(test, argc, argv);
}
Modified: lldb/trunk/tools/lldb-perf/lib/Gauge.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Gauge.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Gauge.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/Gauge.cpp Tue Sep 6 15:57:50 2016
@@ -11,43 +11,40 @@
#include "lldb/lldb-forward.h"
template <>
-lldb_perf::Results::ResultSP
-lldb_perf::GetResult (const char *description, double value)
-{
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddDouble("value", NULL, value);
- return Results::ResultSP (value_dict_ap.release());
- }
- return Results::ResultSP (new Results::Double (NULL, NULL, value));
+lldb_perf::Results::ResultSP lldb_perf::GetResult(const char *description,
+ double value) {
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddDouble("value", NULL, value);
+ return Results::ResultSP(value_dict_ap.release());
+ }
+ return Results::ResultSP(new Results::Double(NULL, NULL, value));
}
template <>
-lldb_perf::Results::ResultSP
-lldb_perf::GetResult (const char *description, uint64_t value)
-{
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddUnsigned("value", NULL, value);
- return Results::ResultSP (value_dict_ap.release());
- }
- return Results::ResultSP (new Results::Unsigned (NULL, NULL, value));
+lldb_perf::Results::ResultSP lldb_perf::GetResult(const char *description,
+ uint64_t value) {
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddUnsigned("value", NULL, value);
+ return Results::ResultSP(value_dict_ap.release());
+ }
+ return Results::ResultSP(new Results::Unsigned(NULL, NULL, value));
}
template <>
-lldb_perf::Results::ResultSP
-lldb_perf::GetResult (const char *description, std::string value)
-{
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddString("value", NULL, value.c_str());
- return Results::ResultSP (value_dict_ap.release());
- }
- return Results::ResultSP (new Results::String (NULL, NULL, value.c_str()));
+lldb_perf::Results::ResultSP lldb_perf::GetResult(const char *description,
+ std::string value) {
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddString("value", NULL, value.c_str());
+ return Results::ResultSP(value_dict_ap.release());
+ }
+ return Results::ResultSP(new Results::String(NULL, NULL, value.c_str()));
}
Modified: lldb/trunk/tools/lldb-perf/lib/Gauge.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Gauge.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Gauge.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Gauge.h Tue Sep 6 15:57:50 2016
@@ -17,48 +17,35 @@
namespace lldb_perf {
-template <class T>
-class Gauge
-{
+template <class T> class Gauge {
public:
- typedef T ValueType;
+ typedef T ValueType;
+
+ Gauge() {}
+
+ virtual ~Gauge() {}
- Gauge ()
- {}
-
- virtual
- ~Gauge ()
- {}
-
- virtual void
- Start () = 0;
-
- virtual ValueType
- Stop () = 0;
+ virtual void Start() = 0;
- virtual ValueType
- GetStartValue () const = 0;
+ virtual ValueType Stop() = 0;
- virtual ValueType
- GetStopValue () const = 0;
+ virtual ValueType GetStartValue() const = 0;
- virtual ValueType
- GetDeltaValue () const = 0;
+ virtual ValueType GetStopValue() const = 0;
+ virtual ValueType GetDeltaValue() const = 0;
};
template <class T>
-Results::ResultSP GetResult (const char *description, T value);
+Results::ResultSP GetResult(const char *description, T value);
-template <>
-Results::ResultSP GetResult (const char *description, double value);
+template <> Results::ResultSP GetResult(const char *description, double value);
template <>
-Results::ResultSP GetResult (const char *description, uint64_t value);
+Results::ResultSP GetResult(const char *description, uint64_t value);
template <>
-Results::ResultSP GetResult (const char *description, std::string value);
-
+Results::ResultSP GetResult(const char *description, std::string value);
}
#endif
Modified: lldb/trunk/tools/lldb-perf/lib/Measurement.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Measurement.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Measurement.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Measurement.h Tue Sep 6 15:57:50 2016
@@ -11,207 +11,148 @@
#define __PerfTestDriver__Measurement__
#include "Gauge.h"
-#include "Timer.h"
-#include "Metric.h"
#include "MemoryGauge.h"
+#include "Metric.h"
+#include "Timer.h"
-namespace lldb_perf
-{
-template <typename GaugeType, typename Callable>
-class Measurement
-{
+namespace lldb_perf {
+template <typename GaugeType, typename Callable> class Measurement {
public:
- Measurement () :
- m_gauge (),
- m_callable (),
- m_metric ()
- {
- }
-
- Measurement (Callable callable, const char* name, const char* desc) :
- m_gauge (),
- m_callable (callable),
- m_metric (Metric<typename GaugeType::ValueType>(name, desc))
- {
- }
-
- Measurement (const char* name, const char* desc) :
- m_gauge (),
- m_callable (),
- m_metric (Metric<typename GaugeType::ValueType>(name, desc))
- {
- }
-
- template <typename GaugeType_Rhs, typename Callable_Rhs>
- Measurement (const Measurement<GaugeType_Rhs, Callable_Rhs>& rhs) :
- m_gauge(rhs.GetGauge()),
- m_callable(rhs.GetCallable()),
- m_metric(rhs.GetMetric())
- {
- }
+ Measurement() : m_gauge(), m_callable(), m_metric() {}
- template <typename... Args>
- void
- operator () (Args... args)
- {
- m_gauge.Start();
- m_callable(args...);
- m_metric.Append (m_gauge.Stop());
- }
-
- virtual const Callable&
- GetCallable () const
- {
- return m_callable;
- }
-
- virtual const GaugeType&
- GetGauge () const
- {
- return m_gauge;
- }
-
- virtual const Metric<typename GaugeType::ValueType>&
- GetMetric () const
- {
- return m_metric;
- }
-
- void
- Start ()
- {
- m_gauge.Start();
- }
-
- typename GaugeType::ValueType
- Stop ()
- {
- auto value = m_gauge.Stop();
- m_metric.Append(value);
- return value;
- }
-
- void
- WriteStartValue (Results &results)
- {
- auto metric = GetMetric ();
- results.GetDictionary().Add(metric.GetName(), metric.GetDescription(), lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetStartValue()));
- }
-
- void
- WriteStopValue (Results &results)
- {
- auto metric = GetMetric ();
- results.GetDictionary().Add(metric.GetName(), metric.GetDescription(), lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetStopValue()));
- }
-
- void
- WriteAverageValue (Results &results)
- {
- auto metric = GetMetric ();
- results.GetDictionary().Add(metric.GetName(), metric.GetDescription(), lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetAverage()));
- }
-
- void
- WriteAverageAndStandardDeviation (Results &results)
- {
- auto metric = GetMetric ();
- auto dictionary = (Results::Dictionary*)results.GetDictionary().Add(metric.GetName(), metric.GetDescription(), lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetAverage())).get();
- if (dictionary)
- {
- dictionary->Add("stddev", NULL, lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetStandardDeviation()));
- }
- }
-
- void
- WriteStandardDeviation (Results &results)
- {
- auto metric = GetMetric ();
- results.GetDictionary().Add(metric.GetName(), metric.GetDescription(), lldb_perf::GetResult<typename GaugeType::ValueType> (NULL, metric.GetStandardDeviation()));
- }
+ Measurement(Callable callable, const char *name, const char *desc)
+ : m_gauge(), m_callable(callable),
+ m_metric(Metric<typename GaugeType::ValueType>(name, desc)) {}
+
+ Measurement(const char *name, const char *desc)
+ : m_gauge(), m_callable(),
+ m_metric(Metric<typename GaugeType::ValueType>(name, desc)) {}
+
+ template <typename GaugeType_Rhs, typename Callable_Rhs>
+ Measurement(const Measurement<GaugeType_Rhs, Callable_Rhs> &rhs)
+ : m_gauge(rhs.GetGauge()), m_callable(rhs.GetCallable()),
+ m_metric(rhs.GetMetric()) {}
+
+ template <typename... Args> void operator()(Args... args) {
+ m_gauge.Start();
+ m_callable(args...);
+ m_metric.Append(m_gauge.Stop());
+ }
+
+ virtual const Callable &GetCallable() const { return m_callable; }
+
+ virtual const GaugeType &GetGauge() const { return m_gauge; }
+
+ virtual const Metric<typename GaugeType::ValueType> &GetMetric() const {
+ return m_metric;
+ }
+
+ void Start() { m_gauge.Start(); }
+
+ typename GaugeType::ValueType Stop() {
+ auto value = m_gauge.Stop();
+ m_metric.Append(value);
+ return value;
+ }
+
+ void WriteStartValue(Results &results) {
+ auto metric = GetMetric();
+ results.GetDictionary().Add(
+ metric.GetName(), metric.GetDescription(),
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetStartValue()));
+ }
+
+ void WriteStopValue(Results &results) {
+ auto metric = GetMetric();
+ results.GetDictionary().Add(
+ metric.GetName(), metric.GetDescription(),
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetStopValue()));
+ }
+
+ void WriteAverageValue(Results &results) {
+ auto metric = GetMetric();
+ results.GetDictionary().Add(
+ metric.GetName(), metric.GetDescription(),
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetAverage()));
+ }
+
+ void WriteAverageAndStandardDeviation(Results &results) {
+ auto metric = GetMetric();
+ auto dictionary =
+ (Results::Dictionary *)results.GetDictionary()
+ .Add(metric.GetName(), metric.GetDescription(),
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetAverage()))
+ .get();
+ if (dictionary) {
+ dictionary->Add("stddev", NULL,
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetStandardDeviation()));
+ }
+ }
+
+ void WriteStandardDeviation(Results &results) {
+ auto metric = GetMetric();
+ results.GetDictionary().Add(
+ metric.GetName(), metric.GetDescription(),
+ lldb_perf::GetResult<typename GaugeType::ValueType>(
+ NULL, metric.GetStandardDeviation()));
+ }
protected:
- GaugeType m_gauge;
- Callable m_callable;
- Metric<typename GaugeType::ValueType> m_metric;
+ GaugeType m_gauge;
+ Callable m_callable;
+ Metric<typename GaugeType::ValueType> m_metric;
};
-
+
template <typename Callable>
-class TimeMeasurement : public Measurement<TimeGauge,Callable>
-{
+class TimeMeasurement : public Measurement<TimeGauge, Callable> {
public:
- TimeMeasurement () :
- Measurement<TimeGauge,Callable> ()
- {
- }
-
- TimeMeasurement (Callable callable,
- const char* name = NULL,
- const char* descr = NULL) :
- Measurement<TimeGauge,Callable> (callable, name, descr)
- {
- }
-
- template <typename Callable_Rhs>
- TimeMeasurement (const TimeMeasurement<Callable_Rhs>& rhs) :
- Measurement<TimeGauge,Callable>(rhs)
- {
- }
-
- template <typename GaugeType_Rhs, typename Callable_Rhs>
- TimeMeasurement (const Measurement<GaugeType_Rhs, Callable_Rhs>& rhs) :
- Measurement<GaugeType_Rhs,Callable_Rhs>(rhs)
- {
- }
-
- template <typename... Args>
- void
- operator () (Args... args)
- {
- Measurement<TimeGauge,Callable>::operator()(args...);
- }
+ TimeMeasurement() : Measurement<TimeGauge, Callable>() {}
+
+ TimeMeasurement(Callable callable, const char *name = NULL,
+ const char *descr = NULL)
+ : Measurement<TimeGauge, Callable>(callable, name, descr) {}
+
+ template <typename Callable_Rhs>
+ TimeMeasurement(const TimeMeasurement<Callable_Rhs> &rhs)
+ : Measurement<TimeGauge, Callable>(rhs) {}
+
+ template <typename GaugeType_Rhs, typename Callable_Rhs>
+ TimeMeasurement(const Measurement<GaugeType_Rhs, Callable_Rhs> &rhs)
+ : Measurement<GaugeType_Rhs, Callable_Rhs>(rhs) {}
+
+ template <typename... Args> void operator()(Args... args) {
+ Measurement<TimeGauge, Callable>::operator()(args...);
+ }
};
template <typename Callable>
-class MemoryMeasurement : public Measurement<MemoryGauge,Callable>
-{
+class MemoryMeasurement : public Measurement<MemoryGauge, Callable> {
public:
- MemoryMeasurement () : Measurement<MemoryGauge,Callable> ()
- {
- }
-
- MemoryMeasurement (Callable callable,
- const char* name,
- const char* descr) :
- Measurement<MemoryGauge,Callable> (callable, name, descr)
- {
- }
+ MemoryMeasurement() : Measurement<MemoryGauge, Callable>() {}
- MemoryMeasurement (const char* name, const char* descr) :
- Measurement<MemoryGauge,Callable> (name, descr)
- {
- }
+ MemoryMeasurement(Callable callable, const char *name, const char *descr)
+ : Measurement<MemoryGauge, Callable>(callable, name, descr) {}
- template <typename Callable_Rhs>
- MemoryMeasurement (const MemoryMeasurement<Callable_Rhs>& rhs) :
- Measurement<MemoryGauge,Callable>(rhs)
- {
- }
-
- template <typename GaugeType_Rhs, typename Callable_Rhs>
- MemoryMeasurement (const Measurement<GaugeType_Rhs, Callable_Rhs>& rhs) :
- Measurement<GaugeType_Rhs,Callable_Rhs>(rhs)
- {
- }
-
- template <typename... Args>
- void
- operator () (Args... args)
- {
- Measurement<MemoryGauge,Callable>::operator()(args...);
- }
+ MemoryMeasurement(const char *name, const char *descr)
+ : Measurement<MemoryGauge, Callable>(name, descr) {}
+
+ template <typename Callable_Rhs>
+ MemoryMeasurement(const MemoryMeasurement<Callable_Rhs> &rhs)
+ : Measurement<MemoryGauge, Callable>(rhs) {}
+
+ template <typename GaugeType_Rhs, typename Callable_Rhs>
+ MemoryMeasurement(const Measurement<GaugeType_Rhs, Callable_Rhs> &rhs)
+ : Measurement<GaugeType_Rhs, Callable_Rhs>(rhs) {}
+
+ template <typename... Args> void operator()(Args... args) {
+ Measurement<MemoryGauge, Callable>::operator()(args...);
+ }
};
-
}
#endif /* defined(__PerfTestDriver__Measurement__) */
Modified: lldb/trunk/tools/lldb-perf/lib/MemoryGauge.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/MemoryGauge.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/MemoryGauge.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/MemoryGauge.cpp Tue Sep 6 15:57:50 2016
@@ -12,154 +12,122 @@
#include <assert.h>
#include <cmath>
#include <mach/mach.h>
-#include <mach/task.h>
#include <mach/mach_traps.h>
+#include <mach/task.h>
using namespace lldb_perf;
-MemoryStats::MemoryStats (mach_vm_size_t virtual_size,
- mach_vm_size_t resident_size,
- mach_vm_size_t max_resident_size) :
- m_virtual_size (virtual_size),
- m_resident_size (resident_size),
- m_max_resident_size (max_resident_size)
-{
-}
-
-MemoryStats::MemoryStats (const MemoryStats& rhs) :
- m_virtual_size (rhs.m_virtual_size),
- m_resident_size (rhs.m_resident_size),
- m_max_resident_size (rhs.m_max_resident_size)
-{
-}
-
-
-MemoryStats&
-MemoryStats::operator = (const MemoryStats& rhs)
-{
- if (this != &rhs)
- {
- m_virtual_size = rhs.m_virtual_size;
- m_resident_size = rhs.m_resident_size;
- m_max_resident_size = rhs.m_max_resident_size;
- }
- return *this;
-}
-
-MemoryStats&
-MemoryStats::operator += (const MemoryStats& rhs)
-{
- m_virtual_size += rhs.m_virtual_size;
- m_resident_size += rhs.m_resident_size;
- m_max_resident_size += rhs.m_max_resident_size;
- return *this;
-}
-
-MemoryStats
-MemoryStats::operator - (const MemoryStats& rhs)
-{
- return MemoryStats(m_virtual_size - rhs.m_virtual_size,
- m_resident_size - rhs.m_resident_size,
- m_max_resident_size - rhs.m_max_resident_size);
-}
-
-MemoryStats
-MemoryStats::operator + (const MemoryStats& rhs)
-{
- return MemoryStats(m_virtual_size + rhs.m_virtual_size,
- m_resident_size + rhs.m_resident_size,
- m_max_resident_size + rhs.m_max_resident_size);
-}
-
-MemoryStats
-MemoryStats::operator / (size_t n)
-{
- MemoryStats result(*this);
- result.m_virtual_size /= n;
- result.m_resident_size /= n;
- result.m_max_resident_size /= n;
- return result;
-}
-
-MemoryStats
-MemoryStats::operator * (const MemoryStats& rhs)
-{
- return MemoryStats(m_virtual_size * rhs.m_virtual_size,
- m_resident_size * rhs.m_resident_size,
- m_max_resident_size * rhs.m_max_resident_size);
-}
-
-Results::ResultSP
-MemoryStats::GetResult (const char *name, const char *description) const
-{
- std::unique_ptr<Results::Dictionary> dict_ap (new Results::Dictionary (name, NULL));
- dict_ap->AddUnsigned("resident", NULL, GetResidentSize());
- dict_ap->AddUnsigned("max_resident", NULL, GetMaxResidentSize());
- return Results::ResultSP(dict_ap.release());
-}
-
-MemoryGauge::ValueType
-MemoryGauge::Now ()
-{
- task_t task = mach_task_self();
- mach_task_basic_info_data_t taskBasicInfo;
- mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
- auto task_info_ret = task_info(task, MACH_TASK_BASIC_INFO, (task_info_t) & taskBasicInfo, &count);
- if (task_info_ret == KERN_SUCCESS) {
- return MemoryStats(taskBasicInfo.virtual_size, taskBasicInfo.resident_size, taskBasicInfo.resident_size_max);
- }
- return 0;
-}
-
-MemoryGauge::MemoryGauge () :
- m_state(MemoryGauge::State::eNeverUsed),
- m_start(),
- m_delta()
-{
-}
-
-void
-MemoryGauge::Start ()
-{
- m_state = MemoryGauge::State::eCounting;
- m_start = Now();
-}
-
-MemoryGauge::ValueType
-MemoryGauge::Stop ()
-{
- m_stop = Now();
- assert(m_state == MemoryGauge::State::eCounting && "cannot stop a non-started gauge");
- m_state = MemoryGauge::State::eStopped;
- m_delta = m_stop - m_start;
- return m_delta;
-}
-
-
-MemoryGauge::ValueType
-MemoryGauge::GetDeltaValue () const
-{
- assert(m_state == MemoryGauge::State::eStopped && "gauge must be used before you can evaluate it");
- return m_delta;
+MemoryStats::MemoryStats(mach_vm_size_t virtual_size,
+ mach_vm_size_t resident_size,
+ mach_vm_size_t max_resident_size)
+ : m_virtual_size(virtual_size), m_resident_size(resident_size),
+ m_max_resident_size(max_resident_size) {}
+
+MemoryStats::MemoryStats(const MemoryStats &rhs)
+ : m_virtual_size(rhs.m_virtual_size), m_resident_size(rhs.m_resident_size),
+ m_max_resident_size(rhs.m_max_resident_size) {}
+
+MemoryStats &MemoryStats::operator=(const MemoryStats &rhs) {
+ if (this != &rhs) {
+ m_virtual_size = rhs.m_virtual_size;
+ m_resident_size = rhs.m_resident_size;
+ m_max_resident_size = rhs.m_max_resident_size;
+ }
+ return *this;
+}
+
+MemoryStats &MemoryStats::operator+=(const MemoryStats &rhs) {
+ m_virtual_size += rhs.m_virtual_size;
+ m_resident_size += rhs.m_resident_size;
+ m_max_resident_size += rhs.m_max_resident_size;
+ return *this;
+}
+
+MemoryStats MemoryStats::operator-(const MemoryStats &rhs) {
+ return MemoryStats(m_virtual_size - rhs.m_virtual_size,
+ m_resident_size - rhs.m_resident_size,
+ m_max_resident_size - rhs.m_max_resident_size);
+}
+
+MemoryStats MemoryStats::operator+(const MemoryStats &rhs) {
+ return MemoryStats(m_virtual_size + rhs.m_virtual_size,
+ m_resident_size + rhs.m_resident_size,
+ m_max_resident_size + rhs.m_max_resident_size);
+}
+
+MemoryStats MemoryStats::operator/(size_t n) {
+ MemoryStats result(*this);
+ result.m_virtual_size /= n;
+ result.m_resident_size /= n;
+ result.m_max_resident_size /= n;
+ return result;
+}
+
+MemoryStats MemoryStats::operator*(const MemoryStats &rhs) {
+ return MemoryStats(m_virtual_size * rhs.m_virtual_size,
+ m_resident_size * rhs.m_resident_size,
+ m_max_resident_size * rhs.m_max_resident_size);
+}
+
+Results::ResultSP MemoryStats::GetResult(const char *name,
+ const char *description) const {
+ std::unique_ptr<Results::Dictionary> dict_ap(
+ new Results::Dictionary(name, NULL));
+ dict_ap->AddUnsigned("resident", NULL, GetResidentSize());
+ dict_ap->AddUnsigned("max_resident", NULL, GetMaxResidentSize());
+ return Results::ResultSP(dict_ap.release());
+}
+
+MemoryGauge::ValueType MemoryGauge::Now() {
+ task_t task = mach_task_self();
+ mach_task_basic_info_data_t taskBasicInfo;
+ mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
+ auto task_info_ret = task_info(task, MACH_TASK_BASIC_INFO,
+ (task_info_t)&taskBasicInfo, &count);
+ if (task_info_ret == KERN_SUCCESS) {
+ return MemoryStats(taskBasicInfo.virtual_size, taskBasicInfo.resident_size,
+ taskBasicInfo.resident_size_max);
+ }
+ return 0;
+}
+
+MemoryGauge::MemoryGauge()
+ : m_state(MemoryGauge::State::eNeverUsed), m_start(), m_delta() {}
+
+void MemoryGauge::Start() {
+ m_state = MemoryGauge::State::eCounting;
+ m_start = Now();
+}
+
+MemoryGauge::ValueType MemoryGauge::Stop() {
+ m_stop = Now();
+ assert(m_state == MemoryGauge::State::eCounting &&
+ "cannot stop a non-started gauge");
+ m_state = MemoryGauge::State::eStopped;
+ m_delta = m_stop - m_start;
+ return m_delta;
+}
+
+MemoryGauge::ValueType MemoryGauge::GetDeltaValue() const {
+ assert(m_state == MemoryGauge::State::eStopped &&
+ "gauge must be used before you can evaluate it");
+ return m_delta;
}
template <>
-Results::ResultSP
-lldb_perf::GetResult (const char *description, MemoryStats value)
-{
- return value.GetResult (NULL, description);
-}
-
-MemoryStats
-sqrt (const MemoryStats& arg)
-{
- long double virt_size = arg.GetVirtualSize();
- long double resident_size = arg.GetResidentSize();
- long double max_resident_size = arg.GetMaxResidentSize();
-
- virt_size = sqrtl(virt_size);
- resident_size = sqrtl(resident_size);
- max_resident_size = sqrtl(max_resident_size);
-
- return MemoryStats(virt_size,resident_size,max_resident_size);
+Results::ResultSP lldb_perf::GetResult(const char *description,
+ MemoryStats value) {
+ return value.GetResult(NULL, description);
+}
+
+MemoryStats sqrt(const MemoryStats &arg) {
+ long double virt_size = arg.GetVirtualSize();
+ long double resident_size = arg.GetResidentSize();
+ long double max_resident_size = arg.GetMaxResidentSize();
+
+ virt_size = sqrtl(virt_size);
+ resident_size = sqrtl(resident_size);
+ max_resident_size = sqrtl(max_resident_size);
+
+ return MemoryStats(virt_size, resident_size, max_resident_size);
}
Modified: lldb/trunk/tools/lldb-perf/lib/MemoryGauge.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/MemoryGauge.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/MemoryGauge.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/MemoryGauge.h Tue Sep 6 15:57:50 2016
@@ -17,131 +17,76 @@
namespace lldb_perf {
-class MemoryStats
-{
+class MemoryStats {
public:
- MemoryStats (mach_vm_size_t virtual_size = 0,
- mach_vm_size_t resident_size = 0,
- mach_vm_size_t max_resident_size = 0);
- MemoryStats (const MemoryStats& rhs);
-
- MemoryStats&
- operator = (const MemoryStats& rhs);
-
- MemoryStats&
- operator += (const MemoryStats& rhs);
-
- MemoryStats
- operator - (const MemoryStats& rhs);
-
- MemoryStats
- operator + (const MemoryStats& rhs);
-
- MemoryStats
- operator / (size_t rhs);
-
- MemoryStats
- operator * (const MemoryStats& rhs);
-
- mach_vm_size_t
- GetVirtualSize () const
- {
- return m_virtual_size;
- }
-
- mach_vm_size_t
- GetResidentSize () const
- {
- return m_resident_size;
- }
-
- mach_vm_size_t
- GetMaxResidentSize () const
- {
- return m_max_resident_size;
- }
-
- void
- SetVirtualSize (mach_vm_size_t vs)
- {
- m_virtual_size = vs;
- }
-
- void
- SetResidentSize (mach_vm_size_t rs)
- {
- m_resident_size = rs;
- }
-
- void
- SetMaxResidentSize (mach_vm_size_t mrs)
- {
- m_max_resident_size = mrs;
- }
-
- Results::ResultSP
- GetResult (const char *name, const char *description) const;
+ MemoryStats(mach_vm_size_t virtual_size = 0, mach_vm_size_t resident_size = 0,
+ mach_vm_size_t max_resident_size = 0);
+ MemoryStats(const MemoryStats &rhs);
+
+ MemoryStats &operator=(const MemoryStats &rhs);
+
+ MemoryStats &operator+=(const MemoryStats &rhs);
+
+ MemoryStats operator-(const MemoryStats &rhs);
+
+ MemoryStats operator+(const MemoryStats &rhs);
+
+ MemoryStats operator/(size_t rhs);
+
+ MemoryStats operator*(const MemoryStats &rhs);
+
+ mach_vm_size_t GetVirtualSize() const { return m_virtual_size; }
+
+ mach_vm_size_t GetResidentSize() const { return m_resident_size; }
+
+ mach_vm_size_t GetMaxResidentSize() const { return m_max_resident_size; }
+
+ void SetVirtualSize(mach_vm_size_t vs) { m_virtual_size = vs; }
+
+ void SetResidentSize(mach_vm_size_t rs) { m_resident_size = rs; }
+
+ void SetMaxResidentSize(mach_vm_size_t mrs) { m_max_resident_size = mrs; }
+
+ Results::ResultSP GetResult(const char *name, const char *description) const;
+
private:
- mach_vm_size_t m_virtual_size;
- mach_vm_size_t m_resident_size;
- mach_vm_size_t m_max_resident_size;
+ mach_vm_size_t m_virtual_size;
+ mach_vm_size_t m_resident_size;
+ mach_vm_size_t m_max_resident_size;
};
-
-class MemoryGauge : public Gauge<MemoryStats>
-{
+
+class MemoryGauge : public Gauge<MemoryStats> {
public:
- MemoryGauge ();
-
- virtual
- ~MemoryGauge ()
- {
- }
-
- void
- Start ();
-
- ValueType
- Stop ();
-
- virtual ValueType
- GetStartValue() const
- {
- return m_start;
- }
-
- virtual ValueType
- GetStopValue() const
- {
- return m_stop;
- }
+ MemoryGauge();
+
+ virtual ~MemoryGauge() {}
+
+ void Start();
+
+ ValueType Stop();
- virtual ValueType
- GetDeltaValue() const;
+ virtual ValueType GetStartValue() const { return m_start; }
+
+ virtual ValueType GetStopValue() const { return m_stop; }
+
+ virtual ValueType GetDeltaValue() const;
private:
- enum class State
- {
- eNeverUsed,
- eCounting,
- eStopped
- };
-
- ValueType
- Now ();
-
- State m_state;
- ValueType m_start;
- ValueType m_stop;
- ValueType m_delta;
+ enum class State { eNeverUsed, eCounting, eStopped };
+
+ ValueType Now();
+
+ State m_state;
+ ValueType m_start;
+ ValueType m_stop;
+ ValueType m_delta;
};
template <>
-Results::ResultSP
-GetResult (const char *description, MemoryStats value);
-
+Results::ResultSP GetResult(const char *description, MemoryStats value);
+
} // namespace lldb_perf
-lldb_perf::MemoryStats
-sqrt (const lldb_perf::MemoryStats& arg);
+lldb_perf::MemoryStats sqrt(const lldb_perf::MemoryStats &arg);
#endif // #ifndef __PerfTestDriver__MemoryGauge__
Modified: lldb/trunk/tools/lldb-perf/lib/Metric.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Metric.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Metric.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/Metric.cpp Tue Sep 6 15:57:50 2016
@@ -13,72 +13,47 @@
using namespace lldb_perf;
-template <class T>
-Metric<T>::Metric () : Metric ("")
-{
-}
+template <class T> Metric<T>::Metric() : Metric("") {}
template <class T>
-Metric<T>::Metric (const char* n, const char* d) :
- m_name(n ? n : ""),
- m_description(d ? d : ""),
- m_dataset ()
-{
-}
+Metric<T>::Metric(const char *n, const char *d)
+ : m_name(n ? n : ""), m_description(d ? d : ""), m_dataset() {}
-template <class T>
-void
-Metric<T>::Append (T v)
-{
- m_dataset.push_back(v);
-}
+template <class T> void Metric<T>::Append(T v) { m_dataset.push_back(v); }
-template <class T>
-size_t
-Metric<T>::GetCount () const
-{
- return m_dataset.size();
+template <class T> size_t Metric<T>::GetCount() const {
+ return m_dataset.size();
}
-template <class T>
-T
-Metric<T>::GetSum () const
-{
- T sum = 0;
- for (auto v : m_dataset)
- sum += v;
- return sum;
+template <class T> T Metric<T>::GetSum() const {
+ T sum = 0;
+ for (auto v : m_dataset)
+ sum += v;
+ return sum;
}
-template <class T>
-T
-Metric<T>::GetAverage () const
-{
- return GetSum()/GetCount();
+template <class T> T Metric<T>::GetAverage() const {
+ return GetSum() / GetCount();
}
-
// Knuth's algorithm for stddev - massive cancellation resistant
template <class T>
-T
-Metric<T>::GetStandardDeviation (StandardDeviationMode mode) const
-{
- size_t n = 0;
- T mean = 0;
- T M2 = 0;
- for (auto x : m_dataset)
- {
- n = n + 1;
- T delta = x - mean;
- mean = mean + delta/n;
- M2 = M2+delta*(x-mean);
- }
- T variance;
- if (mode == StandardDeviationMode::ePopulation || n == 1)
- variance = M2 / n;
- else
- variance = M2 / (n - 1);
- return sqrt(variance);
+T Metric<T>::GetStandardDeviation(StandardDeviationMode mode) const {
+ size_t n = 0;
+ T mean = 0;
+ T M2 = 0;
+ for (auto x : m_dataset) {
+ n = n + 1;
+ T delta = x - mean;
+ mean = mean + delta / n;
+ M2 = M2 + delta * (x - mean);
+ }
+ T variance;
+ if (mode == StandardDeviationMode::ePopulation || n == 1)
+ variance = M2 / n;
+ else
+ variance = M2 / (n - 1);
+ return sqrt(variance);
}
template class lldb_perf::Metric<double>;
Modified: lldb/trunk/tools/lldb-perf/lib/Metric.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Metric.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Metric.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Metric.h Tue Sep 6 15:57:50 2016
@@ -10,62 +10,48 @@
#ifndef __PerfTestDriver__Metric__
#define __PerfTestDriver__Metric__
-#include <vector>
-#include <string>
#include <mach/task_info.h>
+#include <string>
+#include <vector>
namespace lldb_perf {
class MemoryStats;
-template <class ValueType>
-class Metric
-{
+template <class ValueType> class Metric {
public:
- enum class StandardDeviationMode
- {
- eSample,
- ePopulation
- };
-
- Metric ();
- Metric (const char*, const char* = NULL);
-
- void
- Append (ValueType v);
-
- ValueType
- GetAverage () const;
-
- size_t
- GetCount () const;
-
- ValueType
- GetSum () const;
-
- ValueType
- GetStandardDeviation (StandardDeviationMode mode = StandardDeviationMode::ePopulation) const;
-
- const char*
- GetName () const
- {
- if (m_name.empty())
- return NULL;
- return m_name.c_str();
- }
-
- const char*
- GetDescription () const
- {
- if (m_description.empty())
- return NULL;
- return m_description.c_str();
- }
+ enum class StandardDeviationMode { eSample, ePopulation };
+
+ Metric();
+ Metric(const char *, const char * = NULL);
+
+ void Append(ValueType v);
+
+ ValueType GetAverage() const;
+
+ size_t GetCount() const;
+
+ ValueType GetSum() const;
+
+ ValueType GetStandardDeviation(
+ StandardDeviationMode mode = StandardDeviationMode::ePopulation) const;
+
+ const char *GetName() const {
+ if (m_name.empty())
+ return NULL;
+ return m_name.c_str();
+ }
+
+ const char *GetDescription() const {
+ if (m_description.empty())
+ return NULL;
+ return m_description.c_str();
+ }
private:
- std::string m_name;
- std::string m_description;
- std::vector<ValueType> m_dataset;
+ std::string m_name;
+ std::string m_description;
+ std::vector<ValueType> m_dataset;
};
}
Modified: lldb/trunk/tools/lldb-perf/lib/Results.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Results.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Results.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/Results.cpp Tue Sep 6 15:57:50 2016
@@ -19,257 +19,221 @@
using namespace lldb_perf;
-static void
-AddResultToArray (CFCMutableArray &array, Results::Result *result);
+static void AddResultToArray(CFCMutableArray &array, Results::Result *result);
-static void
-AddResultToDictionary (CFCMutableDictionary &parent_dict, const char *key, Results::Result *result);
+static void AddResultToDictionary(CFCMutableDictionary &parent_dict,
+ const char *key, Results::Result *result);
-static void
-AddResultToArray (CFCMutableArray &parent_array, Results::Result *result)
-{
- switch (result->GetType())
- {
- case Results::Result::Type::Invalid:
- break;
-
- case Results::Result::Type::Array:
- {
- Results::Array *value = result->GetAsArray();
- CFCMutableArray array;
- value->ForEach([&array](const Results::ResultSP &value_sp) -> bool
- {
- AddResultToArray (array, value_sp.get());
- return true;
- });
- parent_array.AppendValue(array.get(), true);
- }
- break;
-
- case Results::Result::Type::Dictionary:
- {
- Results::Dictionary *value = result->GetAsDictionary();
- CFCMutableDictionary dict;
- value->ForEach([&dict](const std::string &key, const Results::ResultSP &value_sp) -> bool
- {
- AddResultToDictionary (dict, key.c_str(), value_sp.get());
- return true;
- });
- if (result->GetDescription())
- {
- dict.AddValueCString(CFSTR("description"), result->GetDescription());
- }
- parent_array.AppendValue(dict.get(), true);
- }
- break;
-
- case Results::Result::Type::Double:
- {
- double d = result->GetAsDouble()->GetValue();
- CFCReleaser<CFNumberRef> cf_number(::CFNumberCreate (kCFAllocatorDefault, kCFNumberDoubleType, &d));
- if (cf_number.get())
- parent_array.AppendValue(cf_number.get(), true);
- }
- break;
- case Results::Result::Type::String:
- {
- CFCString cfstr (result->GetAsString()->GetValue());
- if (cfstr.get())
- parent_array.AppendValue(cfstr.get(), true);
- }
- break;
-
- case Results::Result::Type::Unsigned:
- {
- uint64_t uval64 = result->GetAsUnsigned()->GetValue();
- CFCReleaser<CFNumberRef> cf_number(::CFNumberCreate (kCFAllocatorDefault, kCFNumberSInt64Type, &uval64));
- if (cf_number.get())
- parent_array.AppendValue(cf_number.get(), true);
- }
- break;
-
- default:
- assert (!"unhandled result");
- break;
- }
-}
+static void AddResultToArray(CFCMutableArray &parent_array,
+ Results::Result *result) {
+ switch (result->GetType()) {
+ case Results::Result::Type::Invalid:
+ break;
+
+ case Results::Result::Type::Array: {
+ Results::Array *value = result->GetAsArray();
+ CFCMutableArray array;
+ value->ForEach([&array](const Results::ResultSP &value_sp) -> bool {
+ AddResultToArray(array, value_sp.get());
+ return true;
+ });
+ parent_array.AppendValue(array.get(), true);
+ } break;
-
-static void
-AddResultToDictionary (CFCMutableDictionary &parent_dict, const char *key, Results::Result *result)
-{
- assert (key && key[0]);
- CFCString cf_key(key);
- switch (result->GetType())
- {
- case Results::Result::Type::Invalid:
- break;
-
- case Results::Result::Type::Array:
- {
- Results::Array *value = result->GetAsArray();
- CFCMutableArray array;
- value->ForEach([&array](const Results::ResultSP &value_sp) -> bool
- {
- AddResultToArray (array, value_sp.get());
- return true;
- });
- parent_dict.AddValue(cf_key.get(), array.get(), true);
- }
- break;
- case Results::Result::Type::Dictionary:
- {
- Results::Dictionary *value = result->GetAsDictionary();
- CFCMutableDictionary dict;
- value->ForEach([&dict](const std::string &key, const Results::ResultSP &value_sp) -> bool
- {
- AddResultToDictionary (dict, key.c_str(), value_sp.get());
- return true;
- });
- if (result->GetDescription())
- {
- dict.AddValueCString(CFSTR("description"), result->GetDescription());
- }
- parent_dict.AddValue(cf_key.get(), dict.get(), true);
- }
- break;
- case Results::Result::Type::Double:
- {
- parent_dict.SetValueDouble(cf_key.get(), result->GetAsDouble()->GetValue(), true);
- }
- break;
- case Results::Result::Type::String:
- {
- parent_dict.SetValueCString(cf_key.get(), result->GetAsString()->GetValue(), true);
- }
- break;
-
- case Results::Result::Type::Unsigned:
- {
- parent_dict.SetValueUInt64 (cf_key.get(), result->GetAsUnsigned()->GetValue(), true);
- }
- break;
- default:
- assert (!"unhandled result");
- break;
- }
-}
-void
-Results::Write (const char *out_path)
-{
-#ifdef __APPLE__
+ case Results::Result::Type::Dictionary: {
+ Results::Dictionary *value = result->GetAsDictionary();
CFCMutableDictionary dict;
-
- m_results.ForEach([&dict](const std::string &key, const ResultSP &value_sp) -> bool
- {
- AddResultToDictionary (dict, key.c_str(), value_sp.get());
- return true;
- });
- CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, dict.get(), kCFPropertyListXMLFormat_v1_0, 0, NULL);
-
- if (out_path == NULL)
- out_path = "/dev/stdout";
-
- CFURLRef file = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8*)out_path, strlen(out_path), FALSE);
-
- CFURLWriteDataAndPropertiesToResource(file, xmlData, NULL, NULL);
-#endif
-}
-
-Results::ResultSP
-Results::Dictionary::AddUnsigned (const char *name, const char *description, uint64_t value)
-{
- assert (name && name[0]);
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddUnsigned("value", NULL, value);
- m_dictionary[std::string(name)] = ResultSP (value_dict_ap.release());
- }
- else
- m_dictionary[std::string(name)] = ResultSP (new Unsigned (name, description, value));
- return m_dictionary[std::string(name)];
-}
-
-Results::ResultSP
-Results::Dictionary::AddDouble (const char *name, const char *description, double value)
-{
- assert (name && name[0]);
-
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddDouble("value", NULL, value);
- m_dictionary[std::string(name)] = ResultSP (value_dict_ap.release());
- }
- else
- m_dictionary[std::string(name)] = ResultSP (new Double (name, description, value));
- return m_dictionary[std::string(name)];
-}
-Results::ResultSP
-Results::Dictionary::AddString (const char *name, const char *description, const char *value)
-{
- assert (name && name[0]);
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->AddString("value", NULL, value);
- m_dictionary[std::string(name)] = ResultSP (value_dict_ap.release());
- }
- else
- m_dictionary[std::string(name)] = ResultSP (new String (name, description, value));
- return m_dictionary[std::string(name)];
+ value->ForEach([&dict](const std::string &key,
+ const Results::ResultSP &value_sp) -> bool {
+ AddResultToDictionary(dict, key.c_str(), value_sp.get());
+ return true;
+ });
+ if (result->GetDescription()) {
+ dict.AddValueCString(CFSTR("description"), result->GetDescription());
+ }
+ parent_array.AppendValue(dict.get(), true);
+ } break;
+
+ case Results::Result::Type::Double: {
+ double d = result->GetAsDouble()->GetValue();
+ CFCReleaser<CFNumberRef> cf_number(
+ ::CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &d));
+ if (cf_number.get())
+ parent_array.AppendValue(cf_number.get(), true);
+ } break;
+ case Results::Result::Type::String: {
+ CFCString cfstr(result->GetAsString()->GetValue());
+ if (cfstr.get())
+ parent_array.AppendValue(cfstr.get(), true);
+ } break;
+
+ case Results::Result::Type::Unsigned: {
+ uint64_t uval64 = result->GetAsUnsigned()->GetValue();
+ CFCReleaser<CFNumberRef> cf_number(
+ ::CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &uval64));
+ if (cf_number.get())
+ parent_array.AppendValue(cf_number.get(), true);
+ } break;
+
+ default:
+ assert(!"unhandled result");
+ break;
+ }
+}
+
+static void AddResultToDictionary(CFCMutableDictionary &parent_dict,
+ const char *key, Results::Result *result) {
+ assert(key && key[0]);
+ CFCString cf_key(key);
+ switch (result->GetType()) {
+ case Results::Result::Type::Invalid:
+ break;
+
+ case Results::Result::Type::Array: {
+ Results::Array *value = result->GetAsArray();
+ CFCMutableArray array;
+ value->ForEach([&array](const Results::ResultSP &value_sp) -> bool {
+ AddResultToArray(array, value_sp.get());
+ return true;
+ });
+ parent_dict.AddValue(cf_key.get(), array.get(), true);
+ } break;
+ case Results::Result::Type::Dictionary: {
+ Results::Dictionary *value = result->GetAsDictionary();
+ CFCMutableDictionary dict;
+ value->ForEach([&dict](const std::string &key,
+ const Results::ResultSP &value_sp) -> bool {
+ AddResultToDictionary(dict, key.c_str(), value_sp.get());
+ return true;
+ });
+ if (result->GetDescription()) {
+ dict.AddValueCString(CFSTR("description"), result->GetDescription());
+ }
+ parent_dict.AddValue(cf_key.get(), dict.get(), true);
+ } break;
+ case Results::Result::Type::Double: {
+ parent_dict.SetValueDouble(cf_key.get(), result->GetAsDouble()->GetValue(),
+ true);
+ } break;
+ case Results::Result::Type::String: {
+ parent_dict.SetValueCString(cf_key.get(), result->GetAsString()->GetValue(),
+ true);
+ } break;
+
+ case Results::Result::Type::Unsigned: {
+ parent_dict.SetValueUInt64(cf_key.get(),
+ result->GetAsUnsigned()->GetValue(), true);
+ } break;
+ default:
+ assert(!"unhandled result");
+ break;
+ }
}
+void Results::Write(const char *out_path) {
+#ifdef __APPLE__
+ CFCMutableDictionary dict;
-Results::ResultSP
-Results::Dictionary::Add (const char *name, const char *description, const ResultSP &result_sp)
-{
- assert (name && name[0]);
- if (description && description[0])
- {
- std::unique_ptr<Results::Dictionary> value_dict_ap (new Results::Dictionary ());
- value_dict_ap->AddString("description", NULL, description);
- value_dict_ap->Add("value", NULL, result_sp);
- m_dictionary[std::string(name)] = ResultSP (value_dict_ap.release());
- }
- else
- m_dictionary[std::string(name)] = result_sp;
- return m_dictionary[std::string(name)];
-}
+ m_results.ForEach(
+ [&dict](const std::string &key, const ResultSP &value_sp) -> bool {
+ AddResultToDictionary(dict, key.c_str(), value_sp.get());
+ return true;
+ });
+ CFDataRef xmlData = CFPropertyListCreateData(
+ kCFAllocatorDefault, dict.get(), kCFPropertyListXMLFormat_v1_0, 0, NULL);
-void
-Results::Dictionary::ForEach (const std::function <bool (const std::string &, const ResultSP &)> &callback)
-{
- collection::const_iterator pos, end = m_dictionary.end();
- for (pos = m_dictionary.begin(); pos != end; ++pos)
- {
- if (callback (pos->first.c_str(), pos->second) == false)
- return;
- }
-}
+ if (out_path == NULL)
+ out_path = "/dev/stdout";
+ CFURLRef file = CFURLCreateFromFileSystemRepresentation(
+ NULL, (const UInt8 *)out_path, strlen(out_path), FALSE);
-
-Results::ResultSP
-Results::Array::Append (const ResultSP &result_sp)
-{
- m_array.push_back (result_sp);
- return result_sp;
+ CFURLWriteDataAndPropertiesToResource(file, xmlData, NULL, NULL);
+#endif
}
-void
-Results::Array::ForEach (const std::function <bool (const ResultSP &)> &callback)
-{
- collection::const_iterator pos, end = m_array.end();
- for (pos = m_array.begin(); pos != end; ++pos)
- {
- if (callback (*pos) == false)
- return;
- }
+Results::ResultSP Results::Dictionary::AddUnsigned(const char *name,
+ const char *description,
+ uint64_t value) {
+ assert(name && name[0]);
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddUnsigned("value", NULL, value);
+ m_dictionary[std::string(name)] = ResultSP(value_dict_ap.release());
+ } else
+ m_dictionary[std::string(name)] =
+ ResultSP(new Unsigned(name, description, value));
+ return m_dictionary[std::string(name)];
+}
+
+Results::ResultSP Results::Dictionary::AddDouble(const char *name,
+ const char *description,
+ double value) {
+ assert(name && name[0]);
+
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddDouble("value", NULL, value);
+ m_dictionary[std::string(name)] = ResultSP(value_dict_ap.release());
+ } else
+ m_dictionary[std::string(name)] =
+ ResultSP(new Double(name, description, value));
+ return m_dictionary[std::string(name)];
+}
+Results::ResultSP Results::Dictionary::AddString(const char *name,
+ const char *description,
+ const char *value) {
+ assert(name && name[0]);
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->AddString("value", NULL, value);
+ m_dictionary[std::string(name)] = ResultSP(value_dict_ap.release());
+ } else
+ m_dictionary[std::string(name)] =
+ ResultSP(new String(name, description, value));
+ return m_dictionary[std::string(name)];
+}
+
+Results::ResultSP Results::Dictionary::Add(const char *name,
+ const char *description,
+ const ResultSP &result_sp) {
+ assert(name && name[0]);
+ if (description && description[0]) {
+ std::unique_ptr<Results::Dictionary> value_dict_ap(
+ new Results::Dictionary());
+ value_dict_ap->AddString("description", NULL, description);
+ value_dict_ap->Add("value", NULL, result_sp);
+ m_dictionary[std::string(name)] = ResultSP(value_dict_ap.release());
+ } else
+ m_dictionary[std::string(name)] = result_sp;
+ return m_dictionary[std::string(name)];
+}
+
+void Results::Dictionary::ForEach(
+ const std::function<bool(const std::string &, const ResultSP &)>
+ &callback) {
+ collection::const_iterator pos, end = m_dictionary.end();
+ for (pos = m_dictionary.begin(); pos != end; ++pos) {
+ if (callback(pos->first.c_str(), pos->second) == false)
+ return;
+ }
+}
+
+Results::ResultSP Results::Array::Append(const ResultSP &result_sp) {
+ m_array.push_back(result_sp);
+ return result_sp;
+}
+
+void Results::Array::ForEach(
+ const std::function<bool(const ResultSP &)> &callback) {
+ collection::const_iterator pos, end = m_array.end();
+ for (pos = m_array.begin(); pos != end; ++pos) {
+ if (callback(*pos) == false)
+ return;
+ }
}
-
-
-
Modified: lldb/trunk/tools/lldb-perf/lib/Results.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Results.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Results.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Results.h Tue Sep 6 15:57:50 2016
@@ -17,296 +17,189 @@
namespace lldb_perf {
-class Results
-{
+class Results {
public:
- class Array;
- class Dictionary;
- class Double;
- class String;
- class Unsigned;
-
- class Result
- {
- public:
- enum class Type
- {
- Invalid,
- Array,
- Dictionary,
- Double,
- String,
- Unsigned
- };
-
- Result (Type type, const char *name, const char *description) :
- m_name (),
- m_description(),
- m_type (type)
- {
- if (name && name[0])
- m_name = name;
- if (description && description[0])
- m_description = description;
- }
-
- virtual
- ~Result()
- {
- }
-
- virtual void
- Write (Results &results) = 0;
-
- Array *
- GetAsArray ()
- {
- if (m_type == Type::Array)
- return (Array *)this;
- return NULL;
- }
- Dictionary *
- GetAsDictionary ()
- {
- if (m_type == Type::Dictionary)
- return (Dictionary *)this;
- return NULL;
- }
- Double *
- GetAsDouble ()
- {
- if (m_type == Type::Double)
- return (Double *)this;
- return NULL;
- }
-
- String *
- GetAsString ()
- {
- if (m_type == Type::String)
- return (String *)this;
- return NULL;
- }
- Unsigned *
- GetAsUnsigned ()
- {
- if (m_type == Type::Unsigned)
- return (Unsigned *)this;
- return NULL;
- }
-
- const char *
- GetName() const
- {
- if (m_name.empty())
- return NULL;
- return m_name.c_str();
- }
-
- const char *
- GetDescription() const
- {
- if (m_description.empty())
- return NULL;
- return m_description.c_str();
- }
-
- Type
- GetType() const
- {
- return m_type;
- }
-
- protected:
- std::string m_name;
- std::string m_description;
- Type m_type;
- };
-
- typedef std::shared_ptr<Result> ResultSP;
-
- class Array : public Result
- {
- public:
- Array (const char *name, const char *description) :
- Result (Type::Array, name, description)
- {
- }
-
- virtual
- ~Array()
- {
- }
-
- ResultSP
- Append (const ResultSP &result_sp);
-
- void
- ForEach (const std::function <bool (const ResultSP &)> &callback);
-
- virtual void
- Write (Results &results)
- {
- }
- protected:
- typedef std::vector<ResultSP> collection;
- collection m_array;
- };
-
- class Dictionary : public Result
- {
- public:
- Dictionary () :
- Result (Type::Dictionary, NULL, NULL)
- {
- }
-
- Dictionary (const char *name, const char *description) :
- Result (Type::Dictionary, name, description)
- {
- }
-
- virtual
- ~Dictionary()
- {
- }
-
- virtual void
- Write (Results &results)
- {
- }
-
- void
- ForEach (const std::function <bool (const std::string &, const ResultSP &)> &callback);
-
- ResultSP
- Add (const char *name, const char *description, const ResultSP &result_sp);
-
- ResultSP
- AddDouble (const char *name, const char *descriptiorn, double value);
-
- ResultSP
- AddUnsigned (const char *name, const char *description, uint64_t value);
-
- ResultSP
- AddString (const char *name, const char *description, const char *value);
-
- protected:
-
- typedef std::map<std::string, ResultSP> collection;
- collection m_dictionary;
- };
-
- class String : public Result
- {
- public:
- String (const char *name, const char *description, const char *value) :
- Result (Type::String, name, description),
- m_string ()
- {
- if (value && value[0])
- m_string = value;
- }
-
- virtual
- ~String()
- {
- }
-
- virtual void
- Write (Results &results)
- {
- }
-
- const char *
- GetValue () const
- {
- return m_string.empty() ? NULL : m_string.c_str();
- }
-
- protected:
- std::string m_string;
- };
-
- class Double : public Result
- {
- public:
- Double (const char *name, const char *description, double value) :
- Result (Type::Double, name, description),
- m_double (value)
- {
- }
-
- virtual
- ~Double()
- {
- }
-
- virtual void
- Write (Results &results)
- {
- }
-
- double
- GetValue () const
- {
- return m_double;
- }
-
- protected:
- double m_double;
- };
-
- class Unsigned : public Result
- {
- public:
- Unsigned (const char *name, const char *description, uint64_t value) :
- Result (Type::Unsigned, name, description),
- m_unsigned (value)
- {
- }
-
- virtual
- ~Unsigned()
- {
- }
-
- virtual void
- Write (Results &results)
- {
- }
-
- uint64_t
- GetValue () const
- {
- return m_unsigned;
- }
-
- protected:
- uint64_t m_unsigned;
- };
-
- Results () :
- m_results ()
- {
+ class Array;
+ class Dictionary;
+ class Double;
+ class String;
+ class Unsigned;
+
+ class Result {
+ public:
+ enum class Type { Invalid, Array, Dictionary, Double, String, Unsigned };
+
+ Result(Type type, const char *name, const char *description)
+ : m_name(), m_description(), m_type(type) {
+ if (name && name[0])
+ m_name = name;
+ if (description && description[0])
+ m_description = description;
}
-
- ~Results()
- {
+
+ virtual ~Result() {}
+
+ virtual void Write(Results &results) = 0;
+
+ Array *GetAsArray() {
+ if (m_type == Type::Array)
+ return (Array *)this;
+ return NULL;
+ }
+ Dictionary *GetAsDictionary() {
+ if (m_type == Type::Dictionary)
+ return (Dictionary *)this;
+ return NULL;
+ }
+ Double *GetAsDouble() {
+ if (m_type == Type::Double)
+ return (Double *)this;
+ return NULL;
+ }
+
+ String *GetAsString() {
+ if (m_type == Type::String)
+ return (String *)this;
+ return NULL;
+ }
+ Unsigned *GetAsUnsigned() {
+ if (m_type == Type::Unsigned)
+ return (Unsigned *)this;
+ return NULL;
+ }
+
+ const char *GetName() const {
+ if (m_name.empty())
+ return NULL;
+ return m_name.c_str();
+ }
+
+ const char *GetDescription() const {
+ if (m_description.empty())
+ return NULL;
+ return m_description.c_str();
+ }
+
+ Type GetType() const { return m_type; }
+
+ protected:
+ std::string m_name;
+ std::string m_description;
+ Type m_type;
+ };
+
+ typedef std::shared_ptr<Result> ResultSP;
+
+ class Array : public Result {
+ public:
+ Array(const char *name, const char *description)
+ : Result(Type::Array, name, description) {}
+
+ virtual ~Array() {}
+
+ ResultSP Append(const ResultSP &result_sp);
+
+ void ForEach(const std::function<bool(const ResultSP &)> &callback);
+
+ virtual void Write(Results &results) {}
+
+ protected:
+ typedef std::vector<ResultSP> collection;
+ collection m_array;
+ };
+
+ class Dictionary : public Result {
+ public:
+ Dictionary() : Result(Type::Dictionary, NULL, NULL) {}
+
+ Dictionary(const char *name, const char *description)
+ : Result(Type::Dictionary, name, description) {}
+
+ virtual ~Dictionary() {}
+
+ virtual void Write(Results &results) {}
+
+ void ForEach(const std::function<bool(const std::string &,
+ const ResultSP &)> &callback);
+
+ ResultSP Add(const char *name, const char *description,
+ const ResultSP &result_sp);
+
+ ResultSP AddDouble(const char *name, const char *descriptiorn,
+ double value);
+
+ ResultSP AddUnsigned(const char *name, const char *description,
+ uint64_t value);
+
+ ResultSP AddString(const char *name, const char *description,
+ const char *value);
+
+ protected:
+ typedef std::map<std::string, ResultSP> collection;
+ collection m_dictionary;
+ };
+
+ class String : public Result {
+ public:
+ String(const char *name, const char *description, const char *value)
+ : Result(Type::String, name, description), m_string() {
+ if (value && value[0])
+ m_string = value;
}
-
- Dictionary &
- GetDictionary ()
- {
- return m_results;
+
+ virtual ~String() {}
+
+ virtual void Write(Results &results) {}
+
+ const char *GetValue() const {
+ return m_string.empty() ? NULL : m_string.c_str();
}
- void
- Write (const char *path);
-
+ protected:
+ std::string m_string;
+ };
+
+ class Double : public Result {
+ public:
+ Double(const char *name, const char *description, double value)
+ : Result(Type::Double, name, description), m_double(value) {}
+
+ virtual ~Double() {}
+
+ virtual void Write(Results &results) {}
+
+ double GetValue() const { return m_double; }
+
+ protected:
+ double m_double;
+ };
+
+ class Unsigned : public Result {
+ public:
+ Unsigned(const char *name, const char *description, uint64_t value)
+ : Result(Type::Unsigned, name, description), m_unsigned(value) {}
+
+ virtual ~Unsigned() {}
+
+ virtual void Write(Results &results) {}
+
+ uint64_t GetValue() const { return m_unsigned; }
+
+ protected:
+ uint64_t m_unsigned;
+ };
+
+ Results() : m_results() {}
+
+ ~Results() {}
+
+ Dictionary &GetDictionary() { return m_results; }
+
+ void Write(const char *path);
+
protected:
- Dictionary m_results;
+ Dictionary m_results;
};
-
+
} // namespace lldb_perf
#endif // #ifndef __PerfTestDriver_Results_h__
Modified: lldb/trunk/tools/lldb-perf/lib/TestCase.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/TestCase.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/TestCase.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/TestCase.cpp Tue Sep 6 15:57:50 2016
@@ -13,346 +13,296 @@
using namespace lldb_perf;
-TestCase::TestCase () :
- m_debugger(),
- m_target(),
- m_process(),
- m_thread(),
- m_listener(),
- m_verbose(false),
- m_step(0)
-{
- SBDebugger::Initialize();
- SBHostOS::ThreadCreated ("<lldb-tester.app.main>");
- m_debugger = SBDebugger::Create(false);
- m_listener = m_debugger.GetListener();
- m_listener.StartListeningForEventClass (m_debugger, SBProcess::GetBroadcasterClass(), SBProcess::eBroadcastBitStateChanged | SBProcess::eBroadcastBitInterrupt);
+TestCase::TestCase()
+ : m_debugger(), m_target(), m_process(), m_thread(), m_listener(),
+ m_verbose(false), m_step(0) {
+ SBDebugger::Initialize();
+ SBHostOS::ThreadCreated("<lldb-tester.app.main>");
+ m_debugger = SBDebugger::Create(false);
+ m_listener = m_debugger.GetListener();
+ m_listener.StartListeningForEventClass(
+ m_debugger, SBProcess::GetBroadcasterClass(),
+ SBProcess::eBroadcastBitStateChanged | SBProcess::eBroadcastBitInterrupt);
}
-static std::string
-GetShortOptionString (struct option *long_options)
-{
- std::string option_string;
- for (int i = 0; long_options[i].name != NULL; ++i)
- {
- if (long_options[i].flag == NULL)
- {
- option_string.push_back ((char) long_options[i].val);
- switch (long_options[i].has_arg)
- {
- default:
- case no_argument:
- break;
- case required_argument:
- option_string.push_back (':');
- break;
- case optional_argument:
- option_string.append (2, ':');
- break;
- }
- }
+static std::string GetShortOptionString(struct option *long_options) {
+ std::string option_string;
+ for (int i = 0; long_options[i].name != NULL; ++i) {
+ if (long_options[i].flag == NULL) {
+ option_string.push_back((char)long_options[i].val);
+ switch (long_options[i].has_arg) {
+ default:
+ case no_argument:
+ break;
+ case required_argument:
+ option_string.push_back(':');
+ break;
+ case optional_argument:
+ option_string.append(2, ':');
+ break;
+ }
}
- return option_string;
+ }
+ return option_string;
}
-bool
-TestCase::Setup (int& argc, const char**& argv)
-{
- bool done = false;
-
- struct option* long_options = GetLongOptions();
-
- if (long_options)
- {
- std::string short_option_string (GetShortOptionString(long_options));
-
- #if __GLIBC__
- optind = 0;
- #else
- optreset = 1;
- optind = 1;
- #endif
- while (!done)
- {
- int long_options_index = -1;
- const int short_option = ::getopt_long_only (argc,
- const_cast<char **>(argv),
- short_option_string.c_str(),
- long_options,
- &long_options_index);
-
- switch (short_option)
- {
- case 0:
- // Already handled
- break;
-
- case -1:
- done = true;
- break;
-
- default:
- done = !ParseOption(short_option, optarg);
- break;
- }
- }
- argc -= optind;
- argv += optind;
+bool TestCase::Setup(int &argc, const char **&argv) {
+ bool done = false;
+
+ struct option *long_options = GetLongOptions();
+
+ if (long_options) {
+ std::string short_option_string(GetShortOptionString(long_options));
+
+#if __GLIBC__
+ optind = 0;
+#else
+ optreset = 1;
+ optind = 1;
+#endif
+ while (!done) {
+ int long_options_index = -1;
+ const int short_option = ::getopt_long_only(
+ argc, const_cast<char **>(argv), short_option_string.c_str(),
+ long_options, &long_options_index);
+
+ switch (short_option) {
+ case 0:
+ // Already handled
+ break;
+
+ case -1:
+ done = true;
+ break;
+
+ default:
+ done = !ParseOption(short_option, optarg);
+ break;
+ }
}
-
- return false;
-}
+ argc -= optind;
+ argv += optind;
+ }
-bool
-TestCase::Launch (lldb::SBLaunchInfo &launch_info)
-{
- lldb::SBError error;
- m_process = m_target.Launch (launch_info, error);
- if (!error.Success())
- fprintf (stderr, "error: %s\n", error.GetCString());
- if (m_process.IsValid())
- return true;
- return false;
+ return false;
}
-bool
-TestCase::Launch (std::initializer_list<const char*> args)
-{
- std::vector<const char*> args_vect(args);
- args_vect.push_back(NULL);
- lldb::SBLaunchInfo launch_info((const char**)&args_vect[0]);
- return Launch(launch_info);
+bool TestCase::Launch(lldb::SBLaunchInfo &launch_info) {
+ lldb::SBError error;
+ m_process = m_target.Launch(launch_info, error);
+ if (!error.Success())
+ fprintf(stderr, "error: %s\n", error.GetCString());
+ if (m_process.IsValid())
+ return true;
+ return false;
}
-void
-TestCase::SetVerbose (bool b)
-{
- m_verbose = b;
+bool TestCase::Launch(std::initializer_list<const char *> args) {
+ std::vector<const char *> args_vect(args);
+ args_vect.push_back(NULL);
+ lldb::SBLaunchInfo launch_info((const char **)&args_vect[0]);
+ return Launch(launch_info);
}
-bool
-TestCase::GetVerbose ()
-{
- return m_verbose;
-}
+void TestCase::SetVerbose(bool b) { m_verbose = b; }
+
+bool TestCase::GetVerbose() { return m_verbose; }
-void
-TestCase::Loop ()
-{
- while (true)
- {
- bool call_test_step = false;
- if (m_process.IsValid())
- {
- SBEvent evt;
- m_listener.WaitForEvent (UINT32_MAX, evt);
- StateType state = SBProcess::GetStateFromEvent (evt);
+void TestCase::Loop() {
+ while (true) {
+ bool call_test_step = false;
+ if (m_process.IsValid()) {
+ SBEvent evt;
+ m_listener.WaitForEvent(UINT32_MAX, evt);
+ StateType state = SBProcess::GetStateFromEvent(evt);
+ if (m_verbose)
+ printf("event = %s\n", SBDebugger::StateAsCString(state));
+ if (SBProcess::GetRestartedFromEvent(evt)) {
+ if (m_verbose) {
+ const uint32_t num_threads = m_process.GetNumThreads();
+ for (auto thread_index = 0; thread_index < num_threads;
+ thread_index++) {
+ SBThread thread(m_process.GetThreadAtIndex(thread_index));
+ SBFrame frame(thread.GetFrameAtIndex(0));
+ SBStream strm;
+ strm.RedirectToFileHandle(stdout, false);
+ frame.GetDescription(strm);
+ }
+ puts("restarted");
+ }
+ call_test_step = false;
+ } else {
+ switch (state) {
+ case eStateInvalid:
+ case eStateDetached:
+ case eStateCrashed:
+ case eStateUnloaded:
+ break;
+ case eStateExited:
+ return;
+ case eStateConnected:
+ case eStateAttaching:
+ case eStateLaunching:
+ case eStateRunning:
+ case eStateStepping:
+ call_test_step = false;
+ break;
+
+ case eStateStopped:
+ case eStateSuspended: {
+ call_test_step = true;
+ bool fatal = false;
+ bool selected_thread = false;
+ const uint32_t num_threads = m_process.GetNumThreads();
+ for (auto thread_index = 0; thread_index < num_threads;
+ thread_index++) {
+ SBThread thread(m_process.GetThreadAtIndex(thread_index));
+ SBFrame frame(thread.GetFrameAtIndex(0));
+ SBStream strm;
+ strm.RedirectToFileHandle(stdout, false);
+ frame.GetDescription(strm);
+ bool select_thread = false;
+ StopReason stop_reason = thread.GetStopReason();
if (m_verbose)
- printf("event = %s\n",SBDebugger::StateAsCString(state));
- if (SBProcess::GetRestartedFromEvent(evt))
- {
- if (m_verbose)
- {
- const uint32_t num_threads = m_process.GetNumThreads();
- for (auto thread_index = 0; thread_index < num_threads; thread_index++)
- {
- SBThread thread(m_process.GetThreadAtIndex(thread_index));
- SBFrame frame(thread.GetFrameAtIndex(0));
- SBStream strm;
- strm.RedirectToFileHandle(stdout, false);
- frame.GetDescription(strm);
- }
- puts("restarted");
- }
- call_test_step = false;
+ printf("tid = 0x%llx pc = 0x%llx ", thread.GetThreadID(),
+ frame.GetPC());
+ switch (stop_reason) {
+ case eStopReasonNone:
+ if (m_verbose)
+ printf("none\n");
+ break;
+
+ case eStopReasonTrace:
+ select_thread = true;
+ if (m_verbose)
+ printf("trace\n");
+ break;
+
+ case eStopReasonPlanComplete:
+ select_thread = true;
+ if (m_verbose)
+ printf("plan complete\n");
+ break;
+ case eStopReasonThreadExiting:
+ if (m_verbose)
+ printf("thread exiting\n");
+ break;
+ case eStopReasonExec:
+ if (m_verbose)
+ printf("exec\n");
+ break;
+ case eStopReasonInvalid:
+ if (m_verbose)
+ printf("invalid\n");
+ break;
+ case eStopReasonException:
+ select_thread = true;
+ if (m_verbose)
+ printf("exception\n");
+ fatal = true;
+ break;
+ case eStopReasonBreakpoint:
+ select_thread = true;
+ if (m_verbose)
+ printf("breakpoint id = %lld.%lld\n",
+ thread.GetStopReasonDataAtIndex(0),
+ thread.GetStopReasonDataAtIndex(1));
+ break;
+ case eStopReasonWatchpoint:
+ select_thread = true;
+ if (m_verbose)
+ printf("watchpoint id = %lld\n",
+ thread.GetStopReasonDataAtIndex(0));
+ break;
+ case eStopReasonSignal:
+ select_thread = true;
+ if (m_verbose)
+ printf("signal %d\n", (int)thread.GetStopReasonDataAtIndex(0));
+ break;
}
- else
- {
- switch (state)
- {
- case eStateInvalid:
- case eStateDetached:
- case eStateCrashed:
- case eStateUnloaded:
- break;
- case eStateExited:
- return;
- case eStateConnected:
- case eStateAttaching:
- case eStateLaunching:
- case eStateRunning:
- case eStateStepping:
- call_test_step = false;
- break;
-
- case eStateStopped:
- case eStateSuspended:
- {
- call_test_step = true;
- bool fatal = false;
- bool selected_thread = false;
- const uint32_t num_threads = m_process.GetNumThreads();
- for (auto thread_index = 0; thread_index < num_threads; thread_index++)
- {
- SBThread thread(m_process.GetThreadAtIndex(thread_index));
- SBFrame frame(thread.GetFrameAtIndex(0));
- SBStream strm;
- strm.RedirectToFileHandle(stdout, false);
- frame.GetDescription(strm);
- bool select_thread = false;
- StopReason stop_reason = thread.GetStopReason();
- if (m_verbose) printf("tid = 0x%llx pc = 0x%llx ",thread.GetThreadID(),frame.GetPC());
- switch (stop_reason)
- {
- case eStopReasonNone:
- if (m_verbose)
- printf("none\n");
- break;
-
- case eStopReasonTrace:
- select_thread = true;
- if (m_verbose)
- printf("trace\n");
- break;
-
- case eStopReasonPlanComplete:
- select_thread = true;
- if (m_verbose)
- printf("plan complete\n");
- break;
- case eStopReasonThreadExiting:
- if (m_verbose)
- printf("thread exiting\n");
- break;
- case eStopReasonExec:
- if (m_verbose)
- printf("exec\n");
- break;
- case eStopReasonInvalid:
- if (m_verbose)
- printf("invalid\n");
- break;
- case eStopReasonException:
- select_thread = true;
- if (m_verbose)
- printf("exception\n");
- fatal = true;
- break;
- case eStopReasonBreakpoint:
- select_thread = true;
- if (m_verbose)
- printf("breakpoint id = %lld.%lld\n",thread.GetStopReasonDataAtIndex(0),thread.GetStopReasonDataAtIndex(1));
- break;
- case eStopReasonWatchpoint:
- select_thread = true;
- if (m_verbose)
- printf("watchpoint id = %lld\n",thread.GetStopReasonDataAtIndex(0));
- break;
- case eStopReasonSignal:
- select_thread = true;
- if (m_verbose)
- printf("signal %d\n",(int)thread.GetStopReasonDataAtIndex(0));
- break;
- }
- if (select_thread && !selected_thread)
- {
- m_thread = thread;
- selected_thread = m_process.SetSelectedThread(thread);
- }
- }
- if (fatal)
- {
- if (m_verbose) Xcode::RunCommand(m_debugger,"bt all",true);
- exit(1);
- }
- }
- break;
- }
+ if (select_thread && !selected_thread) {
+ m_thread = thread;
+ selected_thread = m_process.SetSelectedThread(thread);
}
- }
- else
- {
- call_test_step = true;
+ }
+ if (fatal) {
+ if (m_verbose)
+ Xcode::RunCommand(m_debugger, "bt all", true);
+ exit(1);
+ }
+ } break;
}
+ }
+ } else {
+ call_test_step = true;
+ }
- if (call_test_step)
- {
- do_the_call:
- if (m_verbose)
- printf("RUNNING STEP %d\n",m_step);
- ActionWanted action;
- TestStep(m_step, action);
- m_step++;
- SBError err;
- switch (action.type)
- {
- case ActionWanted::Type::eNone:
- // Just exit and wait for the next event
- break;
- case ActionWanted::Type::eContinue:
- err = m_process.Continue();
- break;
- case ActionWanted::Type::eStepOut:
- if (action.thread.IsValid() == false)
- {
- if (m_verbose)
- {
- Xcode::RunCommand(m_debugger,"bt all",true);
- printf("error: invalid thread for step out on step %d\n", m_step);
- }
- exit(501);
- }
- m_process.SetSelectedThread(action.thread);
- action.thread.StepOut();
- break;
- case ActionWanted::Type::eStepOver:
- if (action.thread.IsValid() == false)
- {
- if (m_verbose)
- {
- Xcode::RunCommand(m_debugger,"bt all",true);
- printf("error: invalid thread for step over %d\n",m_step);
- }
- exit(500);
- }
- m_process.SetSelectedThread(action.thread);
- action.thread.StepOver();
- break;
- case ActionWanted::Type::eRelaunch:
- if (m_process.IsValid())
- {
- m_process.Kill();
- m_process.Clear();
- }
- Launch(action.launch_info);
- break;
- case ActionWanted::Type::eKill:
- if (m_verbose)
- printf("kill\n");
- m_process.Kill();
- return;
- case ActionWanted::Type::eCallNext:
- goto do_the_call;
- break;
- }
+ if (call_test_step) {
+ do_the_call:
+ if (m_verbose)
+ printf("RUNNING STEP %d\n", m_step);
+ ActionWanted action;
+ TestStep(m_step, action);
+ m_step++;
+ SBError err;
+ switch (action.type) {
+ case ActionWanted::Type::eNone:
+ // Just exit and wait for the next event
+ break;
+ case ActionWanted::Type::eContinue:
+ err = m_process.Continue();
+ break;
+ case ActionWanted::Type::eStepOut:
+ if (action.thread.IsValid() == false) {
+ if (m_verbose) {
+ Xcode::RunCommand(m_debugger, "bt all", true);
+ printf("error: invalid thread for step out on step %d\n", m_step);
+ }
+ exit(501);
}
+ m_process.SetSelectedThread(action.thread);
+ action.thread.StepOut();
+ break;
+ case ActionWanted::Type::eStepOver:
+ if (action.thread.IsValid() == false) {
+ if (m_verbose) {
+ Xcode::RunCommand(m_debugger, "bt all", true);
+ printf("error: invalid thread for step over %d\n", m_step);
+ }
+ exit(500);
+ }
+ m_process.SetSelectedThread(action.thread);
+ action.thread.StepOver();
+ break;
+ case ActionWanted::Type::eRelaunch:
+ if (m_process.IsValid()) {
+ m_process.Kill();
+ m_process.Clear();
+ }
+ Launch(action.launch_info);
+ break;
+ case ActionWanted::Type::eKill:
+ if (m_verbose)
+ printf("kill\n");
+ m_process.Kill();
+ return;
+ case ActionWanted::Type::eCallNext:
+ goto do_the_call;
+ break;
+ }
+ }
+ }
- }
-
- if (GetVerbose()) printf("I am gonna die at step %d\n",m_step);
+ if (GetVerbose())
+ printf("I am gonna die at step %d\n", m_step);
}
-int
-TestCase::Run (TestCase& test, int argc, const char** argv)
-{
- if (test.Setup(argc, argv))
- {
- test.Loop();
- Results results;
- test.WriteResults(results);
- return RUN_SUCCESS;
- }
- else
- return RUN_SETUP_ERROR;
+int TestCase::Run(TestCase &test, int argc, const char **argv) {
+ if (test.Setup(argc, argv)) {
+ test.Loop();
+ Results results;
+ test.WriteResults(results);
+ return RUN_SUCCESS;
+ } else
+ return RUN_SETUP_ERROR;
}
-
Modified: lldb/trunk/tools/lldb-perf/lib/TestCase.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/TestCase.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/TestCase.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/TestCase.h Tue Sep 6 15:57:50 2016
@@ -10,195 +10,135 @@
#ifndef __PerfTestDriver__TestCase__
#define __PerfTestDriver__TestCase__
-#include "lldb/API/LLDB.h"
#include "Measurement.h"
+#include "lldb/API/LLDB.h"
#include <getopt.h>
namespace lldb_perf {
class Results;
-
-class TestCase
-{
+
+class TestCase {
public:
- TestCase();
-
- struct ActionWanted
- {
- enum class Type
- {
- eStepOver,
- eContinue,
- eStepOut,
- eRelaunch,
- eCallNext,
- eNone,
- eKill
- } type;
- lldb::SBThread thread;
- lldb::SBLaunchInfo launch_info;
-
- ActionWanted () :
- type (Type::eContinue),
- thread (),
- launch_info (NULL)
- {
- }
-
- void
- None ()
- {
- type = Type::eNone;
- thread = lldb::SBThread();
- }
-
- void
- Continue()
- {
- type = Type::eContinue;
- thread = lldb::SBThread();
- }
-
- void
- StepOver (lldb::SBThread t)
- {
- type = Type::eStepOver;
- thread = t;
- }
-
- void
- StepOut (lldb::SBThread t)
- {
- type = Type::eStepOut;
- thread = t;
- }
-
- void
- Relaunch (lldb::SBLaunchInfo l)
- {
- type = Type::eRelaunch;
- thread = lldb::SBThread();
- launch_info = l;
- }
-
- void
- Kill ()
- {
- type = Type::eKill;
- thread = lldb::SBThread();
- }
-
- void
- CallNext ()
- {
- type = Type::eCallNext;
- thread = lldb::SBThread();
- }
- };
-
- virtual
- ~TestCase ()
- {
- }
-
- virtual bool
- Setup (int& argc, const char**& argv);
-
- virtual void
- TestStep (int counter, ActionWanted &next_action) = 0;
-
- bool
- Launch (lldb::SBLaunchInfo &launch_info);
-
- bool
- Launch (std::initializer_list<const char*> args = {});
-
- void
- Loop();
-
- void
- SetVerbose (bool);
-
- bool
- GetVerbose ();
-
- virtual void
- WriteResults (Results &results) = 0;
-
- template <typename G,typename A>
- Measurement<G,A> CreateMeasurement (A a, const char* name = NULL, const char* description = NULL)
- {
- return Measurement<G,A> (a,name, description);
- }
-
- template <typename A>
- TimeMeasurement<A> CreateTimeMeasurement (A a, const char* name = NULL, const char* description = NULL)
- {
- return TimeMeasurement<A> (a,name, description);
- }
-
- template <typename A>
- MemoryMeasurement<A> CreateMemoryMeasurement (A a, const char* name = NULL, const char* description = NULL)
- {
- return MemoryMeasurement<A> (a,name, description);
- }
-
- static int
- Run (TestCase& test, int argc, const char** argv);
-
- virtual bool
- ParseOption (int short_option, const char* optarg)
- {
- return false;
- }
-
- virtual struct option*
- GetLongOptions ()
- {
- return NULL;
- }
-
- lldb::SBDebugger &
- GetDebugger()
- {
- return m_debugger;
- }
-
- lldb::SBTarget &
- GetTarget()
- {
- return m_target;
- }
-
- lldb::SBProcess &
- GetProcess ()
- {
- return m_process;
- }
-
- lldb::SBThread &
- GetThread ()
- {
- return m_thread;
- }
-
- int
- GetStep ()
- {
- return m_step;
- }
-
- static const int RUN_SUCCESS = 0;
- static const int RUN_SETUP_ERROR = 100;
-
+ TestCase();
+
+ struct ActionWanted {
+ enum class Type {
+ eStepOver,
+ eContinue,
+ eStepOut,
+ eRelaunch,
+ eCallNext,
+ eNone,
+ eKill
+ } type;
+ lldb::SBThread thread;
+ lldb::SBLaunchInfo launch_info;
+
+ ActionWanted() : type(Type::eContinue), thread(), launch_info(NULL) {}
+
+ void None() {
+ type = Type::eNone;
+ thread = lldb::SBThread();
+ }
+
+ void Continue() {
+ type = Type::eContinue;
+ thread = lldb::SBThread();
+ }
+
+ void StepOver(lldb::SBThread t) {
+ type = Type::eStepOver;
+ thread = t;
+ }
+
+ void StepOut(lldb::SBThread t) {
+ type = Type::eStepOut;
+ thread = t;
+ }
+
+ void Relaunch(lldb::SBLaunchInfo l) {
+ type = Type::eRelaunch;
+ thread = lldb::SBThread();
+ launch_info = l;
+ }
+
+ void Kill() {
+ type = Type::eKill;
+ thread = lldb::SBThread();
+ }
+
+ void CallNext() {
+ type = Type::eCallNext;
+ thread = lldb::SBThread();
+ }
+ };
+
+ virtual ~TestCase() {}
+
+ virtual bool Setup(int &argc, const char **&argv);
+
+ virtual void TestStep(int counter, ActionWanted &next_action) = 0;
+
+ bool Launch(lldb::SBLaunchInfo &launch_info);
+
+ bool Launch(std::initializer_list<const char *> args = {});
+
+ void Loop();
+
+ void SetVerbose(bool);
+
+ bool GetVerbose();
+
+ virtual void WriteResults(Results &results) = 0;
+
+ template <typename G, typename A>
+ Measurement<G, A> CreateMeasurement(A a, const char *name = NULL,
+ const char *description = NULL) {
+ return Measurement<G, A>(a, name, description);
+ }
+
+ template <typename A>
+ TimeMeasurement<A> CreateTimeMeasurement(A a, const char *name = NULL,
+ const char *description = NULL) {
+ return TimeMeasurement<A>(a, name, description);
+ }
+
+ template <typename A>
+ MemoryMeasurement<A> CreateMemoryMeasurement(A a, const char *name = NULL,
+ const char *description = NULL) {
+ return MemoryMeasurement<A>(a, name, description);
+ }
+
+ static int Run(TestCase &test, int argc, const char **argv);
+
+ virtual bool ParseOption(int short_option, const char *optarg) {
+ return false;
+ }
+
+ virtual struct option *GetLongOptions() { return NULL; }
+
+ lldb::SBDebugger &GetDebugger() { return m_debugger; }
+
+ lldb::SBTarget &GetTarget() { return m_target; }
+
+ lldb::SBProcess &GetProcess() { return m_process; }
+
+ lldb::SBThread &GetThread() { return m_thread; }
+
+ int GetStep() { return m_step; }
+
+ static const int RUN_SUCCESS = 0;
+ static const int RUN_SETUP_ERROR = 100;
+
protected:
- lldb::SBDebugger m_debugger;
- lldb::SBTarget m_target;
- lldb::SBProcess m_process;
- lldb::SBThread m_thread;
- lldb::SBListener m_listener;
- bool m_verbose;
- int m_step;
+ lldb::SBDebugger m_debugger;
+ lldb::SBTarget m_target;
+ lldb::SBProcess m_process;
+ lldb::SBThread m_thread;
+ lldb::SBListener m_listener;
+ bool m_verbose;
+ int m_step;
};
}
Modified: lldb/trunk/tools/lldb-perf/lib/Timer.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Timer.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Timer.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/Timer.cpp Tue Sep 6 15:57:50 2016
@@ -12,50 +12,36 @@
using namespace lldb_perf;
-TimeGauge::TimeType
-TimeGauge::Now ()
-{
- return high_resolution_clock::now();
-}
+TimeGauge::TimeType TimeGauge::Now() { return high_resolution_clock::now(); }
-TimeGauge::TimeGauge () :
- m_start(),
- m_state(TimeGauge::State::eNeverUsed)
-{
-}
+TimeGauge::TimeGauge() : m_start(), m_state(TimeGauge::State::eNeverUsed) {}
-void
-TimeGauge::Start ()
-{
- m_state = TimeGauge::State::eCounting;
- m_start = Now();
+void TimeGauge::Start() {
+ m_state = TimeGauge::State::eCounting;
+ m_start = Now();
}
-double
-TimeGauge::Stop ()
-{
- m_stop = Now();
- assert(m_state == TimeGauge::State::eCounting && "cannot stop a non-started clock");
- m_state = TimeGauge::State::eStopped;
- m_delta = duration_cast<duration<double>>(m_stop-m_start).count();
- return m_delta;
+double TimeGauge::Stop() {
+ m_stop = Now();
+ assert(m_state == TimeGauge::State::eCounting &&
+ "cannot stop a non-started clock");
+ m_state = TimeGauge::State::eStopped;
+ m_delta = duration_cast<duration<double>>(m_stop - m_start).count();
+ return m_delta;
}
-double
-TimeGauge::GetStartValue () const
-{
- return (double)m_start.time_since_epoch().count() * (double)system_clock::period::num / (double)system_clock::period::den;
+double TimeGauge::GetStartValue() const {
+ return (double)m_start.time_since_epoch().count() *
+ (double)system_clock::period::num / (double)system_clock::period::den;
}
-double
-TimeGauge::GetStopValue () const
-{
- return (double)m_stop.time_since_epoch().count() * (double)system_clock::period::num / (double)system_clock::period::den;
+double TimeGauge::GetStopValue() const {
+ return (double)m_stop.time_since_epoch().count() *
+ (double)system_clock::period::num / (double)system_clock::period::den;
}
-double
-TimeGauge::GetDeltaValue () const
-{
- assert(m_state == TimeGauge::State::eStopped && "clock must be used before you can evaluate it");
- return m_delta;
+double TimeGauge::GetDeltaValue() const {
+ assert(m_state == TimeGauge::State::eStopped &&
+ "clock must be used before you can evaluate it");
+ return m_delta;
}
Modified: lldb/trunk/tools/lldb-perf/lib/Timer.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Timer.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Timer.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Timer.h Tue Sep 6 15:57:50 2016
@@ -16,50 +16,33 @@
using namespace std::chrono;
-namespace lldb_perf
-{
-class TimeGauge : public Gauge<double>
-{
+namespace lldb_perf {
+class TimeGauge : public Gauge<double> {
public:
- TimeGauge ();
-
- virtual
- ~TimeGauge ()
- {
- }
-
- void
- Start ();
-
- double
- Stop ();
-
- virtual double
- GetStartValue () const;
-
- virtual double
- GetStopValue () const;
+ TimeGauge();
- virtual double
- GetDeltaValue () const;
+ virtual ~TimeGauge() {}
+
+ void Start();
+
+ double Stop();
+
+ virtual double GetStartValue() const;
+
+ virtual double GetStopValue() const;
+
+ virtual double GetDeltaValue() const;
private:
- enum class State
- {
- eNeverUsed,
- eCounting,
- eStopped
- };
-
- typedef high_resolution_clock::time_point TimeType;
- TimeType m_start;
- TimeType m_stop;
- double m_delta;
- State m_state;
-
- TimeType
- Now ();
-
+ enum class State { eNeverUsed, eCounting, eStopped };
+
+ typedef high_resolution_clock::time_point TimeType;
+ TimeType m_start;
+ TimeType m_stop;
+ double m_delta;
+ State m_state;
+
+ TimeType Now();
};
}
Modified: lldb/trunk/tools/lldb-perf/lib/Xcode.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Xcode.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Xcode.cpp (original)
+++ lldb/trunk/tools/lldb-perf/lib/Xcode.cpp Tue Sep 6 15:57:50 2016
@@ -13,153 +13,125 @@
using namespace std;
using namespace lldb_perf;
-void
-Xcode::FetchVariable (SBValue value, uint32_t expand, bool verbose)
-{
- auto name = value.GetName();
- auto num_value = value.GetValueAsUnsigned(0);
- auto summary = value.GetSummary();
- auto in_scope = value.IsInScope();
- auto has_children = value.MightHaveChildren();
- auto type_1 = value.GetType();
- auto type_2 = value.GetType();
- auto type_name_1 = value.GetTypeName();
- auto type_3 = value.GetType();
- auto type_name_2 = value.GetTypeName();
- if (verbose)
- printf("%s %s = 0x%llx (%llu) %s\n",value.GetTypeName(),value.GetName(),num_value, num_value,summary);
- if (expand > 0)
- {
- auto count = value.GetNumChildren();
- for (int i = 0; i < count; i++)
- {
- SBValue child(value.GetChildAtIndex(i, lldb::eDynamicCanRunTarget, true));
- FetchVariable (child,expand-1,verbose);
- }
- }
-}
-
-void
-Xcode::FetchModules (SBTarget target, bool verbose)
-{
- auto count = target.GetNumModules();
- for (int i = 0; i < count; i++)
- {
- SBModule module(target.GetModuleAtIndex(i));
- auto fspec = module.GetFileSpec();
- std::string path(1024,0);
- fspec.GetPath(&path[0],1024);
- auto uuid = module.GetUUIDBytes();
- if (verbose)
- {
- printf("%s %s\n",path.c_str(),module.GetUUIDString());
- }
- }
-}
-
-void
-Xcode::FetchVariables (SBFrame frame, uint32_t expand, bool verbose)
-{
- auto values = frame.GetVariables (true,true,true,false, eDynamicCanRunTarget);
- auto count = values.GetSize();
- for (int i = 0; i < count; i++)
- {
- SBValue value(values.GetValueAtIndex(i));
- FetchVariable (value,expand,verbose);
- }
-}
-
-void
-Xcode::FetchFrames(SBProcess process, bool variables, bool verbose)
-{
- auto pCount = process.GetNumThreads();
- for (int p = 0; p < pCount; p++)
- {
- SBThread thread(process.GetThreadAtIndex(p));
- auto tCount = thread.GetNumFrames ();
- if (verbose)
- printf("%s %d %d {%d}\n",thread.GetQueueName(),tCount,thread.GetStopReason(),eStopReasonBreakpoint);
- for (int t = 0; t < tCount; t++)
- {
- SBFrame frame(thread.GetFrameAtIndex(t));
- auto fp = frame.GetFP();
- SBThread thread_dup = frame.GetThread();
- SBFileSpec filespec(process.GetTarget().GetExecutable());
- std::string path(1024,0);
- filespec.GetPath(&path[0],1024);
- auto state = process.GetState();
- auto pCount_dup = process.GetNumThreads();
- auto byte_size = process.GetAddressByteSize();
- auto pc = frame.GetPC();
- SBSymbolContext context(frame.GetSymbolContext(0x0000006e));
- SBModule module(context.GetModule());
- SBLineEntry entry(context.GetLineEntry());
- SBFileSpec entry_filespec(process.GetTarget().GetExecutable());
- std::string entry_path(1024,0);
- entry_filespec.GetPath(&entry_path[0],1024);
- auto line_1 = entry.GetLine();
- auto line_2 = entry.GetLine();
- auto fname = frame.GetFunctionName();
- if (verbose)
- printf("%llu %s %d %d %llu %s %d %s\n",fp,path.c_str(),state,byte_size,pc,entry_path.c_str(),line_1,fname);
- if (variables)
- FetchVariables (frame, 0, verbose);
- }
- }
-}
-
-void
-Xcode::RunExpression (SBFrame frame, const char* expression, bool po, bool verbose)
-{
- SBValue value (frame.EvaluateExpression (expression, eDynamicCanRunTarget));
- FetchVariable (value,0,verbose);
- if (po)
- {
- auto descr = value.GetObjectDescription();
- if (descr)
- printf("po = %s\n",descr);
- }
-}
-
-void
-Xcode::Next (SBThread thread)
-{
- thread.StepOver();
-}
-
-void
-Xcode::Continue (SBProcess process)
-{
- process.Continue();
-}
-
-void
-Xcode::RunCommand (SBDebugger debugger, const char* cmd, bool verbose)
-{
- SBCommandReturnObject sb_ret;
- auto interpreter = debugger.GetCommandInterpreter();
- interpreter.HandleCommand(cmd,sb_ret);
- if (verbose)
- printf("%s\n%s\n",sb_ret.GetOutput(false),sb_ret.GetError(false));
-}
-
-SBThread
-Xcode::GetThreadWithStopReason (SBProcess process, StopReason reason)
-{
- auto threads_count = process.GetNumThreads();
- for (auto thread_num = 0; thread_num < threads_count; thread_num++)
- {
- SBThread thread(process.GetThreadAtIndex(thread_num));
- if (thread.GetStopReason() == reason)
- {
- return thread;
- }
- }
- return SBThread();
-}
-
-SBBreakpoint
-Xcode::CreateFileLineBreakpoint (SBTarget target, const char* file, uint32_t line)
-{
- return target.BreakpointCreateByLocation(file, line);
+void Xcode::FetchVariable(SBValue value, uint32_t expand, bool verbose) {
+ auto name = value.GetName();
+ auto num_value = value.GetValueAsUnsigned(0);
+ auto summary = value.GetSummary();
+ auto in_scope = value.IsInScope();
+ auto has_children = value.MightHaveChildren();
+ auto type_1 = value.GetType();
+ auto type_2 = value.GetType();
+ auto type_name_1 = value.GetTypeName();
+ auto type_3 = value.GetType();
+ auto type_name_2 = value.GetTypeName();
+ if (verbose)
+ printf("%s %s = 0x%llx (%llu) %s\n", value.GetTypeName(), value.GetName(),
+ num_value, num_value, summary);
+ if (expand > 0) {
+ auto count = value.GetNumChildren();
+ for (int i = 0; i < count; i++) {
+ SBValue child(value.GetChildAtIndex(i, lldb::eDynamicCanRunTarget, true));
+ FetchVariable(child, expand - 1, verbose);
+ }
+ }
+}
+
+void Xcode::FetchModules(SBTarget target, bool verbose) {
+ auto count = target.GetNumModules();
+ for (int i = 0; i < count; i++) {
+ SBModule module(target.GetModuleAtIndex(i));
+ auto fspec = module.GetFileSpec();
+ std::string path(1024, 0);
+ fspec.GetPath(&path[0], 1024);
+ auto uuid = module.GetUUIDBytes();
+ if (verbose) {
+ printf("%s %s\n", path.c_str(), module.GetUUIDString());
+ }
+ }
+}
+
+void Xcode::FetchVariables(SBFrame frame, uint32_t expand, bool verbose) {
+ auto values =
+ frame.GetVariables(true, true, true, false, eDynamicCanRunTarget);
+ auto count = values.GetSize();
+ for (int i = 0; i < count; i++) {
+ SBValue value(values.GetValueAtIndex(i));
+ FetchVariable(value, expand, verbose);
+ }
+}
+
+void Xcode::FetchFrames(SBProcess process, bool variables, bool verbose) {
+ auto pCount = process.GetNumThreads();
+ for (int p = 0; p < pCount; p++) {
+ SBThread thread(process.GetThreadAtIndex(p));
+ auto tCount = thread.GetNumFrames();
+ if (verbose)
+ printf("%s %d %d {%d}\n", thread.GetQueueName(), tCount,
+ thread.GetStopReason(), eStopReasonBreakpoint);
+ for (int t = 0; t < tCount; t++) {
+ SBFrame frame(thread.GetFrameAtIndex(t));
+ auto fp = frame.GetFP();
+ SBThread thread_dup = frame.GetThread();
+ SBFileSpec filespec(process.GetTarget().GetExecutable());
+ std::string path(1024, 0);
+ filespec.GetPath(&path[0], 1024);
+ auto state = process.GetState();
+ auto pCount_dup = process.GetNumThreads();
+ auto byte_size = process.GetAddressByteSize();
+ auto pc = frame.GetPC();
+ SBSymbolContext context(frame.GetSymbolContext(0x0000006e));
+ SBModule module(context.GetModule());
+ SBLineEntry entry(context.GetLineEntry());
+ SBFileSpec entry_filespec(process.GetTarget().GetExecutable());
+ std::string entry_path(1024, 0);
+ entry_filespec.GetPath(&entry_path[0], 1024);
+ auto line_1 = entry.GetLine();
+ auto line_2 = entry.GetLine();
+ auto fname = frame.GetFunctionName();
+ if (verbose)
+ printf("%llu %s %d %d %llu %s %d %s\n", fp, path.c_str(), state,
+ byte_size, pc, entry_path.c_str(), line_1, fname);
+ if (variables)
+ FetchVariables(frame, 0, verbose);
+ }
+ }
+}
+
+void Xcode::RunExpression(SBFrame frame, const char *expression, bool po,
+ bool verbose) {
+ SBValue value(frame.EvaluateExpression(expression, eDynamicCanRunTarget));
+ FetchVariable(value, 0, verbose);
+ if (po) {
+ auto descr = value.GetObjectDescription();
+ if (descr)
+ printf("po = %s\n", descr);
+ }
+}
+
+void Xcode::Next(SBThread thread) { thread.StepOver(); }
+
+void Xcode::Continue(SBProcess process) { process.Continue(); }
+
+void Xcode::RunCommand(SBDebugger debugger, const char *cmd, bool verbose) {
+ SBCommandReturnObject sb_ret;
+ auto interpreter = debugger.GetCommandInterpreter();
+ interpreter.HandleCommand(cmd, sb_ret);
+ if (verbose)
+ printf("%s\n%s\n", sb_ret.GetOutput(false), sb_ret.GetError(false));
+}
+
+SBThread Xcode::GetThreadWithStopReason(SBProcess process, StopReason reason) {
+ auto threads_count = process.GetNumThreads();
+ for (auto thread_num = 0; thread_num < threads_count; thread_num++) {
+ SBThread thread(process.GetThreadAtIndex(thread_num));
+ if (thread.GetStopReason() == reason) {
+ return thread;
+ }
+ }
+ return SBThread();
+}
+
+SBBreakpoint Xcode::CreateFileLineBreakpoint(SBTarget target, const char *file,
+ uint32_t line) {
+ return target.BreakpointCreateByLocation(file, line);
}
Modified: lldb/trunk/tools/lldb-perf/lib/Xcode.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-perf/lib/Xcode.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-perf/lib/Xcode.h (original)
+++ lldb/trunk/tools/lldb-perf/lib/Xcode.h Tue Sep 6 15:57:50 2016
@@ -10,54 +10,48 @@
#ifndef __PerfTestDriver__Xcode__
#define __PerfTestDriver__Xcode__
+#include "lldb/API/SBBreakpoint.h"
+#include "lldb/API/SBCommandInterpreter.h"
+#include "lldb/API/SBCommandReturnObject.h"
+#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBDefines.h"
-#include "lldb/API/SBValue.h"
-#include "lldb/API/SBTarget.h"
+#include "lldb/API/SBLineEntry.h"
#include "lldb/API/SBModule.h"
#include "lldb/API/SBProcess.h"
-#include "lldb/API/SBLineEntry.h"
+#include "lldb/API/SBTarget.h"
#include "lldb/API/SBThread.h"
-#include "lldb/API/SBDebugger.h"
-#include "lldb/API/SBCommandInterpreter.h"
-#include "lldb/API/SBCommandReturnObject.h"
-#include "lldb/API/SBBreakpoint.h"
+#include "lldb/API/SBValue.h"
using namespace lldb;
-namespace lldb_perf
-{
-class Xcode
-{
+namespace lldb_perf {
+class Xcode {
public:
- static void
- FetchVariable (SBValue value, uint32_t expand = 0, bool verbose = false);
-
- static void
- FetchModules (SBTarget target, bool verbose = false);
-
- static void
- FetchVariables (SBFrame frame, uint32_t expand = 0, bool verbose = false);
-
- static void
- FetchFrames (SBProcess process, bool variables = false, bool verbose = false);
-
- static void
- RunExpression (SBFrame frame, const char* expression, bool po = false, bool verbose = false);
-
- static void
- Next (SBThread thread);
-
- static void
- Continue (SBProcess process);
-
- static void
- RunCommand (SBDebugger debugger, const char* cmd, bool verbose = false);
-
- static SBThread
- GetThreadWithStopReason (SBProcess process, StopReason reason);
-
- static SBBreakpoint
- CreateFileLineBreakpoint (SBTarget target, const char* file, uint32_t line);
+ static void FetchVariable(SBValue value, uint32_t expand = 0,
+ bool verbose = false);
+
+ static void FetchModules(SBTarget target, bool verbose = false);
+
+ static void FetchVariables(SBFrame frame, uint32_t expand = 0,
+ bool verbose = false);
+
+ static void FetchFrames(SBProcess process, bool variables = false,
+ bool verbose = false);
+
+ static void RunExpression(SBFrame frame, const char *expression,
+ bool po = false, bool verbose = false);
+
+ static void Next(SBThread thread);
+
+ static void Continue(SBProcess process);
+
+ static void RunCommand(SBDebugger debugger, const char *cmd,
+ bool verbose = false);
+
+ static SBThread GetThreadWithStopReason(SBProcess process, StopReason reason);
+
+ static SBBreakpoint CreateFileLineBreakpoint(SBTarget target,
+ const char *file, uint32_t line);
};
}
Modified: lldb/trunk/tools/lldb-server/Acceptor.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/Acceptor.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/Acceptor.cpp (original)
+++ lldb/trunk/tools/lldb-server/Acceptor.cpp Tue Sep 6 15:57:50 2016
@@ -25,10 +25,9 @@ using namespace llvm;
namespace {
-struct SocketScheme
-{
- const char* m_scheme;
- const Socket::SocketProtocol m_protocol;
+struct SocketScheme {
+ const char *m_scheme;
+ const Socket::SocketProtocol m_protocol;
};
SocketScheme socket_schemes[] = {
@@ -38,134 +37,102 @@ SocketScheme socket_schemes[] = {
{"unix-abstract", Socket::ProtocolUnixAbstract},
};
-bool
-FindProtocolByScheme(const char* scheme, Socket::SocketProtocol& protocol)
-{
- for (auto s: socket_schemes)
- {
- if (!strcmp(s.m_scheme, scheme))
- {
- protocol = s.m_protocol;
- return true;
- }
+bool FindProtocolByScheme(const char *scheme,
+ Socket::SocketProtocol &protocol) {
+ for (auto s : socket_schemes) {
+ if (!strcmp(s.m_scheme, scheme)) {
+ protocol = s.m_protocol;
+ return true;
}
- return false;
+ }
+ return false;
}
-const char*
-FindSchemeByProtocol(const Socket::SocketProtocol protocol)
-{
- for (auto s: socket_schemes)
- {
- if (s.m_protocol == protocol)
- return s.m_scheme;
- }
- return nullptr;
+const char *FindSchemeByProtocol(const Socket::SocketProtocol protocol) {
+ for (auto s : socket_schemes) {
+ if (s.m_protocol == protocol)
+ return s.m_scheme;
+ }
+ return nullptr;
}
-
}
-Error
-Acceptor::Listen(int backlog)
-{
- return m_listener_socket_up->Listen(StringRef(m_name.c_str()),
- backlog);
+Error Acceptor::Listen(int backlog) {
+ return m_listener_socket_up->Listen(StringRef(m_name.c_str()), backlog);
}
-Error
-Acceptor::Accept(const bool child_processes_inherit, Connection *&conn)
-{
- Socket* conn_socket = nullptr;
- auto error = m_listener_socket_up->Accept(StringRef(m_name.c_str()),
- child_processes_inherit,
- conn_socket);
- if (error.Success())
- conn = new ConnectionFileDescriptor(conn_socket);
+Error Acceptor::Accept(const bool child_processes_inherit, Connection *&conn) {
+ Socket *conn_socket = nullptr;
+ auto error = m_listener_socket_up->Accept(
+ StringRef(m_name.c_str()), child_processes_inherit, conn_socket);
+ if (error.Success())
+ conn = new ConnectionFileDescriptor(conn_socket);
- return error;
+ return error;
}
-Socket::SocketProtocol
-Acceptor::GetSocketProtocol() const
-{
- return m_listener_socket_up->GetSocketProtocol();
+Socket::SocketProtocol Acceptor::GetSocketProtocol() const {
+ return m_listener_socket_up->GetSocketProtocol();
}
-const char*
-Acceptor::GetSocketScheme() const
-{
- return FindSchemeByProtocol(GetSocketProtocol());
+const char *Acceptor::GetSocketScheme() const {
+ return FindSchemeByProtocol(GetSocketProtocol());
}
-std::string
-Acceptor::GetLocalSocketId() const
-{
- return m_local_socket_id();
-}
+std::string Acceptor::GetLocalSocketId() const { return m_local_socket_id(); }
-std::unique_ptr<Acceptor>
-Acceptor::Create(StringRef name, const bool child_processes_inherit, Error &error)
-{
- error.Clear();
+std::unique_ptr<Acceptor> Acceptor::Create(StringRef name,
+ const bool child_processes_inherit,
+ Error &error) {
+ error.Clear();
- Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain;
- int port;
- std::string scheme, host, path;
- // Try to match socket name as URL - e.g., tcp://localhost:5555
- if (UriParser::Parse(name.str(), scheme, host, port, path))
- {
- if (!FindProtocolByScheme(scheme.c_str(), socket_protocol))
- error.SetErrorStringWithFormat("Unknown protocol scheme \"%s\"", scheme.c_str());
- else
- name = name.drop_front(scheme.size() + strlen("://"));
- }
+ Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain;
+ int port;
+ std::string scheme, host, path;
+ // Try to match socket name as URL - e.g., tcp://localhost:5555
+ if (UriParser::Parse(name.str(), scheme, host, port, path)) {
+ if (!FindProtocolByScheme(scheme.c_str(), socket_protocol))
+ error.SetErrorStringWithFormat("Unknown protocol scheme \"%s\"",
+ scheme.c_str());
else
- {
- std::string host_str;
- std::string port_str;
- int32_t port = INT32_MIN;
- // Try to match socket name as $host:port - e.g., localhost:5555
- if (Socket::DecodeHostAndPort (name, host_str, port_str, port, nullptr))
- socket_protocol = Socket::ProtocolTcp;
- }
+ name = name.drop_front(scheme.size() + strlen("://"));
+ } else {
+ std::string host_str;
+ std::string port_str;
+ int32_t port = INT32_MIN;
+ // Try to match socket name as $host:port - e.g., localhost:5555
+ if (Socket::DecodeHostAndPort(name, host_str, port_str, port, nullptr))
+ socket_protocol = Socket::ProtocolTcp;
+ }
- if (error.Fail())
- return std::unique_ptr<Acceptor>();
-
- std::unique_ptr<Socket> listener_socket_up = Socket::Create(
- socket_protocol, child_processes_inherit, error);
+ if (error.Fail())
+ return std::unique_ptr<Acceptor>();
- LocalSocketIdFunc local_socket_id;
- if (error.Success())
- {
- if (listener_socket_up->GetSocketProtocol() == Socket::ProtocolTcp)
- {
- TCPSocket* tcp_socket = static_cast<TCPSocket*>(listener_socket_up.get());
- local_socket_id = [tcp_socket]() {
- auto local_port = tcp_socket->GetLocalPortNumber();
- return (local_port != 0) ? llvm::to_string(local_port) : "";
- };
- }
- else
- {
- const std::string socket_name = name;
- local_socket_id = [socket_name](){
- return socket_name;
- };
- }
+ std::unique_ptr<Socket> listener_socket_up =
+ Socket::Create(socket_protocol, child_processes_inherit, error);
- return std::unique_ptr<Acceptor>(
- new Acceptor(std::move(listener_socket_up), name, local_socket_id));
+ LocalSocketIdFunc local_socket_id;
+ if (error.Success()) {
+ if (listener_socket_up->GetSocketProtocol() == Socket::ProtocolTcp) {
+ TCPSocket *tcp_socket =
+ static_cast<TCPSocket *>(listener_socket_up.get());
+ local_socket_id = [tcp_socket]() {
+ auto local_port = tcp_socket->GetLocalPortNumber();
+ return (local_port != 0) ? llvm::to_string(local_port) : "";
+ };
+ } else {
+ const std::string socket_name = name;
+ local_socket_id = [socket_name]() { return socket_name; };
}
- return std::unique_ptr<Acceptor>();
+ return std::unique_ptr<Acceptor>(
+ new Acceptor(std::move(listener_socket_up), name, local_socket_id));
+ }
+
+ return std::unique_ptr<Acceptor>();
}
-Acceptor::Acceptor(std::unique_ptr<Socket> &&listener_socket,
- StringRef name,
+Acceptor::Acceptor(std::unique_ptr<Socket> &&listener_socket, StringRef name,
const LocalSocketIdFunc &local_socket_id)
- : m_listener_socket_up(std::move(listener_socket)),
- m_name(name.str()),
- m_local_socket_id(local_socket_id)
-{
-}
+ : m_listener_socket_up(std::move(listener_socket)), m_name(name.str()),
+ m_local_socket_id(local_socket_id) {}
Modified: lldb/trunk/tools/lldb-server/Acceptor.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/Acceptor.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/Acceptor.h (original)
+++ lldb/trunk/tools/lldb-server/Acceptor.h Tue Sep 6 15:57:50 2016
@@ -17,52 +17,45 @@
#include <memory>
#include <string>
-namespace llvm
-{
- class StringRef;
+namespace llvm {
+class StringRef;
}
namespace lldb_private {
namespace lldb_server {
-class Acceptor
-{
+class Acceptor {
public:
- virtual ~Acceptor() = default;
+ virtual ~Acceptor() = default;
- Error
- Listen(int backlog);
+ Error Listen(int backlog);
- Error
- Accept(const bool child_processes_inherit, Connection *&conn);
+ Error Accept(const bool child_processes_inherit, Connection *&conn);
- static std::unique_ptr<Acceptor>
- Create(llvm::StringRef name, const bool child_processes_inherit, Error &error);
+ static std::unique_ptr<Acceptor> Create(llvm::StringRef name,
+ const bool child_processes_inherit,
+ Error &error);
- Socket::SocketProtocol
- GetSocketProtocol() const;
+ Socket::SocketProtocol GetSocketProtocol() const;
- const char*
- GetSocketScheme() const;
+ const char *GetSocketScheme() const;
- // Returns either TCP port number as string or domain socket path.
- // Empty string is returned in case of error.
- std::string
- GetLocalSocketId() const;
+ // Returns either TCP port number as string or domain socket path.
+ // Empty string is returned in case of error.
+ std::string GetLocalSocketId() const;
private:
- typedef std::function<std::string()> LocalSocketIdFunc;
+ typedef std::function<std::string()> LocalSocketIdFunc;
- Acceptor(std::unique_ptr<Socket> &&listener_socket,
- llvm::StringRef name,
- const LocalSocketIdFunc &local_socket_id);
-
- const std::unique_ptr<Socket> m_listener_socket_up;
- const std::string m_name;
- const LocalSocketIdFunc m_local_socket_id;
+ Acceptor(std::unique_ptr<Socket> &&listener_socket, llvm::StringRef name,
+ const LocalSocketIdFunc &local_socket_id);
+
+ const std::unique_ptr<Socket> m_listener_socket_up;
+ const std::string m_name;
+ const LocalSocketIdFunc m_local_socket_id;
};
} // namespace lldb_server
} // namespace lldb_private
-#endif // lldb_server_Acceptor_h_
+#endif // lldb_server_Acceptor_h_
Modified: lldb/trunk/tools/lldb-server/LLDBServerUtilities.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/LLDBServerUtilities.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/LLDBServerUtilities.cpp (original)
+++ lldb/trunk/tools/lldb-server/LLDBServerUtilities.cpp Tue Sep 6 15:57:50 2016
@@ -21,47 +21,37 @@ using namespace lldb;
using namespace lldb_private::lldb_server;
using namespace llvm;
-bool
-LLDBServerUtilities::SetupLogging(const std::string& log_file,
- const StringRef& log_channels,
- uint32_t log_options)
-{
- lldb::StreamSP log_stream_sp;
- if (log_file.empty())
- {
- log_stream_sp.reset(new StreamFile(stdout, false));
- }
- else
- {
- uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate |
- File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
- if (!(log_options & LLDB_LOG_OPTION_APPEND))
- options |= File::eOpenOptionTruncate;
+bool LLDBServerUtilities::SetupLogging(const std::string &log_file,
+ const StringRef &log_channels,
+ uint32_t log_options) {
+ lldb::StreamSP log_stream_sp;
+ if (log_file.empty()) {
+ log_stream_sp.reset(new StreamFile(stdout, false));
+ } else {
+ uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate |
+ File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
+ if (!(log_options & LLDB_LOG_OPTION_APPEND))
+ options |= File::eOpenOptionTruncate;
- log_stream_sp.reset(new StreamFile(log_file.c_str(), options));
- }
+ log_stream_sp.reset(new StreamFile(log_file.c_str(), options));
+ }
- SmallVector<StringRef, 32> channel_array;
- log_channels.split(channel_array, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
- for (auto channel_with_categories : channel_array)
- {
- StreamString error_stream;
- Args channel_then_categories(channel_with_categories);
- std::string channel(channel_then_categories.GetArgumentAtIndex(0));
- channel_then_categories.Shift (); // Shift off the channel
+ SmallVector<StringRef, 32> channel_array;
+ log_channels.split(channel_array, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
+ for (auto channel_with_categories : channel_array) {
+ StreamString error_stream;
+ Args channel_then_categories(channel_with_categories);
+ std::string channel(channel_then_categories.GetArgumentAtIndex(0));
+ channel_then_categories.Shift(); // Shift off the channel
- bool success = Log::EnableLogChannel(log_stream_sp,
- log_options,
- channel.c_str(),
- channel_then_categories.GetConstArgumentVector(),
- error_stream);
- if (!success)
- {
- fprintf(stderr, "Unable to open log file '%s' for channel \"%s\"\n",
- log_file.c_str(),
- channel_with_categories.str().c_str());
- return false;
- }
+ bool success = Log::EnableLogChannel(
+ log_stream_sp, log_options, channel.c_str(),
+ channel_then_categories.GetConstArgumentVector(), error_stream);
+ if (!success) {
+ fprintf(stderr, "Unable to open log file '%s' for channel \"%s\"\n",
+ log_file.c_str(), channel_with_categories.str().c_str());
+ return false;
}
- return true;
+ }
+ return true;
}
Modified: lldb/trunk/tools/lldb-server/LLDBServerUtilities.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/LLDBServerUtilities.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/LLDBServerUtilities.h (original)
+++ lldb/trunk/tools/lldb-server/LLDBServerUtilities.h Tue Sep 6 15:57:50 2016
@@ -14,12 +14,11 @@
namespace lldb_private {
namespace lldb_server {
-class LLDBServerUtilities
-{
+class LLDBServerUtilities {
public:
- static bool
- SetupLogging(const std::string& log_file, const llvm::StringRef& log_channels, uint32_t log_options);
+ static bool SetupLogging(const std::string &log_file,
+ const llvm::StringRef &log_channels,
+ uint32_t log_options);
};
-
}
}
Modified: lldb/trunk/tools/lldb-server/lldb-gdbserver.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/lldb-gdbserver.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/lldb-gdbserver.cpp (original)
+++ lldb/trunk/tools/lldb-server/lldb-gdbserver.cpp Tue Sep 6 15:57:50 2016
@@ -24,6 +24,10 @@
// Other libraries and framework includes
#include "llvm/ADT/StringRef.h"
+#include "Acceptor.h"
+#include "LLDBServerUtilities.h"
+#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
+#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
@@ -32,10 +36,6 @@
#include "lldb/Host/Pipe.h"
#include "lldb/Host/Socket.h"
#include "lldb/Host/StringConvert.h"
-#include "Acceptor.h"
-#include "LLDBServerUtilities.h"
-#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
-#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
#ifndef LLGS_PROGRAM_NAME
#define LLGS_PROGRAM_NAME "lldb-server"
@@ -58,21 +58,24 @@ using namespace lldb_private::process_gd
static int g_debug = 0;
static int g_verbose = 0;
-static struct option g_long_options[] =
-{
- { "debug", no_argument, &g_debug, 1 },
- { "verbose", no_argument, &g_verbose, 1 },
- { "log-file", required_argument, NULL, 'l' },
- { "log-channels", required_argument, NULL, 'c' },
- { "attach", required_argument, NULL, 'a' },
- { "named-pipe", required_argument, NULL, 'N' },
- { "pipe", required_argument, NULL, 'U' },
- { "native-regs", no_argument, NULL, 'r' }, // Specify to use the native registers instead of the gdb defaults for the architecture. NOTE: this is a do-nothing arg as it's behavior is default now. FIXME remove call from lldb-platform.
- { "reverse-connect", no_argument, NULL, 'R' }, // Specifies that llgs attaches to the client address:port rather than llgs listening for a connection from address on port.
- { "setsid", no_argument, NULL, 'S' }, // Call setsid() to make llgs run in its own session.
- { NULL, 0, NULL, 0 }
-};
-
+static struct option g_long_options[] = {
+ {"debug", no_argument, &g_debug, 1},
+ {"verbose", no_argument, &g_verbose, 1},
+ {"log-file", required_argument, NULL, 'l'},
+ {"log-channels", required_argument, NULL, 'c'},
+ {"attach", required_argument, NULL, 'a'},
+ {"named-pipe", required_argument, NULL, 'N'},
+ {"pipe", required_argument, NULL, 'U'},
+ {"native-regs", no_argument, NULL,
+ 'r'}, // Specify to use the native registers instead of the gdb defaults
+ // for the architecture. NOTE: this is a do-nothing arg as it's
+ // behavior is default now. FIXME remove call from lldb-platform.
+ {"reverse-connect", no_argument, NULL,
+ 'R'}, // Specifies that llgs attaches to the client address:port rather
+ // than llgs listening for a connection from address on port.
+ {"setsid", no_argument, NULL,
+ 'S'}, // Call setsid() to make llgs run in its own session.
+ {NULL, 0, NULL, 0}};
//----------------------------------------------------------------------
// Watch for signals
@@ -80,418 +83,401 @@ static struct option g_long_options[] =
static int g_sighup_received_count = 0;
#ifndef _WIN32
-static void
-sighup_handler(MainLoopBase &mainloop)
-{
- ++g_sighup_received_count;
-
- Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
- if (log)
- log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
+static void sighup_handler(MainLoopBase &mainloop) {
+ ++g_sighup_received_count;
- if (g_sighup_received_count >= 2)
- mainloop.RequestTermination();
+ Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
+ if (log)
+ log->Printf("lldb-server:%s swallowing SIGHUP (receive count=%d)",
+ __FUNCTION__, g_sighup_received_count);
+
+ if (g_sighup_received_count >= 2)
+ mainloop.RequestTermination();
}
#endif // #ifndef _WIN32
-static void
-display_usage (const char *progname, const char* subcommand)
-{
- fprintf(stderr, "Usage:\n %s %s "
- "[--log-file log-file-name] "
- "[--log-channels log-channel-list] "
- "[--setsid] "
- "[--named-pipe named-pipe-path] "
- "[--native-regs] "
- "[--attach pid] "
- "[[HOST]:PORT] "
- "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
- exit(0);
-}
-
-void
-handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
-{
- Error error = gdb_server.AttachToProcess (pid);
- if (error.Fail ())
- {
- fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
- exit(1);
- }
+static void display_usage(const char *progname, const char *subcommand) {
+ fprintf(stderr, "Usage:\n %s %s "
+ "[--log-file log-file-name] "
+ "[--log-channels log-channel-list] "
+ "[--setsid] "
+ "[--named-pipe named-pipe-path] "
+ "[--native-regs] "
+ "[--attach pid] "
+ "[[HOST]:PORT] "
+ "[-- PROGRAM ARG1 ARG2 ...]\n",
+ progname, subcommand);
+ exit(0);
+}
+
+void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
+ lldb::pid_t pid) {
+ Error error = gdb_server.AttachToProcess(pid);
+ if (error.Fail()) {
+ fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
+ error.AsCString());
+ exit(1);
+ }
+}
+
+void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
+ const std::string &process_name) {
+ // FIXME implement.
+}
+
+void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
+ const std::string &attach_target) {
+ assert(!attach_target.empty() && "attach_target cannot be empty");
+
+ // First check if the attach_target is convertible to a long. If so, we'll use
+ // it as a pid.
+ char *end_p = nullptr;
+ const long int pid = strtol(attach_target.c_str(), &end_p, 10);
+
+ // We'll call it a match if the entire argument is consumed.
+ if (end_p &&
+ static_cast<size_t>(end_p - attach_target.c_str()) ==
+ attach_target.size())
+ handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
+ else
+ handle_attach_to_process_name(gdb_server, attach_target);
+}
+
+void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
+ const char *const argv[]) {
+ Error error;
+ error = gdb_server.SetLaunchArguments(argv, argc);
+ if (error.Fail()) {
+ fprintf(stderr, "error: failed to set launch args for '%s': %s\n", argv[0],
+ error.AsCString());
+ exit(1);
+ }
+
+ unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
+
+ error = gdb_server.SetLaunchFlags(launch_flags);
+ if (error.Fail()) {
+ fprintf(stderr, "error: failed to set launch flags for '%s': %s\n", argv[0],
+ error.AsCString());
+ exit(1);
+ }
+
+ error = gdb_server.LaunchProcess();
+ if (error.Fail()) {
+ fprintf(stderr, "error: failed to launch '%s': %s\n", argv[0],
+ error.AsCString());
+ exit(1);
+ }
+}
+
+Error writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
+ size_t bytes_written = 0;
+ // Write the port number as a C string with the NULL terminator.
+ return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
+ bytes_written);
+}
+
+Error writeSocketIdToPipe(const char *const named_pipe_path,
+ const std::string &socket_id) {
+ Pipe port_name_pipe;
+ // Wait for 10 seconds for pipe to be opened.
+ auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
+ std::chrono::seconds{10});
+ if (error.Fail())
+ return error;
+ return writeSocketIdToPipe(port_name_pipe, socket_id);
}
-void
-handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
-{
- // FIXME implement.
-}
-
-void
-handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
-{
- assert (!attach_target.empty () && "attach_target cannot be empty");
-
- // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
- char *end_p = nullptr;
- const long int pid = strtol (attach_target.c_str (), &end_p, 10);
-
- // We'll call it a match if the entire argument is consumed.
- if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
- handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
- else
- handle_attach_to_process_name (gdb_server, attach_target);
-}
-
-void
-handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
-{
- Error error;
- error = gdb_server.SetLaunchArguments (argv, argc);
- if (error.Fail ())
- {
- fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
- exit(1);
- }
-
- unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
-
- error = gdb_server.SetLaunchFlags (launch_flags);
- if (error.Fail ())
- {
- fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
- exit(1);
- }
-
- error = gdb_server.LaunchProcess ();
- if (error.Fail ())
- {
- fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
- exit(1);
- }
-}
-
-Error
-writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id)
-{
- size_t bytes_written = 0;
- // Write the port number as a C string with the NULL terminator.
- return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1, bytes_written);
-}
-
-Error
-writeSocketIdToPipe(const char *const named_pipe_path, const std::string &socket_id)
-{
- Pipe port_name_pipe;
- // Wait for 10 seconds for pipe to be opened.
- auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
- std::chrono::seconds{10});
- if (error.Fail())
- return error;
- return writeSocketIdToPipe(port_name_pipe, socket_id);
-}
-
-Error
-writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id)
-{
+Error writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id) {
#if defined(_WIN32)
- return Error("Unnamed pipes are not supported on Windows.");
+ return Error("Unnamed pipes are not supported on Windows.");
#else
- Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
- return writeSocketIdToPipe(port_pipe, socket_id);
+ Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
+ return writeSocketIdToPipe(port_pipe, socket_id);
#endif
}
-void
-ConnectToRemote(MainLoop &mainloop, GDBRemoteCommunicationServerLLGS &gdb_server,
- bool reverse_connect, const char *const host_and_port,
- const char *const progname, const char *const subcommand,
- const char *const named_pipe_path, int unnamed_pipe_fd)
-{
- Error error;
-
- if (host_and_port && host_and_port[0])
- {
- // Parse out host and port.
- std::string final_host_and_port;
- std::string connection_host;
- std::string connection_port;
- uint32_t connection_portno = 0;
-
- // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
- if (host_and_port[0] == ':')
- final_host_and_port.append ("localhost");
- final_host_and_port.append (host_and_port);
-
- const std::string::size_type colon_pos = final_host_and_port.find (':');
- if (colon_pos != std::string::npos)
- {
- connection_host = final_host_and_port.substr (0, colon_pos);
- connection_port = final_host_and_port.substr (colon_pos + 1);
- connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
- }
+void ConnectToRemote(MainLoop &mainloop,
+ GDBRemoteCommunicationServerLLGS &gdb_server,
+ bool reverse_connect, const char *const host_and_port,
+ const char *const progname, const char *const subcommand,
+ const char *const named_pipe_path, int unnamed_pipe_fd) {
+ Error error;
+
+ if (host_and_port && host_and_port[0]) {
+ // Parse out host and port.
+ std::string final_host_and_port;
+ std::string connection_host;
+ std::string connection_port;
+ uint32_t connection_portno = 0;
+
+ // If host_and_port starts with ':', default the host to be "localhost" and
+ // expect the remainder to be the port.
+ if (host_and_port[0] == ':')
+ final_host_and_port.append("localhost");
+ final_host_and_port.append(host_and_port);
+
+ const std::string::size_type colon_pos = final_host_and_port.find(':');
+ if (colon_pos != std::string::npos) {
+ connection_host = final_host_and_port.substr(0, colon_pos);
+ connection_port = final_host_and_port.substr(colon_pos + 1);
+ connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
+ }
- std::unique_ptr<Connection> connection_up;
+ std::unique_ptr<Connection> connection_up;
- if (reverse_connect)
- {
- // llgs will connect to the gdb-remote client.
-
- // Ensure we have a port number for the connection.
- if (connection_portno == 0)
- {
- fprintf (stderr, "error: port number must be specified on when using reverse connect");
- exit (1);
- }
-
- // Build the connection string.
- char connection_url[512];
- snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
-
- // Create the connection.
- connection_up.reset(new ConnectionFileDescriptor);
- auto connection_result = connection_up->Connect (connection_url, &error);
- if (connection_result != eConnectionStatusSuccess)
- {
- fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
- exit (-1);
- }
- if (error.Fail ())
- {
- fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
- exit (-1);
- }
- }
- else
- {
- std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(final_host_and_port, false, error));
- if (error.Fail())
- {
- fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
- exit(1);
- }
- error = acceptor_up->Listen(1);
- if (error.Fail())
- {
- fprintf(stderr, "failed to listen: %s\n", error.AsCString());
- exit(1);
- }
- const std::string socket_id = acceptor_up->GetLocalSocketId();
- if (!socket_id.empty())
- {
- // If we have a named pipe to write the socket id back to, do that now.
- if (named_pipe_path && named_pipe_path[0])
- {
- error = writeSocketIdToPipe (named_pipe_path, socket_id);
- if (error.Fail ())
- fprintf (stderr, "failed to write to the named pipe \'%s\': %s",
- named_pipe_path, error.AsCString());
- }
- // If we have an unnamed pipe to write the socket id back to, do that now.
- else if (unnamed_pipe_fd >= 0)
- {
- error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
- if (error.Fail())
- fprintf(stderr, "failed to write to the unnamed pipe: %s",
- error.AsCString());
- }
- }
- else
- {
- fprintf (stderr, "unable to get the socket id for the listening connection\n");
- }
-
- Connection* conn = nullptr;
- error = acceptor_up->Accept(false, conn);
- if (error.Fail())
- {
- printf ("failed to accept new connection: %s\n", error.AsCString());
- exit(1);
- }
- connection_up.reset(conn);
+ if (reverse_connect) {
+ // llgs will connect to the gdb-remote client.
+
+ // Ensure we have a port number for the connection.
+ if (connection_portno == 0) {
+ fprintf(stderr, "error: port number must be specified on when using "
+ "reverse connect");
+ exit(1);
+ }
+
+ // Build the connection string.
+ char connection_url[512];
+ snprintf(connection_url, sizeof(connection_url), "connect://%s",
+ final_host_and_port.c_str());
+
+ // Create the connection.
+ connection_up.reset(new ConnectionFileDescriptor);
+ auto connection_result = connection_up->Connect(connection_url, &error);
+ if (connection_result != eConnectionStatusSuccess) {
+ fprintf(stderr, "error: failed to connect to client at '%s' "
+ "(connection status: %d)",
+ connection_url, static_cast<int>(connection_result));
+ exit(-1);
+ }
+ if (error.Fail()) {
+ fprintf(stderr, "error: failed to connect to client at '%s': %s",
+ connection_url, error.AsCString());
+ exit(-1);
+ }
+ } else {
+ std::unique_ptr<Acceptor> acceptor_up(
+ Acceptor::Create(final_host_and_port, false, error));
+ if (error.Fail()) {
+ fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
+ exit(1);
+ }
+ error = acceptor_up->Listen(1);
+ if (error.Fail()) {
+ fprintf(stderr, "failed to listen: %s\n", error.AsCString());
+ exit(1);
+ }
+ const std::string socket_id = acceptor_up->GetLocalSocketId();
+ if (!socket_id.empty()) {
+ // If we have a named pipe to write the socket id back to, do that now.
+ if (named_pipe_path && named_pipe_path[0]) {
+ error = writeSocketIdToPipe(named_pipe_path, socket_id);
+ if (error.Fail())
+ fprintf(stderr, "failed to write to the named pipe \'%s\': %s",
+ named_pipe_path, error.AsCString());
}
- error = gdb_server.InitializeConnection (std::move(connection_up));
- if (error.Fail())
- {
- fprintf(stderr, "Failed to initialize connection: %s\n", error.AsCString());
- exit(-1);
+ // If we have an unnamed pipe to write the socket id back to, do that
+ // now.
+ else if (unnamed_pipe_fd >= 0) {
+ error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
+ if (error.Fail())
+ fprintf(stderr, "failed to write to the unnamed pipe: %s",
+ error.AsCString());
}
- printf ("Connection established.\n");
+ } else {
+ fprintf(stderr,
+ "unable to get the socket id for the listening connection\n");
+ }
+
+ Connection *conn = nullptr;
+ error = acceptor_up->Accept(false, conn);
+ if (error.Fail()) {
+ printf("failed to accept new connection: %s\n", error.AsCString());
+ exit(1);
+ }
+ connection_up.reset(conn);
+ }
+ error = gdb_server.InitializeConnection(std::move(connection_up));
+ if (error.Fail()) {
+ fprintf(stderr, "Failed to initialize connection: %s\n",
+ error.AsCString());
+ exit(-1);
}
+ printf("Connection established.\n");
+ }
}
//----------------------------------------------------------------------
// main
//----------------------------------------------------------------------
-int
-main_gdbserver (int argc, char *argv[])
-{
- Error error;
- MainLoop mainloop;
+int main_gdbserver(int argc, char *argv[]) {
+ Error error;
+ MainLoop mainloop;
#ifndef _WIN32
- // Setup signal handlers first thing.
- signal(SIGPIPE, SIG_IGN);
- MainLoop::SignalHandleUP sighup_handle = mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
+ // Setup signal handlers first thing.
+ signal(SIGPIPE, SIG_IGN);
+ MainLoop::SignalHandleUP sighup_handle =
+ mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
#endif
- const char *progname = argv[0];
- const char *subcommand = argv[1];
- argc--;
- argv++;
- int long_option_index = 0;
- int ch;
- std::string attach_target;
- std::string named_pipe_path;
- std::string log_file;
- StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
- int unnamed_pipe_fd = -1;
- bool reverse_connect = false;
+ const char *progname = argv[0];
+ const char *subcommand = argv[1];
+ argc--;
+ argv++;
+ int long_option_index = 0;
+ int ch;
+ std::string attach_target;
+ std::string named_pipe_path;
+ std::string log_file;
+ StringRef
+ log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
+ int unnamed_pipe_fd = -1;
+ bool reverse_connect = false;
- // ProcessLaunchInfo launch_info;
- ProcessAttachInfo attach_info;
+ // ProcessLaunchInfo launch_info;
+ ProcessAttachInfo attach_info;
- bool show_usage = false;
- int option_error = 0;
+ bool show_usage = false;
+ int option_error = 0;
#if __GLIBC__
- optind = 0;
+ optind = 0;
#else
- optreset = 1;
- optind = 1;
+ optreset = 1;
+ optind = 1;
#endif
- std::string short_options(OptionParser::GetShortOptionString(g_long_options));
+ std::string short_options(OptionParser::GetShortOptionString(g_long_options));
- while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
- {
- switch (ch)
- {
- case 0: // Any optional that auto set themselves will return 0
- break;
-
- case 'l': // Set Log File
- if (optarg && optarg[0])
- log_file.assign(optarg);
- break;
-
- case 'c': // Log Channels
- if (optarg && optarg[0])
- log_channels = StringRef(optarg);
- break;
-
- case 'N': // named pipe
- if (optarg && optarg[0])
- named_pipe_path = optarg;
- break;
-
- case 'U': // unnamed pipe
- if (optarg && optarg[0])
- unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
- break;
-
- case 'r':
- // Do nothing, native regs is the default these days
- break;
-
- case 'R':
- reverse_connect = true;
- break;
+ while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
+ g_long_options, &long_option_index)) != -1) {
+ switch (ch) {
+ case 0: // Any optional that auto set themselves will return 0
+ break;
+
+ case 'l': // Set Log File
+ if (optarg && optarg[0])
+ log_file.assign(optarg);
+ break;
+
+ case 'c': // Log Channels
+ if (optarg && optarg[0])
+ log_channels = StringRef(optarg);
+ break;
+
+ case 'N': // named pipe
+ if (optarg && optarg[0])
+ named_pipe_path = optarg;
+ break;
+
+ case 'U': // unnamed pipe
+ if (optarg && optarg[0])
+ unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
+ break;
+
+ case 'r':
+ // Do nothing, native regs is the default these days
+ break;
+
+ case 'R':
+ reverse_connect = true;
+ break;
#ifndef _WIN32
- case 'S':
- // Put llgs into a new session. Terminals group processes
- // into sessions and when a special terminal key sequences
- // (like control+c) are typed they can cause signals to go out to
- // all processes in a session. Using this --setsid (-S) option
- // will cause debugserver to run in its own sessions and be free
- // from such issues.
- //
- // This is useful when llgs is spawned from a command
- // line application that uses llgs to do the debugging,
- // yet that application doesn't want llgs receiving the
- // signals sent to the session (i.e. dying when anyone hits ^C).
- {
- const ::pid_t new_sid = setsid();
- if (new_sid == -1)
- {
- const char *errno_str = strerror(errno);
- fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
- }
- }
- break;
-#endif
-
- case 'a': // attach {pid|process_name}
- if (optarg && optarg[0])
- attach_target = optarg;
- break;
-
- case 'h': /* fall-through is intentional */
- case '?':
- show_usage = true;
- break;
+ case 'S':
+ // Put llgs into a new session. Terminals group processes
+ // into sessions and when a special terminal key sequences
+ // (like control+c) are typed they can cause signals to go out to
+ // all processes in a session. Using this --setsid (-S) option
+ // will cause debugserver to run in its own sessions and be free
+ // from such issues.
+ //
+ // This is useful when llgs is spawned from a command
+ // line application that uses llgs to do the debugging,
+ // yet that application doesn't want llgs receiving the
+ // signals sent to the session (i.e. dying when anyone hits ^C).
+ {
+ const ::pid_t new_sid = setsid();
+ if (new_sid == -1) {
+ const char *errno_str = strerror(errno);
+ fprintf(stderr, "failed to set new session id for %s (%s)\n",
+ LLGS_PROGRAM_NAME,
+ errno_str ? errno_str : "<no error string>");
}
- }
-
- if (show_usage || option_error)
- {
- display_usage(progname, subcommand);
- exit(option_error);
- }
-
- if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, LLDB_LOG_OPTION_PREPEND_TIMESTAMP))
- return -1;
+ }
+ break;
+#endif
- Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
- if (log)
- {
- log->Printf ("lldb-server launch");
- for (int i = 0; i < argc; i++)
- {
- log->Printf ("argv[%i] = '%s'", i, argv[i]);
- }
+ case 'a': // attach {pid|process_name}
+ if (optarg && optarg[0])
+ attach_target = optarg;
+ break;
+
+ case 'h': /* fall-through is intentional */
+ case '?':
+ show_usage = true;
+ break;
}
+ }
- // Skip any options we consumed with getopt_long_only.
- argc -= optind;
- argv += optind;
-
- if (argc == 0)
- {
- display_usage(progname, subcommand);
- exit(255);
+ if (show_usage || option_error) {
+ display_usage(progname, subcommand);
+ exit(option_error);
+ }
+
+ if (!LLDBServerUtilities::SetupLogging(log_file, log_channels,
+ LLDB_LOG_OPTION_PREPEND_TIMESTAMP))
+ return -1;
+
+ Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_VERBOSE));
+ if (log) {
+ log->Printf("lldb-server launch");
+ for (int i = 0; i < argc; i++) {
+ log->Printf("argv[%i] = '%s'", i, argv[i]);
}
+ }
- GDBRemoteCommunicationServerLLGS gdb_server(mainloop);
-
- const char *const host_and_port = argv[0];
- argc -= 1;
- argv += 1;
-
- // Any arguments left over are for the program that we need to launch. If there
- // are no arguments, then the GDB server will start up and wait for an 'A' packet
- // to launch a program, or a vAttach packet to attach to an existing process, unless
- // explicitly asked to attach with the --attach={pid|program_name} form.
- if (!attach_target.empty ())
- handle_attach (gdb_server, attach_target);
- else if (argc > 0)
- handle_launch (gdb_server, argc, argv);
-
- // Print version info.
- printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
-
- ConnectToRemote(mainloop, gdb_server, reverse_connect,
- host_and_port, progname, subcommand,
- named_pipe_path.c_str(), unnamed_pipe_fd);
-
-
- if (! gdb_server.IsConnected())
- {
- fprintf (stderr, "no connection information provided, unable to run\n");
- display_usage (progname, subcommand);
- return 1;
- }
+ // Skip any options we consumed with getopt_long_only.
+ argc -= optind;
+ argv += optind;
+
+ if (argc == 0) {
+ display_usage(progname, subcommand);
+ exit(255);
+ }
+
+ GDBRemoteCommunicationServerLLGS gdb_server(mainloop);
+
+ const char *const host_and_port = argv[0];
+ argc -= 1;
+ argv += 1;
+
+ // Any arguments left over are for the program that we need to launch. If
+ // there
+ // are no arguments, then the GDB server will start up and wait for an 'A'
+ // packet
+ // to launch a program, or a vAttach packet to attach to an existing process,
+ // unless
+ // explicitly asked to attach with the --attach={pid|program_name} form.
+ if (!attach_target.empty())
+ handle_attach(gdb_server, attach_target);
+ else if (argc > 0)
+ handle_launch(gdb_server, argc, argv);
+
+ // Print version info.
+ printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
+
+ ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
+ progname, subcommand, named_pipe_path.c_str(),
+ unnamed_pipe_fd);
+
+ if (!gdb_server.IsConnected()) {
+ fprintf(stderr, "no connection information provided, unable to run\n");
+ display_usage(progname, subcommand);
+ return 1;
+ }
- mainloop.Run();
- fprintf(stderr, "lldb-server exiting...\n");
+ mainloop.Run();
+ fprintf(stderr, "lldb-server exiting...\n");
- return 0;
+ return 0;
}
Modified: lldb/trunk/tools/lldb-server/lldb-platform.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/lldb-platform.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/lldb-platform.cpp (original)
+++ lldb/trunk/tools/lldb-server/lldb-platform.cpp Tue Sep 6 15:57:50 2016
@@ -26,6 +26,10 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FileUtilities.h"
+#include "Acceptor.h"
+#include "LLDBServerUtilities.h"
+#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h"
+#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
#include "lldb/Core/Error.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/FileSpec.h"
@@ -33,10 +37,6 @@
#include "lldb/Host/HostGetOpt.h"
#include "lldb/Host/OptionParser.h"
#include "lldb/Host/common/TCPSocket.h"
-#include "Acceptor.h"
-#include "LLDBServerUtilities.h"
-#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h"
-#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
using namespace lldb;
using namespace lldb_private;
@@ -52,365 +52,335 @@ static int g_debug = 0;
static int g_verbose = 0;
static int g_server = 0;
-static struct option g_long_options[] =
-{
- { "debug", no_argument, &g_debug, 1 },
- { "verbose", no_argument, &g_verbose, 1 },
- { "log-file", required_argument, NULL, 'l' },
- { "log-channels", required_argument, NULL, 'c' },
- { "listen", required_argument, NULL, 'L' },
- { "port-offset", required_argument, NULL, 'p' },
- { "gdbserver-port", required_argument, NULL, 'P' },
- { "min-gdbserver-port", required_argument, NULL, 'm' },
- { "max-gdbserver-port", required_argument, NULL, 'M' },
- { "socket-file", required_argument, NULL, 'f' },
- { "server", no_argument, &g_server, 1 },
- { NULL, 0, NULL, 0 }
-};
-
-#if defined (__APPLE__)
-#define LOW_PORT (IPPORT_RESERVED)
-#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
+static struct option g_long_options[] = {
+ {"debug", no_argument, &g_debug, 1},
+ {"verbose", no_argument, &g_verbose, 1},
+ {"log-file", required_argument, NULL, 'l'},
+ {"log-channels", required_argument, NULL, 'c'},
+ {"listen", required_argument, NULL, 'L'},
+ {"port-offset", required_argument, NULL, 'p'},
+ {"gdbserver-port", required_argument, NULL, 'P'},
+ {"min-gdbserver-port", required_argument, NULL, 'm'},
+ {"max-gdbserver-port", required_argument, NULL, 'M'},
+ {"socket-file", required_argument, NULL, 'f'},
+ {"server", no_argument, &g_server, 1},
+ {NULL, 0, NULL, 0}};
+
+#if defined(__APPLE__)
+#define LOW_PORT (IPPORT_RESERVED)
+#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
#else
-#define LOW_PORT (1024u)
-#define HIGH_PORT (49151u)
+#define LOW_PORT (1024u)
+#define HIGH_PORT (49151u)
#endif
//----------------------------------------------------------------------
// Watch for signals
//----------------------------------------------------------------------
-static void
-signal_handler(int signo)
-{
- switch (signo)
- {
- case SIGHUP:
- // Use SIGINT first, if that does not work, use SIGHUP as a last resort.
- // And we should not call exit() here because it results in the global destructors
- // to be invoked and wreaking havoc on the threads still running.
- Host::SystemLog(Host::eSystemLogWarning, "SIGHUP received, exiting lldb-server...\n");
- abort();
- break;
- }
+static void signal_handler(int signo) {
+ switch (signo) {
+ case SIGHUP:
+ // Use SIGINT first, if that does not work, use SIGHUP as a last resort.
+ // And we should not call exit() here because it results in the global
+ // destructors
+ // to be invoked and wreaking havoc on the threads still running.
+ Host::SystemLog(Host::eSystemLogWarning,
+ "SIGHUP received, exiting lldb-server...\n");
+ abort();
+ break;
+ }
}
-static void
-display_usage (const char *progname, const char *subcommand)
-{
- fprintf(stderr, "Usage:\n %s %s [--log-file log-file-name] [--log-channels log-channel-list] [--port-file port-file-path] --server --listen port\n", progname, subcommand);
- exit(0);
+static void display_usage(const char *progname, const char *subcommand) {
+ fprintf(stderr, "Usage:\n %s %s [--log-file log-file-name] [--log-channels "
+ "log-channel-list] [--port-file port-file-path] --server "
+ "--listen port\n",
+ progname, subcommand);
+ exit(0);
}
-static Error
-save_socket_id_to_file(const std::string &socket_id, const FileSpec &file_spec)
-{
- FileSpec temp_file_spec(file_spec.GetDirectory().AsCString(), false);
- auto error = FileSystem::MakeDirectory(temp_file_spec, eFilePermissionsDirectoryDefault);
- if (error.Fail())
- return Error("Failed to create directory %s: %s", temp_file_spec.GetCString(), error.AsCString());
-
- llvm::SmallString<PATH_MAX> temp_file_path;
- temp_file_spec.AppendPathComponent("port-file.%%%%%%");
- auto err_code = llvm::sys::fs::createUniqueFile(temp_file_spec.GetCString(), temp_file_path);
- if (err_code)
- return Error("Failed to create temp file: %s", err_code.message().c_str());
-
- llvm::FileRemover tmp_file_remover(temp_file_path.c_str());
-
- {
- std::ofstream temp_file(temp_file_path.c_str(), std::ios::out);
- if (!temp_file.is_open())
- return Error("Failed to open temp file %s", temp_file_path.c_str());
- temp_file << socket_id;
- }
-
- err_code = llvm::sys::fs::rename(temp_file_path.c_str(), file_spec.GetPath().c_str());
- if (err_code)
- return Error("Failed to rename file %s to %s: %s",
- temp_file_path.c_str(), file_spec.GetPath().c_str(), err_code.message().c_str());
+static Error save_socket_id_to_file(const std::string &socket_id,
+ const FileSpec &file_spec) {
+ FileSpec temp_file_spec(file_spec.GetDirectory().AsCString(), false);
+ auto error = FileSystem::MakeDirectory(temp_file_spec,
+ eFilePermissionsDirectoryDefault);
+ if (error.Fail())
+ return Error("Failed to create directory %s: %s",
+ temp_file_spec.GetCString(), error.AsCString());
+
+ llvm::SmallString<PATH_MAX> temp_file_path;
+ temp_file_spec.AppendPathComponent("port-file.%%%%%%");
+ auto err_code = llvm::sys::fs::createUniqueFile(temp_file_spec.GetCString(),
+ temp_file_path);
+ if (err_code)
+ return Error("Failed to create temp file: %s", err_code.message().c_str());
+
+ llvm::FileRemover tmp_file_remover(temp_file_path.c_str());
+
+ {
+ std::ofstream temp_file(temp_file_path.c_str(), std::ios::out);
+ if (!temp_file.is_open())
+ return Error("Failed to open temp file %s", temp_file_path.c_str());
+ temp_file << socket_id;
+ }
+
+ err_code = llvm::sys::fs::rename(temp_file_path.c_str(),
+ file_spec.GetPath().c_str());
+ if (err_code)
+ return Error("Failed to rename file %s to %s: %s", temp_file_path.c_str(),
+ file_spec.GetPath().c_str(), err_code.message().c_str());
- tmp_file_remover.releaseFile();
- return Error();
+ tmp_file_remover.releaseFile();
+ return Error();
}
//----------------------------------------------------------------------
// main
//----------------------------------------------------------------------
-int
-main_platform (int argc, char *argv[])
-{
- const char *progname = argv[0];
- const char *subcommand = argv[1];
- argc--;
- argv++;
- signal (SIGPIPE, SIG_IGN);
- signal (SIGHUP, signal_handler);
- int long_option_index = 0;
- Error error;
- std::string listen_host_port;
- int ch;
-
- std::string log_file;
- StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
-
- GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap;
- int min_gdbserver_port = 0;
- int max_gdbserver_port = 0;
- uint16_t port_offset = 0;
-
- FileSpec socket_file;
- bool show_usage = false;
- int option_error = 0;
- int socket_error = -1;
-
- std::string short_options(OptionParser::GetShortOptionString(g_long_options));
-
+int main_platform(int argc, char *argv[]) {
+ const char *progname = argv[0];
+ const char *subcommand = argv[1];
+ argc--;
+ argv++;
+ signal(SIGPIPE, SIG_IGN);
+ signal(SIGHUP, signal_handler);
+ int long_option_index = 0;
+ Error error;
+ std::string listen_host_port;
+ int ch;
+
+ std::string log_file;
+ StringRef
+ log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
+
+ GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap;
+ int min_gdbserver_port = 0;
+ int max_gdbserver_port = 0;
+ uint16_t port_offset = 0;
+
+ FileSpec socket_file;
+ bool show_usage = false;
+ int option_error = 0;
+ int socket_error = -1;
+
+ std::string short_options(OptionParser::GetShortOptionString(g_long_options));
+
#if __GLIBC__
- optind = 0;
+ optind = 0;
#else
- optreset = 1;
- optind = 1;
+ optreset = 1;
+ optind = 1;
#endif
- while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
- {
- switch (ch)
- {
- case 0: // Any optional that auto set themselves will return 0
- break;
-
- case 'L':
- listen_host_port.append (optarg);
- break;
-
- case 'l': // Set Log File
- if (optarg && optarg[0])
- log_file.assign(optarg);
- break;
-
- case 'c': // Log Channels
- if (optarg && optarg[0])
- log_channels = StringRef(optarg);
- break;
-
- case 'f': // Socket file
- if (optarg && optarg[0])
- socket_file.SetFile(optarg, false);
- break;
-
- case 'p':
- {
- char *end = NULL;
- long tmp_port_offset = strtoul(optarg, &end, 0);
- if (end && *end == '\0')
- {
- if (LOW_PORT <= tmp_port_offset && tmp_port_offset <= HIGH_PORT)
- {
- port_offset = (uint16_t)tmp_port_offset;
- }
- else
- {
- fprintf (stderr, "error: port offset %li is not in the valid user port range of %u - %u\n", tmp_port_offset, LOW_PORT, HIGH_PORT);
- option_error = 5;
- }
- }
- else
- {
- fprintf (stderr, "error: invalid port offset string %s\n", optarg);
- option_error = 4;
- }
- }
- break;
-
- case 'P':
- case 'm':
- case 'M':
- {
- char *end = NULL;
- long portnum = strtoul(optarg, &end, 0);
- if (end && *end == '\0')
- {
- if (LOW_PORT <= portnum && portnum <= HIGH_PORT)
- {
- if (ch == 'P')
- gdbserver_portmap[(uint16_t)portnum] = LLDB_INVALID_PROCESS_ID;
- else if (ch == 'm')
- min_gdbserver_port = portnum;
- else
- max_gdbserver_port = portnum;
- }
- else
- {
- fprintf (stderr, "error: port number %li is not in the valid user port range of %u - %u\n", portnum, LOW_PORT, HIGH_PORT);
- option_error = 1;
- }
- }
- else
- {
- fprintf (stderr, "error: invalid port number string %s\n", optarg);
- option_error = 2;
- }
- }
- break;
-
- case 'h': /* fall-through is intentional */
- case '?':
- show_usage = true;
- break;
+ while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
+ g_long_options, &long_option_index)) != -1) {
+ switch (ch) {
+ case 0: // Any optional that auto set themselves will return 0
+ break;
+
+ case 'L':
+ listen_host_port.append(optarg);
+ break;
+
+ case 'l': // Set Log File
+ if (optarg && optarg[0])
+ log_file.assign(optarg);
+ break;
+
+ case 'c': // Log Channels
+ if (optarg && optarg[0])
+ log_channels = StringRef(optarg);
+ break;
+
+ case 'f': // Socket file
+ if (optarg && optarg[0])
+ socket_file.SetFile(optarg, false);
+ break;
+
+ case 'p': {
+ char *end = NULL;
+ long tmp_port_offset = strtoul(optarg, &end, 0);
+ if (end && *end == '\0') {
+ if (LOW_PORT <= tmp_port_offset && tmp_port_offset <= HIGH_PORT) {
+ port_offset = (uint16_t)tmp_port_offset;
+ } else {
+ fprintf(stderr, "error: port offset %li is not in the valid user "
+ "port range of %u - %u\n",
+ tmp_port_offset, LOW_PORT, HIGH_PORT);
+ option_error = 5;
+ }
+ } else {
+ fprintf(stderr, "error: invalid port offset string %s\n", optarg);
+ option_error = 4;
+ }
+ } break;
+
+ case 'P':
+ case 'm':
+ case 'M': {
+ char *end = NULL;
+ long portnum = strtoul(optarg, &end, 0);
+ if (end && *end == '\0') {
+ if (LOW_PORT <= portnum && portnum <= HIGH_PORT) {
+ if (ch == 'P')
+ gdbserver_portmap[(uint16_t)portnum] = LLDB_INVALID_PROCESS_ID;
+ else if (ch == 'm')
+ min_gdbserver_port = portnum;
+ else
+ max_gdbserver_port = portnum;
+ } else {
+ fprintf(stderr, "error: port number %li is not in the valid user "
+ "port range of %u - %u\n",
+ portnum, LOW_PORT, HIGH_PORT);
+ option_error = 1;
}
+ } else {
+ fprintf(stderr, "error: invalid port number string %s\n", optarg);
+ option_error = 2;
+ }
+ } break;
+
+ case 'h': /* fall-through is intentional */
+ case '?':
+ show_usage = true;
+ break;
}
+ }
- if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
- return -1;
+ if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
+ return -1;
- // Make a port map for a port range that was specified.
- if (min_gdbserver_port < max_gdbserver_port)
- {
- for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port)
- gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID;
- }
- else if (min_gdbserver_port != max_gdbserver_port)
- {
- fprintf (stderr, "error: --min-gdbserver-port (%u) is greater than --max-gdbserver-port (%u)\n", min_gdbserver_port, max_gdbserver_port);
- option_error = 3;
+ // Make a port map for a port range that was specified.
+ if (min_gdbserver_port < max_gdbserver_port) {
+ for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port)
+ gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID;
+ } else if (min_gdbserver_port != max_gdbserver_port) {
+ fprintf(stderr, "error: --min-gdbserver-port (%u) is greater than "
+ "--max-gdbserver-port (%u)\n",
+ min_gdbserver_port, max_gdbserver_port);
+ option_error = 3;
+ }
+
+ // Print usage and exit if no listening port is specified.
+ if (listen_host_port.empty())
+ show_usage = true;
+
+ if (show_usage || option_error) {
+ display_usage(progname, subcommand);
+ exit(option_error);
+ }
+
+ // Skip any options we consumed with getopt_long_only.
+ argc -= optind;
+ argv += optind;
+ lldb_private::Args inferior_arguments;
+ inferior_arguments.SetArguments(argc, const_cast<const char **>(argv));
+
+ const bool children_inherit_listen_socket = false;
+ // the test suite makes many connections in parallel, let's not miss any.
+ // The highest this should get reasonably is a function of the number
+ // of target CPUs. For now, let's just use 100.
+ const int backlog = 100;
+
+ std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(
+ listen_host_port, children_inherit_listen_socket, error));
+ if (error.Fail()) {
+ fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
+ exit(socket_error);
+ }
+
+ error = acceptor_up->Listen(backlog);
+ if (error.Fail()) {
+ printf("failed to listen: %s\n", error.AsCString());
+ exit(socket_error);
+ }
+ if (socket_file) {
+ error =
+ save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file);
+ if (error.Fail()) {
+ fprintf(stderr, "failed to write socket id to %s: %s\n",
+ socket_file.GetPath().c_str(), error.AsCString());
+ return 1;
}
+ }
- // Print usage and exit if no listening port is specified.
- if (listen_host_port.empty())
- show_usage = true;
-
- if (show_usage || option_error)
- {
- display_usage(progname, subcommand);
- exit(option_error);
- }
+ do {
+ GDBRemoteCommunicationServerPlatform platform(
+ acceptor_up->GetSocketProtocol(), acceptor_up->GetSocketScheme());
- // Skip any options we consumed with getopt_long_only.
- argc -= optind;
- argv += optind;
- lldb_private::Args inferior_arguments;
- inferior_arguments.SetArguments(argc, const_cast<const char**>(argv));
-
- const bool children_inherit_listen_socket = false;
- // the test suite makes many connections in parallel, let's not miss any.
- // The highest this should get reasonably is a function of the number
- // of target CPUs. For now, let's just use 100.
- const int backlog = 100;
-
- std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(listen_host_port, children_inherit_listen_socket, error));
- if (error.Fail())
- {
- fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
- exit(socket_error);
+ if (port_offset > 0)
+ platform.SetPortOffset(port_offset);
+
+ if (!gdbserver_portmap.empty()) {
+ platform.SetPortMap(std::move(gdbserver_portmap));
}
- error = acceptor_up->Listen(backlog);
- if (error.Fail())
- {
- printf("failed to listen: %s\n", error.AsCString());
- exit(socket_error);
+ const bool children_inherit_accept_socket = true;
+ Connection *conn = nullptr;
+ error = acceptor_up->Accept(children_inherit_accept_socket, conn);
+ if (error.Fail()) {
+ printf("error: %s\n", error.AsCString());
+ exit(socket_error);
}
- if (socket_file)
- {
- error = save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file);
- if (error.Fail())
- {
- fprintf(stderr, "failed to write socket id to %s: %s\n", socket_file.GetPath().c_str(), error.AsCString());
- return 1;
- }
+ printf("Connection established.\n");
+ if (g_server) {
+ // Collect child zombie processes.
+ while (waitpid(-1, nullptr, WNOHANG) > 0)
+ ;
+ if (fork()) {
+ // Parent doesn't need a connection to the lldb client
+ delete conn;
+
+ // Parent will continue to listen for new connections.
+ continue;
+ } else {
+ // Child process will handle the connection and exit.
+ g_server = 0;
+ // Listening socket is owned by parent process.
+ acceptor_up.release();
+ }
+ } else {
+ // If not running as a server, this process will not accept
+ // connections while a connection is active.
+ acceptor_up.reset();
}
+ platform.SetConnection(conn);
- do {
- GDBRemoteCommunicationServerPlatform platform(acceptor_up->GetSocketProtocol(),
- acceptor_up->GetSocketScheme());
-
- if (port_offset > 0)
- platform.SetPortOffset(port_offset);
-
- if (!gdbserver_portmap.empty())
- {
- platform.SetPortMap(std::move(gdbserver_portmap));
- }
-
- const bool children_inherit_accept_socket = true;
- Connection* conn = nullptr;
- error = acceptor_up->Accept(children_inherit_accept_socket, conn);
- if (error.Fail())
- {
- printf ("error: %s\n", error.AsCString());
- exit(socket_error);
- }
- printf ("Connection established.\n");
- if (g_server)
- {
- // Collect child zombie processes.
- while (waitpid(-1, nullptr, WNOHANG) > 0);
- if (fork())
- {
- // Parent doesn't need a connection to the lldb client
- delete conn;
-
- // Parent will continue to listen for new connections.
- continue;
- }
- else
- {
- // Child process will handle the connection and exit.
- g_server = 0;
- // Listening socket is owned by parent process.
- acceptor_up.release();
- }
- }
+ if (platform.IsConnected()) {
+ if (inferior_arguments.GetArgumentCount() > 0) {
+ lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
+ uint16_t port = 0;
+ std::string socket_name;
+ Error error = platform.LaunchGDBServer(inferior_arguments,
+ "", // hostname
+ pid, port, socket_name);
+ if (error.Success())
+ platform.SetPendingGdbServer(pid, port, socket_name);
else
- {
- // If not running as a server, this process will not accept
- // connections while a connection is active.
- acceptor_up.reset();
+ fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString());
+ }
+
+ // After we connected, we need to get an initial ack from...
+ if (platform.HandshakeWithClient()) {
+ bool interrupt = false;
+ bool done = false;
+ while (!interrupt && !done) {
+ if (platform.GetPacketAndSendResponse(UINT32_MAX, error, interrupt,
+ done) !=
+ GDBRemoteCommunication::PacketResult::Success)
+ break;
}
- platform.SetConnection (conn);
- if (platform.IsConnected())
- {
- if (inferior_arguments.GetArgumentCount() > 0)
- {
- lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
- uint16_t port = 0;
- std::string socket_name;
- Error error = platform.LaunchGDBServer(inferior_arguments,
- "", // hostname
- pid,
- port,
- socket_name);
- if (error.Success())
- platform.SetPendingGdbServer(pid, port, socket_name);
- else
- fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString());
- }
-
- // After we connected, we need to get an initial ack from...
- if (platform.HandshakeWithClient())
- {
- bool interrupt = false;
- bool done = false;
- while (!interrupt && !done)
- {
- if (platform.GetPacketAndSendResponse (UINT32_MAX, error, interrupt, done) != GDBRemoteCommunication::PacketResult::Success)
- break;
- }
-
- if (error.Fail())
- {
- fprintf(stderr, "error: %s\n", error.AsCString());
- }
- }
- else
- {
- fprintf(stderr, "error: handshake with client failed\n");
- }
+ if (error.Fail()) {
+ fprintf(stderr, "error: %s\n", error.AsCString());
}
- } while (g_server);
+ } else {
+ fprintf(stderr, "error: handshake with client failed\n");
+ }
+ }
+ } while (g_server);
- fprintf(stderr, "lldb-server exiting...\n");
+ fprintf(stderr, "lldb-server exiting...\n");
- return 0;
+ return 0;
}
Modified: lldb/trunk/tools/lldb-server/lldb-server.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/tools/lldb-server/lldb-server.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/tools/lldb-server/lldb-server.cpp (original)
+++ lldb/trunk/tools/lldb-server/lldb-server.cpp Tue Sep 6 15:57:50 2016
@@ -7,8 +7,8 @@
//
//===----------------------------------------------------------------------===//
-#include "lldb/Initialization/SystemLifetimeManager.h"
#include "lldb/Initialization/SystemInitializerCommon.h"
+#include "lldb/Initialization/SystemLifetimeManager.h"
#include "lldb/lldb-private.h"
#include "llvm/ADT/STLExtras.h"
@@ -17,66 +17,57 @@
#include <stdio.h>
#include <stdlib.h>
-static llvm::ManagedStatic<lldb_private::SystemLifetimeManager> g_debugger_lifetime;
+static llvm::ManagedStatic<lldb_private::SystemLifetimeManager>
+ g_debugger_lifetime;
-static void
-display_usage (const char *progname)
-{
- fprintf(stderr, "Usage:\n"
- " %s v[ersion]\n"
- " %s g[dbserver] [options]\n"
- " %s p[latform] [options]\n"
- "Invoke subcommand for additional help\n", progname, progname, progname);
- exit(0);
+static void display_usage(const char *progname) {
+ fprintf(stderr, "Usage:\n"
+ " %s v[ersion]\n"
+ " %s g[dbserver] [options]\n"
+ " %s p[latform] [options]\n"
+ "Invoke subcommand for additional help\n",
+ progname, progname, progname);
+ exit(0);
}
// Forward declarations of subcommand main methods.
-int main_gdbserver (int argc, char *argv[]);
-int main_platform (int argc, char *argv[]);
+int main_gdbserver(int argc, char *argv[]);
+int main_platform(int argc, char *argv[]);
-static void
-initialize ()
-{
- g_debugger_lifetime->Initialize(llvm::make_unique<lldb_private::SystemInitializerCommon>(), nullptr);
+static void initialize() {
+ g_debugger_lifetime->Initialize(
+ llvm::make_unique<lldb_private::SystemInitializerCommon>(), nullptr);
}
-static void
-terminate ()
-{
- g_debugger_lifetime->Terminate();
-}
+static void terminate() { g_debugger_lifetime->Terminate(); }
//----------------------------------------------------------------------
// main
//----------------------------------------------------------------------
-int
-main (int argc, char *argv[])
-{
- int option_error = 0;
- const char *progname = argv[0];
- if (argc < 2)
- {
- display_usage(progname);
- exit(option_error);
- }
-
- switch (argv[1][0])
- {
- case 'g':
- initialize();
- main_gdbserver(argc, argv);
- terminate();
- break;
- case 'p':
- initialize();
- main_platform(argc, argv);
- terminate();
- break;
- case 'v':
- fprintf(stderr, "%s\n", lldb_private::GetVersion());
- break;
- default:
- display_usage(progname);
- exit(option_error);
- }
+int main(int argc, char *argv[]) {
+ int option_error = 0;
+ const char *progname = argv[0];
+ if (argc < 2) {
+ display_usage(progname);
+ exit(option_error);
+ }
+
+ switch (argv[1][0]) {
+ case 'g':
+ initialize();
+ main_gdbserver(argc, argv);
+ terminate();
+ break;
+ case 'p':
+ initialize();
+ main_platform(argc, argv);
+ terminate();
+ break;
+ case 'v':
+ fprintf(stderr, "%s\n", lldb_private::GetVersion());
+ break;
+ default:
+ display_usage(progname);
+ exit(option_error);
+ }
}
Modified: lldb/trunk/unittests/Core/BroadcasterTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Core/BroadcasterTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Core/BroadcasterTest.cpp (original)
+++ lldb/trunk/unittests/Core/BroadcasterTest.cpp Tue Sep 6 15:57:50 2016
@@ -18,55 +18,56 @@
using namespace lldb;
using namespace lldb_private;
-TEST(BroadcasterTest, BroadcastEvent)
-{
- EventSP event_sp;
- Broadcaster broadcaster(nullptr, "test-broadcaster");
-
- // Create a listener, sign it up, make sure it recieves an event.
- ListenerSP listener1_sp = Listener::MakeListener("test-listener1");
- const uint32_t event_mask1 = 1;
- EXPECT_EQ(event_mask1, listener1_sp->StartListeningForEvents(&broadcaster, event_mask1));
- broadcaster.BroadcastEvent(event_mask1, nullptr);
- EXPECT_TRUE(listener1_sp->GetNextEvent(event_sp));
- EXPECT_EQ(event_mask1, event_sp->GetType());
-
- {
- // Add one more listener, make sure it works as well.
- ListenerSP listener2_sp = Listener::MakeListener("test-listener2");
- const uint32_t event_mask2 = 1;
- EXPECT_EQ(event_mask2, listener2_sp->StartListeningForEvents(&broadcaster, event_mask1 | event_mask2));
- broadcaster.BroadcastEvent(event_mask2, nullptr);
- EXPECT_TRUE(listener2_sp->GetNextEvent(event_sp));
- EXPECT_EQ(event_mask2, event_sp->GetType());
-
- // Both listeners should get this event.
- broadcaster.BroadcastEvent(event_mask1, nullptr);
- EXPECT_TRUE(listener1_sp->GetNextEvent(event_sp));
- EXPECT_EQ(event_mask1, event_sp->GetType());
- EXPECT_TRUE(listener2_sp->GetNextEvent(event_sp));
- EXPECT_EQ(event_mask2, event_sp->GetType());
- }
+TEST(BroadcasterTest, BroadcastEvent) {
+ EventSP event_sp;
+ Broadcaster broadcaster(nullptr, "test-broadcaster");
+
+ // Create a listener, sign it up, make sure it recieves an event.
+ ListenerSP listener1_sp = Listener::MakeListener("test-listener1");
+ const uint32_t event_mask1 = 1;
+ EXPECT_EQ(event_mask1,
+ listener1_sp->StartListeningForEvents(&broadcaster, event_mask1));
+ broadcaster.BroadcastEvent(event_mask1, nullptr);
+ EXPECT_TRUE(listener1_sp->GetNextEvent(event_sp));
+ EXPECT_EQ(event_mask1, event_sp->GetType());
+
+ {
+ // Add one more listener, make sure it works as well.
+ ListenerSP listener2_sp = Listener::MakeListener("test-listener2");
+ const uint32_t event_mask2 = 1;
+ EXPECT_EQ(event_mask2, listener2_sp->StartListeningForEvents(
+ &broadcaster, event_mask1 | event_mask2));
+ broadcaster.BroadcastEvent(event_mask2, nullptr);
+ EXPECT_TRUE(listener2_sp->GetNextEvent(event_sp));
+ EXPECT_EQ(event_mask2, event_sp->GetType());
- // Now again only one listener should be active.
+ // Both listeners should get this event.
broadcaster.BroadcastEvent(event_mask1, nullptr);
EXPECT_TRUE(listener1_sp->GetNextEvent(event_sp));
EXPECT_EQ(event_mask1, event_sp->GetType());
+ EXPECT_TRUE(listener2_sp->GetNextEvent(event_sp));
+ EXPECT_EQ(event_mask2, event_sp->GetType());
+ }
+
+ // Now again only one listener should be active.
+ broadcaster.BroadcastEvent(event_mask1, nullptr);
+ EXPECT_TRUE(listener1_sp->GetNextEvent(event_sp));
+ EXPECT_EQ(event_mask1, event_sp->GetType());
}
-TEST(BroadcasterTest, EventTypeHasListeners)
-{
- EventSP event_sp;
- Broadcaster broadcaster(nullptr, "test-broadcaster");
-
- const uint32_t event_mask = 1;
- EXPECT_FALSE(broadcaster.EventTypeHasListeners(event_mask));
-
- {
- ListenerSP listener_sp = Listener::MakeListener("test-listener");
- EXPECT_EQ(event_mask, listener_sp->StartListeningForEvents(&broadcaster, event_mask));
- EXPECT_TRUE(broadcaster.EventTypeHasListeners(event_mask));
- }
+TEST(BroadcasterTest, EventTypeHasListeners) {
+ EventSP event_sp;
+ Broadcaster broadcaster(nullptr, "test-broadcaster");
+
+ const uint32_t event_mask = 1;
+ EXPECT_FALSE(broadcaster.EventTypeHasListeners(event_mask));
+
+ {
+ ListenerSP listener_sp = Listener::MakeListener("test-listener");
+ EXPECT_EQ(event_mask,
+ listener_sp->StartListeningForEvents(&broadcaster, event_mask));
+ EXPECT_TRUE(broadcaster.EventTypeHasListeners(event_mask));
+ }
- EXPECT_FALSE(broadcaster.EventTypeHasListeners(event_mask));
+ EXPECT_FALSE(broadcaster.EventTypeHasListeners(event_mask));
}
Modified: lldb/trunk/unittests/Core/DataExtractorTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Core/DataExtractorTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Core/DataExtractorTest.cpp (original)
+++ lldb/trunk/unittests/Core/DataExtractorTest.cpp Tue Sep 6 15:57:50 2016
@@ -8,7 +8,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -19,38 +20,39 @@
using namespace lldb_private;
-TEST(DataExtractorTest, GetBitfield)
-{
- uint8_t buffer[] = { 0x01, 0x23, 0x45, 0x67 };
- DataExtractor LE(buffer, sizeof(buffer), lldb::eByteOrderLittle, sizeof(void *));
- DataExtractor BE(buffer, sizeof(buffer), lldb::eByteOrderBig, sizeof(void *));
-
- lldb::offset_t offset;
-
- offset = 0;
- ASSERT_EQ(buffer[1], LE.GetMaxU64Bitfield(&offset, sizeof(buffer), 8, 8));
- offset = 0;
- ASSERT_EQ(buffer[1], BE.GetMaxU64Bitfield(&offset, sizeof(buffer), 8, 8));
-
- offset = 0;
- ASSERT_EQ(int8_t(buffer[1]), LE.GetMaxS64Bitfield(&offset, sizeof(buffer), 8, 8));
- offset = 0;
- ASSERT_EQ(int8_t(buffer[1]), BE.GetMaxS64Bitfield(&offset, sizeof(buffer), 8, 8));
+TEST(DataExtractorTest, GetBitfield) {
+ uint8_t buffer[] = {0x01, 0x23, 0x45, 0x67};
+ DataExtractor LE(buffer, sizeof(buffer), lldb::eByteOrderLittle,
+ sizeof(void *));
+ DataExtractor BE(buffer, sizeof(buffer), lldb::eByteOrderBig, sizeof(void *));
+
+ lldb::offset_t offset;
+
+ offset = 0;
+ ASSERT_EQ(buffer[1], LE.GetMaxU64Bitfield(&offset, sizeof(buffer), 8, 8));
+ offset = 0;
+ ASSERT_EQ(buffer[1], BE.GetMaxU64Bitfield(&offset, sizeof(buffer), 8, 8));
+
+ offset = 0;
+ ASSERT_EQ(int8_t(buffer[1]),
+ LE.GetMaxS64Bitfield(&offset, sizeof(buffer), 8, 8));
+ offset = 0;
+ ASSERT_EQ(int8_t(buffer[1]),
+ BE.GetMaxS64Bitfield(&offset, sizeof(buffer), 8, 8));
}
-TEST(DataExtractorTest, PeekData)
-{
- uint8_t buffer[] = { 0x01, 0x02, 0x03, 0x04 };
- DataExtractor E(buffer, sizeof buffer, lldb::eByteOrderLittle, 4);
-
- EXPECT_EQ(buffer + 0, E.PeekData(0, 0));
- EXPECT_EQ(buffer + 0, E.PeekData(0, 4));
- EXPECT_EQ(nullptr, E.PeekData(0, 5));
-
- EXPECT_EQ(buffer + 2, E.PeekData(2, 0));
- EXPECT_EQ(buffer + 2, E.PeekData(2, 2));
- EXPECT_EQ(nullptr, E.PeekData(2, 3));
+TEST(DataExtractorTest, PeekData) {
+ uint8_t buffer[] = {0x01, 0x02, 0x03, 0x04};
+ DataExtractor E(buffer, sizeof buffer, lldb::eByteOrderLittle, 4);
+
+ EXPECT_EQ(buffer + 0, E.PeekData(0, 0));
+ EXPECT_EQ(buffer + 0, E.PeekData(0, 4));
+ EXPECT_EQ(nullptr, E.PeekData(0, 5));
+
+ EXPECT_EQ(buffer + 2, E.PeekData(2, 0));
+ EXPECT_EQ(buffer + 2, E.PeekData(2, 2));
+ EXPECT_EQ(nullptr, E.PeekData(2, 3));
- EXPECT_EQ(buffer + 4, E.PeekData(4, 0));
- EXPECT_EQ(nullptr, E.PeekData(4, 1));
+ EXPECT_EQ(buffer + 4, E.PeekData(4, 0));
+ EXPECT_EQ(nullptr, E.PeekData(4, 1));
}
Modified: lldb/trunk/unittests/Core/ScalarTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Core/ScalarTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Core/ScalarTest.cpp (original)
+++ lldb/trunk/unittests/Core/ScalarTest.cpp Tue Sep 6 15:57:50 2016
@@ -8,135 +8,134 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
#include "gtest/gtest.h"
+#include "lldb/Core/DataExtractor.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Scalar.h"
-#include "lldb/Core/DataExtractor.h"
-#include "lldb/Host/Endian.h"
#include "lldb/Core/StreamString.h"
+#include "lldb/Host/Endian.h"
using namespace lldb_private;
-TEST(ScalarTest, RightShiftOperator)
-{
- int a = 0x00001000;
- int b = 0xFFFFFFFF;
- int c = 4;
- Scalar a_scalar(a);
- Scalar b_scalar(b);
- Scalar c_scalar(c);
- ASSERT_EQ(a >> c, a_scalar >> c_scalar);
- ASSERT_EQ(b >> c, b_scalar >> c_scalar);
-}
-
-TEST(ScalarTest, GetBytes)
-{
- int a = 0x01020304;
- long long b = 0x0102030405060708LL;
- float c = 1234567.89e42;
- double d = 1234567.89e42;
- char e[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
- char f[32] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
- 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
- Scalar a_scalar(a);
- Scalar b_scalar(b);
- Scalar c_scalar(c);
- Scalar d_scalar(d);
- Scalar e_scalar;
- Scalar f_scalar;
- DataExtractor e_data(e, sizeof(e), endian::InlHostByteOrder(), sizeof(void *));
- Error e_error = e_scalar.SetValueFromData(e_data, lldb::eEncodingUint, sizeof(e));
- DataExtractor f_data(f, sizeof(f), endian::InlHostByteOrder(), sizeof(void *));
- Error f_error = f_scalar.SetValueFromData(f_data, lldb::eEncodingUint, sizeof(f));
- ASSERT_EQ(0, memcmp(&a, a_scalar.GetBytes(), sizeof(a)));
- ASSERT_EQ(0, memcmp(&b, b_scalar.GetBytes(), sizeof(b)));
- ASSERT_EQ(0, memcmp(&c, c_scalar.GetBytes(), sizeof(c)));
- ASSERT_EQ(0, memcmp(&d, d_scalar.GetBytes(), sizeof(d)));
- ASSERT_EQ(0, e_error.Fail());
- ASSERT_EQ(0, memcmp(e, e_scalar.GetBytes(), sizeof(e)));
- ASSERT_EQ(0, f_error.Fail());
- ASSERT_EQ(0, memcmp(f, f_scalar.GetBytes(), sizeof(f)));
-}
-
-TEST(ScalarTest, CastOperations)
-{
- long long a = 0xf1f2f3f4f5f6f7f8LL;
- Scalar a_scalar(a);
- ASSERT_EQ((signed char)a, a_scalar.SChar());
- ASSERT_EQ((unsigned char)a, a_scalar.UChar());
- ASSERT_EQ((signed short)a, a_scalar.SShort());
- ASSERT_EQ((unsigned short)a, a_scalar.UShort());
- ASSERT_EQ((signed int)a, a_scalar.SInt());
- ASSERT_EQ((unsigned int)a, a_scalar.UInt());
- ASSERT_EQ((signed long)a, a_scalar.SLong());
- ASSERT_EQ((unsigned long)a, a_scalar.ULong());
- ASSERT_EQ((signed long long)a, a_scalar.SLongLong());
- ASSERT_EQ((unsigned long long)a, a_scalar.ULongLong());
-}
-
-TEST(ScalarTest, ExtractBitfield)
-{
- uint32_t len = sizeof(long long) * 8;
-
- long long a1 = 0xf1f2f3f4f5f6f7f8LL;
- long long b1 = 0xff1f2f3f4f5f6f7fLL;
- Scalar s_scalar(a1);
- ASSERT_TRUE(s_scalar.ExtractBitfield(0, 0));
- ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
- ASSERT_TRUE(s_scalar.ExtractBitfield(len, 0));
- ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
- ASSERT_TRUE(s_scalar.ExtractBitfield(len - 4, 4));
- ASSERT_EQ(0, memcmp(&b1, s_scalar.GetBytes(), sizeof(b1)));
-
- unsigned long long a2 = 0xf1f2f3f4f5f6f7f8ULL;
- unsigned long long b2 = 0x0f1f2f3f4f5f6f7fULL;
- Scalar u_scalar(a2);
- ASSERT_TRUE(u_scalar.ExtractBitfield(0, 0));
- ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
- ASSERT_TRUE(u_scalar.ExtractBitfield(len, 0));
- ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
- ASSERT_TRUE(u_scalar.ExtractBitfield(len - 4, 4));
- ASSERT_EQ(0, memcmp(&b2, u_scalar.GetBytes(), sizeof(b2)));
-}
-
-template <typename T>
-static std::string
-ScalarGetValue(T value)
-{
- StreamString stream;
- Scalar(value).GetValue(&stream, false);
- return stream.GetString();
-}
-
-TEST(ScalarTest, GetValue)
-{
- EXPECT_EQ("12345", ScalarGetValue<signed short>(12345));
- EXPECT_EQ("-12345", ScalarGetValue<signed short>(-12345));
- EXPECT_EQ("12345", ScalarGetValue<unsigned short>(12345));
- EXPECT_EQ(std::to_string(std::numeric_limits<unsigned short>::max()),
- ScalarGetValue(std::numeric_limits<unsigned short>::max()));
-
- EXPECT_EQ("12345", ScalarGetValue<signed int>(12345));
- EXPECT_EQ("-12345", ScalarGetValue<signed int>(-12345));
- EXPECT_EQ("12345", ScalarGetValue<unsigned int>(12345));
- EXPECT_EQ(std::to_string(std::numeric_limits<unsigned int>::max()),
- ScalarGetValue(std::numeric_limits<unsigned int>::max()));
-
- EXPECT_EQ("12345678", ScalarGetValue<signed long>(12345678L));
- EXPECT_EQ("-12345678", ScalarGetValue<signed long>(-12345678L));
- EXPECT_EQ("12345678", ScalarGetValue<unsigned long>(12345678UL));
- EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long>::max()),
- ScalarGetValue(std::numeric_limits<unsigned long>::max()));
-
- EXPECT_EQ("1234567890123", ScalarGetValue<signed long long>(1234567890123LL));
- EXPECT_EQ("-1234567890123", ScalarGetValue<signed long long>(-1234567890123LL));
- EXPECT_EQ("1234567890123", ScalarGetValue<unsigned long long>(1234567890123ULL));
- EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long long>::max()),
- ScalarGetValue(std::numeric_limits<unsigned long long>::max()));
+TEST(ScalarTest, RightShiftOperator) {
+ int a = 0x00001000;
+ int b = 0xFFFFFFFF;
+ int c = 4;
+ Scalar a_scalar(a);
+ Scalar b_scalar(b);
+ Scalar c_scalar(c);
+ ASSERT_EQ(a >> c, a_scalar >> c_scalar);
+ ASSERT_EQ(b >> c, b_scalar >> c_scalar);
+}
+
+TEST(ScalarTest, GetBytes) {
+ int a = 0x01020304;
+ long long b = 0x0102030405060708LL;
+ float c = 1234567.89e42;
+ double d = 1234567.89e42;
+ char e[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
+ char f[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
+ Scalar a_scalar(a);
+ Scalar b_scalar(b);
+ Scalar c_scalar(c);
+ Scalar d_scalar(d);
+ Scalar e_scalar;
+ Scalar f_scalar;
+ DataExtractor e_data(e, sizeof(e), endian::InlHostByteOrder(),
+ sizeof(void *));
+ Error e_error =
+ e_scalar.SetValueFromData(e_data, lldb::eEncodingUint, sizeof(e));
+ DataExtractor f_data(f, sizeof(f), endian::InlHostByteOrder(),
+ sizeof(void *));
+ Error f_error =
+ f_scalar.SetValueFromData(f_data, lldb::eEncodingUint, sizeof(f));
+ ASSERT_EQ(0, memcmp(&a, a_scalar.GetBytes(), sizeof(a)));
+ ASSERT_EQ(0, memcmp(&b, b_scalar.GetBytes(), sizeof(b)));
+ ASSERT_EQ(0, memcmp(&c, c_scalar.GetBytes(), sizeof(c)));
+ ASSERT_EQ(0, memcmp(&d, d_scalar.GetBytes(), sizeof(d)));
+ ASSERT_EQ(0, e_error.Fail());
+ ASSERT_EQ(0, memcmp(e, e_scalar.GetBytes(), sizeof(e)));
+ ASSERT_EQ(0, f_error.Fail());
+ ASSERT_EQ(0, memcmp(f, f_scalar.GetBytes(), sizeof(f)));
+}
+
+TEST(ScalarTest, CastOperations) {
+ long long a = 0xf1f2f3f4f5f6f7f8LL;
+ Scalar a_scalar(a);
+ ASSERT_EQ((signed char)a, a_scalar.SChar());
+ ASSERT_EQ((unsigned char)a, a_scalar.UChar());
+ ASSERT_EQ((signed short)a, a_scalar.SShort());
+ ASSERT_EQ((unsigned short)a, a_scalar.UShort());
+ ASSERT_EQ((signed int)a, a_scalar.SInt());
+ ASSERT_EQ((unsigned int)a, a_scalar.UInt());
+ ASSERT_EQ((signed long)a, a_scalar.SLong());
+ ASSERT_EQ((unsigned long)a, a_scalar.ULong());
+ ASSERT_EQ((signed long long)a, a_scalar.SLongLong());
+ ASSERT_EQ((unsigned long long)a, a_scalar.ULongLong());
+}
+
+TEST(ScalarTest, ExtractBitfield) {
+ uint32_t len = sizeof(long long) * 8;
+
+ long long a1 = 0xf1f2f3f4f5f6f7f8LL;
+ long long b1 = 0xff1f2f3f4f5f6f7fLL;
+ Scalar s_scalar(a1);
+ ASSERT_TRUE(s_scalar.ExtractBitfield(0, 0));
+ ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
+ ASSERT_TRUE(s_scalar.ExtractBitfield(len, 0));
+ ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
+ ASSERT_TRUE(s_scalar.ExtractBitfield(len - 4, 4));
+ ASSERT_EQ(0, memcmp(&b1, s_scalar.GetBytes(), sizeof(b1)));
+
+ unsigned long long a2 = 0xf1f2f3f4f5f6f7f8ULL;
+ unsigned long long b2 = 0x0f1f2f3f4f5f6f7fULL;
+ Scalar u_scalar(a2);
+ ASSERT_TRUE(u_scalar.ExtractBitfield(0, 0));
+ ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
+ ASSERT_TRUE(u_scalar.ExtractBitfield(len, 0));
+ ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
+ ASSERT_TRUE(u_scalar.ExtractBitfield(len - 4, 4));
+ ASSERT_EQ(0, memcmp(&b2, u_scalar.GetBytes(), sizeof(b2)));
+}
+
+template <typename T> static std::string ScalarGetValue(T value) {
+ StreamString stream;
+ Scalar(value).GetValue(&stream, false);
+ return stream.GetString();
+}
+
+TEST(ScalarTest, GetValue) {
+ EXPECT_EQ("12345", ScalarGetValue<signed short>(12345));
+ EXPECT_EQ("-12345", ScalarGetValue<signed short>(-12345));
+ EXPECT_EQ("12345", ScalarGetValue<unsigned short>(12345));
+ EXPECT_EQ(std::to_string(std::numeric_limits<unsigned short>::max()),
+ ScalarGetValue(std::numeric_limits<unsigned short>::max()));
+
+ EXPECT_EQ("12345", ScalarGetValue<signed int>(12345));
+ EXPECT_EQ("-12345", ScalarGetValue<signed int>(-12345));
+ EXPECT_EQ("12345", ScalarGetValue<unsigned int>(12345));
+ EXPECT_EQ(std::to_string(std::numeric_limits<unsigned int>::max()),
+ ScalarGetValue(std::numeric_limits<unsigned int>::max()));
+
+ EXPECT_EQ("12345678", ScalarGetValue<signed long>(12345678L));
+ EXPECT_EQ("-12345678", ScalarGetValue<signed long>(-12345678L));
+ EXPECT_EQ("12345678", ScalarGetValue<unsigned long>(12345678UL));
+ EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long>::max()),
+ ScalarGetValue(std::numeric_limits<unsigned long>::max()));
+
+ EXPECT_EQ("1234567890123", ScalarGetValue<signed long long>(1234567890123LL));
+ EXPECT_EQ("-1234567890123",
+ ScalarGetValue<signed long long>(-1234567890123LL));
+ EXPECT_EQ("1234567890123",
+ ScalarGetValue<unsigned long long>(1234567890123ULL));
+ EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long long>::max()),
+ ScalarGetValue(std::numeric_limits<unsigned long long>::max()));
}
Modified: lldb/trunk/unittests/Editline/EditlineTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Editline/EditlineTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Editline/EditlineTest.cpp (original)
+++ lldb/trunk/unittests/Editline/EditlineTest.cpp Tue Sep 6 15:57:50 2016
@@ -25,348 +25,289 @@
#include "lldb/Host/Pipe.h"
#include "lldb/Utility/PseudoTerminal.h"
-namespace
-{
- const size_t TIMEOUT_MILLIS = 5000;
+namespace {
+const size_t TIMEOUT_MILLIS = 5000;
}
-class FilePointer
-{
+class FilePointer {
public:
+ FilePointer() = delete;
- FilePointer () = delete;
+ FilePointer(const FilePointer &) = delete;
- FilePointer (const FilePointer&) = delete;
+ FilePointer(FILE *file_p) : _file_p(file_p) {}
- FilePointer (FILE *file_p)
- : _file_p (file_p)
- {
+ ~FilePointer() {
+ if (_file_p != nullptr) {
+ const int close_result = fclose(_file_p);
+ EXPECT_EQ(0, close_result);
}
+ }
- ~FilePointer ()
- {
- if (_file_p != nullptr)
- {
- const int close_result = fclose (_file_p);
- EXPECT_EQ(0, close_result);
- }
- }
-
- operator FILE* ()
- {
- return _file_p;
- }
+ operator FILE *() { return _file_p; }
private:
-
- FILE *_file_p;
-
+ FILE *_file_p;
};
/**
Wraps an Editline class, providing a simple way to feed
input (as if from the keyboard) and receive output from Editline.
*/
-class EditlineAdapter
-{
+class EditlineAdapter {
public:
+ EditlineAdapter();
- EditlineAdapter ();
-
- void
- CloseInput ();
+ void CloseInput();
- bool
- IsValid () const
- {
- return _editline_sp.get () != nullptr;
- }
+ bool IsValid() const { return _editline_sp.get() != nullptr; }
- lldb_private::Editline&
- GetEditline ()
- {
- return *_editline_sp;
- }
+ lldb_private::Editline &GetEditline() { return *_editline_sp; }
- bool
- SendLine (const std::string &line);
+ bool SendLine(const std::string &line);
- bool
- SendLines (const std::vector<std::string> &lines);
+ bool SendLines(const std::vector<std::string> &lines);
- bool
- GetLine (std::string &line, bool &interrupted, size_t timeout_millis);
+ bool GetLine(std::string &line, bool &interrupted, size_t timeout_millis);
- bool
- GetLines (lldb_private::StringList &lines, bool &interrupted, size_t timeout_millis);
+ bool GetLines(lldb_private::StringList &lines, bool &interrupted,
+ size_t timeout_millis);
- void
- ConsumeAllOutput ();
+ void ConsumeAllOutput();
private:
+ static bool IsInputComplete(lldb_private::Editline *editline,
+ lldb_private::StringList &lines, void *baton);
- static bool
- IsInputComplete (
- lldb_private::Editline * editline,
- lldb_private::StringList & lines,
- void * baton);
-
- std::unique_ptr<lldb_private::Editline> _editline_sp;
-
- lldb_utility::PseudoTerminal _pty;
- int _pty_master_fd;
- int _pty_slave_fd;
+ std::unique_ptr<lldb_private::Editline> _editline_sp;
- std::unique_ptr<FilePointer> _el_slave_file;
-};
+ lldb_utility::PseudoTerminal _pty;
+ int _pty_master_fd;
+ int _pty_slave_fd;
-EditlineAdapter::EditlineAdapter () :
- _editline_sp (),
- _pty (),
- _pty_master_fd (-1),
- _pty_slave_fd (-1),
- _el_slave_file ()
-{
- lldb_private::Error error;
-
- // Open the first master pty available.
- char error_string[256];
- error_string[0] = '\0';
- if (!_pty.OpenFirstAvailableMaster (O_RDWR, error_string, sizeof (error_string)))
- {
- fprintf(stderr, "failed to open first available master pty: '%s'\n", error_string);
- return;
- }
+ std::unique_ptr<FilePointer> _el_slave_file;
+};
- // Grab the master fd. This is a file descriptor we will:
- // (1) write to when we want to send input to editline.
- // (2) read from when we want to see what editline sends back.
- _pty_master_fd = _pty.GetMasterFileDescriptor();
-
- // Open the corresponding slave pty.
- if (!_pty.OpenSlave (O_RDWR, error_string, sizeof (error_string)))
- {
- fprintf(stderr, "failed to open slave pty: '%s'\n", error_string);
- return;
- }
- _pty_slave_fd = _pty.GetSlaveFileDescriptor();
+EditlineAdapter::EditlineAdapter()
+ : _editline_sp(), _pty(), _pty_master_fd(-1), _pty_slave_fd(-1),
+ _el_slave_file() {
+ lldb_private::Error error;
+
+ // Open the first master pty available.
+ char error_string[256];
+ error_string[0] = '\0';
+ if (!_pty.OpenFirstAvailableMaster(O_RDWR, error_string,
+ sizeof(error_string))) {
+ fprintf(stderr, "failed to open first available master pty: '%s'\n",
+ error_string);
+ return;
+ }
+
+ // Grab the master fd. This is a file descriptor we will:
+ // (1) write to when we want to send input to editline.
+ // (2) read from when we want to see what editline sends back.
+ _pty_master_fd = _pty.GetMasterFileDescriptor();
+
+ // Open the corresponding slave pty.
+ if (!_pty.OpenSlave(O_RDWR, error_string, sizeof(error_string))) {
+ fprintf(stderr, "failed to open slave pty: '%s'\n", error_string);
+ return;
+ }
+ _pty_slave_fd = _pty.GetSlaveFileDescriptor();
+
+ _el_slave_file.reset(new FilePointer(fdopen(_pty_slave_fd, "rw")));
+ EXPECT_FALSE(nullptr == *_el_slave_file);
+ if (*_el_slave_file == nullptr)
+ return;
+
+ // Create an Editline instance.
+ _editline_sp.reset(new lldb_private::Editline("gtest editor", *_el_slave_file,
+ *_el_slave_file,
+ *_el_slave_file, false));
+ _editline_sp->SetPrompt("> ");
+
+ // Hookup our input complete callback.
+ _editline_sp->SetIsInputCompleteCallback(IsInputComplete, this);
+}
+
+void EditlineAdapter::CloseInput() {
+ if (_el_slave_file != nullptr)
+ _el_slave_file.reset(nullptr);
+}
+
+bool EditlineAdapter::SendLine(const std::string &line) {
+ // Ensure we're valid before proceeding.
+ if (!IsValid())
+ return false;
+
+ // Write the line out to the pipe connected to editline's input.
+ ssize_t input_bytes_written =
+ ::write(_pty_master_fd, line.c_str(),
+ line.length() * sizeof(std::string::value_type));
+
+ const char *eoln = "\n";
+ const size_t eoln_length = strlen(eoln);
+ input_bytes_written =
+ ::write(_pty_master_fd, eoln, eoln_length * sizeof(char));
+
+ EXPECT_NE(-1, input_bytes_written) << strerror(errno);
+ EXPECT_EQ(eoln_length * sizeof(char), size_t(input_bytes_written));
+ return eoln_length * sizeof(char) == size_t(input_bytes_written);
+}
- _el_slave_file.reset (new FilePointer (fdopen (_pty_slave_fd, "rw")));
- EXPECT_FALSE (nullptr == *_el_slave_file);
- if (*_el_slave_file == nullptr)
- return;
-
- // Create an Editline instance.
- _editline_sp.reset (new lldb_private::Editline("gtest editor", *_el_slave_file, *_el_slave_file, *_el_slave_file, false));
- _editline_sp->SetPrompt ("> ");
-
- // Hookup our input complete callback.
- _editline_sp->SetIsInputCompleteCallback(IsInputComplete, this);
-}
-
-void
-EditlineAdapter::CloseInput ()
-{
- if (_el_slave_file != nullptr)
- _el_slave_file.reset (nullptr);
-}
-
-bool
-EditlineAdapter::SendLine (const std::string &line)
-{
- // Ensure we're valid before proceeding.
- if (!IsValid ())
- return false;
-
- // Write the line out to the pipe connected to editline's input.
- ssize_t input_bytes_written =
- ::write (_pty_master_fd,
- line.c_str(),
- line.length() * sizeof (std::string::value_type));
-
- const char *eoln = "\n";
- const size_t eoln_length = strlen(eoln);
- input_bytes_written =
- ::write (_pty_master_fd,
- eoln,
- eoln_length * sizeof (char));
-
- EXPECT_NE(-1, input_bytes_written) << strerror(errno);
- EXPECT_EQ (eoln_length * sizeof (char), size_t(input_bytes_written));
- return eoln_length * sizeof (char) == size_t(input_bytes_written);
-}
-
-bool
-EditlineAdapter::SendLines (const std::vector<std::string> &lines)
-{
- for (auto &line : lines)
- {
+bool EditlineAdapter::SendLines(const std::vector<std::string> &lines) {
+ for (auto &line : lines) {
#if EDITLINE_TEST_DUMP_OUTPUT
- printf ("<stdin> sending line \"%s\"\n", line.c_str());
+ printf("<stdin> sending line \"%s\"\n", line.c_str());
#endif
- if (!SendLine (line))
- return false;
- }
- return true;
+ if (!SendLine(line))
+ return false;
+ }
+ return true;
}
// We ignore the timeout for now.
-bool
-EditlineAdapter::GetLine (std::string &line, bool &interrupted, size_t /* timeout_millis */)
-{
- // Ensure we're valid before proceeding.
- if (!IsValid ())
- return false;
-
- _editline_sp->GetLine (line, interrupted);
- return true;
-}
-
-bool
-EditlineAdapter::GetLines (lldb_private::StringList &lines, bool &interrupted, size_t /* timeout_millis */)
-{
- // Ensure we're valid before proceeding.
- if (!IsValid ())
- return false;
-
- _editline_sp->GetLines (1, lines, interrupted);
- return true;
-}
-
-bool
-EditlineAdapter::IsInputComplete (
- lldb_private::Editline * editline,
- lldb_private::StringList & lines,
- void * baton)
-{
- // We'll call ourselves complete if we've received a balanced set of braces.
- int start_block_count = 0;
- int brace_balance = 0;
-
- for (size_t i = 0; i < lines.GetSize (); ++i)
- {
- for (auto ch : lines[i])
- {
- if (ch == '{')
- {
- ++start_block_count;
- ++brace_balance;
- }
- else if (ch == '}')
- --brace_balance;
- }
+bool EditlineAdapter::GetLine(std::string &line, bool &interrupted,
+ size_t /* timeout_millis */) {
+ // Ensure we're valid before proceeding.
+ if (!IsValid())
+ return false;
+
+ _editline_sp->GetLine(line, interrupted);
+ return true;
+}
+
+bool EditlineAdapter::GetLines(lldb_private::StringList &lines,
+ bool &interrupted, size_t /* timeout_millis */) {
+ // Ensure we're valid before proceeding.
+ if (!IsValid())
+ return false;
+
+ _editline_sp->GetLines(1, lines, interrupted);
+ return true;
+}
+
+bool EditlineAdapter::IsInputComplete(lldb_private::Editline *editline,
+ lldb_private::StringList &lines,
+ void *baton) {
+ // We'll call ourselves complete if we've received a balanced set of braces.
+ int start_block_count = 0;
+ int brace_balance = 0;
+
+ for (size_t i = 0; i < lines.GetSize(); ++i) {
+ for (auto ch : lines[i]) {
+ if (ch == '{') {
+ ++start_block_count;
+ ++brace_balance;
+ } else if (ch == '}')
+ --brace_balance;
}
+ }
- return (start_block_count > 0) && (brace_balance == 0);
+ return (start_block_count > 0) && (brace_balance == 0);
}
-void
-EditlineAdapter::ConsumeAllOutput ()
-{
- FilePointer output_file (fdopen (_pty_master_fd, "r"));
+void EditlineAdapter::ConsumeAllOutput() {
+ FilePointer output_file(fdopen(_pty_master_fd, "r"));
- int ch;
- while ((ch = fgetc(output_file)) != EOF)
- {
+ int ch;
+ while ((ch = fgetc(output_file)) != EOF) {
#if EDITLINE_TEST_DUMP_OUTPUT
- char display_str[] = { 0, 0, 0 };
- switch (ch)
- {
- case '\t':
- display_str[0] = '\\';
- display_str[1] = 't';
- break;
- case '\n':
- display_str[0] = '\\';
- display_str[1] = 'n';
- break;
- case '\r':
- display_str[0] = '\\';
- display_str[1] = 'r';
- break;
- default:
- display_str[0] = ch;
- break;
- }
- printf ("<stdout> 0x%02x (%03d) (%s)\n", ch, ch, display_str);
- // putc(ch, stdout);
-#endif
+ char display_str[] = {0, 0, 0};
+ switch (ch) {
+ case '\t':
+ display_str[0] = '\\';
+ display_str[1] = 't';
+ break;
+ case '\n':
+ display_str[0] = '\\';
+ display_str[1] = 'n';
+ break;
+ case '\r':
+ display_str[0] = '\\';
+ display_str[1] = 'r';
+ break;
+ default:
+ display_str[0] = ch;
+ break;
}
+ printf("<stdout> 0x%02x (%03d) (%s)\n", ch, ch, display_str);
+// putc(ch, stdout);
+#endif
+ }
}
-class EditlineTestFixture : public ::testing::Test
-{
+class EditlineTestFixture : public ::testing::Test {
private:
- EditlineAdapter _el_adapter;
- std::shared_ptr<std::thread> _sp_output_thread;
+ EditlineAdapter _el_adapter;
+ std::shared_ptr<std::thread> _sp_output_thread;
public:
- void SetUp()
- {
- // We need a TERM set properly for editline to work as expected.
- setenv("TERM", "vt100", 1);
-
- // Validate the editline adapter.
- EXPECT_TRUE(_el_adapter.IsValid());
- if (!_el_adapter.IsValid())
- return;
-
- // Dump output.
- _sp_output_thread.reset(new std::thread([&] { _el_adapter.ConsumeAllOutput(); }));
- }
+ void SetUp() {
+ // We need a TERM set properly for editline to work as expected.
+ setenv("TERM", "vt100", 1);
+
+ // Validate the editline adapter.
+ EXPECT_TRUE(_el_adapter.IsValid());
+ if (!_el_adapter.IsValid())
+ return;
+
+ // Dump output.
+ _sp_output_thread.reset(
+ new std::thread([&] { _el_adapter.ConsumeAllOutput(); }));
+ }
+
+ void TearDown() {
+ _el_adapter.CloseInput();
+ if (_sp_output_thread)
+ _sp_output_thread->join();
+ }
- void TearDown()
- {
- _el_adapter.CloseInput();
- if (_sp_output_thread)
- _sp_output_thread->join();
- }
-
- EditlineAdapter &GetEditlineAdapter() { return _el_adapter; }
+ EditlineAdapter &GetEditlineAdapter() { return _el_adapter; }
};
-TEST_F(EditlineTestFixture, EditlineReceivesSingleLineText)
-{
- // Send it some text via our virtual keyboard.
- const std::string input_text ("Hello, world");
- EXPECT_TRUE(GetEditlineAdapter().SendLine(input_text));
-
- // Verify editline sees what we put in.
- std::string el_reported_line;
- bool input_interrupted = false;
- const bool received_line = GetEditlineAdapter().GetLine(el_reported_line, input_interrupted, TIMEOUT_MILLIS);
-
- EXPECT_TRUE (received_line);
- EXPECT_FALSE (input_interrupted);
- EXPECT_EQ (input_text, el_reported_line);
-}
-
-TEST_F(EditlineTestFixture, EditlineReceivesMultiLineText)
-{
- // Send it some text via our virtual keyboard.
- std::vector<std::string> input_lines;
- input_lines.push_back ("int foo()");
- input_lines.push_back ("{");
- input_lines.push_back ("printf(\"Hello, world\");");
- input_lines.push_back ("}");
- input_lines.push_back ("");
-
- EXPECT_TRUE(GetEditlineAdapter().SendLines(input_lines));
-
- // Verify editline sees what we put in.
- lldb_private::StringList el_reported_lines;
- bool input_interrupted = false;
-
- EXPECT_TRUE(GetEditlineAdapter().GetLines(el_reported_lines, input_interrupted, TIMEOUT_MILLIS));
- EXPECT_FALSE (input_interrupted);
-
- // Without any auto indentation support, our output should directly match our input.
- EXPECT_EQ (input_lines.size (), el_reported_lines.GetSize ());
- if (input_lines.size () == el_reported_lines.GetSize ())
- {
- for (size_t i = 0; i < input_lines.size(); ++i)
- EXPECT_EQ (input_lines[i], el_reported_lines[i]);
- }
+TEST_F(EditlineTestFixture, EditlineReceivesSingleLineText) {
+ // Send it some text via our virtual keyboard.
+ const std::string input_text("Hello, world");
+ EXPECT_TRUE(GetEditlineAdapter().SendLine(input_text));
+
+ // Verify editline sees what we put in.
+ std::string el_reported_line;
+ bool input_interrupted = false;
+ const bool received_line = GetEditlineAdapter().GetLine(
+ el_reported_line, input_interrupted, TIMEOUT_MILLIS);
+
+ EXPECT_TRUE(received_line);
+ EXPECT_FALSE(input_interrupted);
+ EXPECT_EQ(input_text, el_reported_line);
+}
+
+TEST_F(EditlineTestFixture, EditlineReceivesMultiLineText) {
+ // Send it some text via our virtual keyboard.
+ std::vector<std::string> input_lines;
+ input_lines.push_back("int foo()");
+ input_lines.push_back("{");
+ input_lines.push_back("printf(\"Hello, world\");");
+ input_lines.push_back("}");
+ input_lines.push_back("");
+
+ EXPECT_TRUE(GetEditlineAdapter().SendLines(input_lines));
+
+ // Verify editline sees what we put in.
+ lldb_private::StringList el_reported_lines;
+ bool input_interrupted = false;
+
+ EXPECT_TRUE(GetEditlineAdapter().GetLines(el_reported_lines,
+ input_interrupted, TIMEOUT_MILLIS));
+ EXPECT_FALSE(input_interrupted);
+
+ // Without any auto indentation support, our output should directly match our
+ // input.
+ EXPECT_EQ(input_lines.size(), el_reported_lines.GetSize());
+ if (input_lines.size() == el_reported_lines.GetSize()) {
+ for (size_t i = 0; i < input_lines.size(); ++i)
+ EXPECT_EQ(input_lines[i], el_reported_lines[i]);
+ }
}
#endif
Modified: lldb/trunk/unittests/Expression/GoParserTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Expression/GoParserTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Expression/GoParserTest.cpp (original)
+++ lldb/trunk/unittests/Expression/GoParserTest.cpp Tue Sep 6 15:57:50 2016
@@ -1,4 +1,5 @@
-//===-- GoParserTest.cpp ------------------------------------------*- C++ -*-===//
+//===-- GoParserTest.cpp ------------------------------------------*- C++
+//-*-===//
//
// The LLVM Compiler Infrastructure
//
@@ -8,7 +9,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -17,234 +19,262 @@
#include "gtest/gtest.h"
-#include "lldb/Core/Error.h"
#include "Plugins/ExpressionParser/Go/GoParser.h"
+#include "lldb/Core/Error.h"
using namespace lldb_private;
-namespace
-{
-struct ASTPrinter
-{
- ASTPrinter(GoASTNode *n) { (*this)(n); }
-
- void
- operator()(GoASTNode *n)
- {
- if (n == nullptr)
- {
- m_stream << "nil ";
- return;
- }
- m_stream << "(" << n->GetKindName() << " ";
- n->WalkChildren(*this);
- if (auto *nn = llvm::dyn_cast<GoASTAssignStmt>(n))
- m_stream << nn->GetDefine() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTBasicLit>(n))
- m_stream << nn->GetValue().m_value.str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTBinaryExpr>(n))
- m_stream << GoLexer::LookupToken(nn->GetOp()).str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTIdent>(n))
- m_stream << nn->GetName().m_value.str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTBranchStmt>(n))
- m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTCallExpr>(n))
- m_stream << (nn->GetEllipsis() ? "..." : "") << " ";
- if (auto *nn = llvm::dyn_cast<GoASTChanType>(n))
- m_stream << nn->GetDir() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTGenDecl>(n))
- m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTIncDecStmt>(n))
- m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTRangeStmt>(n))
- m_stream << nn->GetDefine() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTSliceExpr>(n))
- m_stream << nn->GetSlice3() << " ";
- if (auto *nn = llvm::dyn_cast<GoASTUnaryExpr>(n))
- m_stream << GoLexer::LookupToken(nn->GetOp()).str() << " ";
- m_stream << ") ";
+namespace {
+struct ASTPrinter {
+ ASTPrinter(GoASTNode *n) { (*this)(n); }
+
+ void operator()(GoASTNode *n) {
+ if (n == nullptr) {
+ m_stream << "nil ";
+ return;
}
+ m_stream << "(" << n->GetKindName() << " ";
+ n->WalkChildren(*this);
+ if (auto *nn = llvm::dyn_cast<GoASTAssignStmt>(n))
+ m_stream << nn->GetDefine() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTBasicLit>(n))
+ m_stream << nn->GetValue().m_value.str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTBinaryExpr>(n))
+ m_stream << GoLexer::LookupToken(nn->GetOp()).str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTIdent>(n))
+ m_stream << nn->GetName().m_value.str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTBranchStmt>(n))
+ m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTCallExpr>(n))
+ m_stream << (nn->GetEllipsis() ? "..." : "") << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTChanType>(n))
+ m_stream << nn->GetDir() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTGenDecl>(n))
+ m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTIncDecStmt>(n))
+ m_stream << GoLexer::LookupToken(nn->GetTok()).str() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTRangeStmt>(n))
+ m_stream << nn->GetDefine() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTSliceExpr>(n))
+ m_stream << nn->GetSlice3() << " ";
+ if (auto *nn = llvm::dyn_cast<GoASTUnaryExpr>(n))
+ m_stream << GoLexer::LookupToken(nn->GetOp()).str() << " ";
+ m_stream << ") ";
+ }
- const std::string
- str() const
- {
- return m_stream.str();
- }
- std::stringstream m_stream;
+ const std::string str() const { return m_stream.str(); }
+ std::stringstream m_stream;
};
-testing::AssertionResult
-CheckStatement(const char *_s, const char *c_expr, const char *sexpr, const char *code)
-{
- GoParser parser(code);
- std::unique_ptr<GoASTStmt> stmt(parser.Statement());
- if (parser.Failed() || !stmt)
- {
- Error err;
- parser.GetError(err);
- return testing::AssertionFailure() << "Error parsing " << c_expr << "\n\t" << err.AsCString();
- }
- std::string actual_sexpr = ASTPrinter(stmt.get()).str();
- if (actual_sexpr == sexpr)
- return testing::AssertionSuccess();
- return testing::AssertionFailure() << "Parsing: " << c_expr << "\nExpected: " << sexpr
- << "\nGot: " << actual_sexpr;
+testing::AssertionResult CheckStatement(const char *_s, const char *c_expr,
+ const char *sexpr, const char *code) {
+ GoParser parser(code);
+ std::unique_ptr<GoASTStmt> stmt(parser.Statement());
+ if (parser.Failed() || !stmt) {
+ Error err;
+ parser.GetError(err);
+ return testing::AssertionFailure() << "Error parsing " << c_expr << "\n\t"
+ << err.AsCString();
+ }
+ std::string actual_sexpr = ASTPrinter(stmt.get()).str();
+ if (actual_sexpr == sexpr)
+ return testing::AssertionSuccess();
+ return testing::AssertionFailure() << "Parsing: " << c_expr
+ << "\nExpected: " << sexpr
+ << "\nGot: " << actual_sexpr;
}
} // namespace
#define EXPECT_PARSE(s, c) EXPECT_PRED_FORMAT2(CheckStatement, s, c)
-TEST(GoParserTest, ParseBasicLiterals)
-{
- EXPECT_PARSE("(ExprStmt (BasicLit 0 ) ) ", "0");
- EXPECT_PARSE("(ExprStmt (BasicLit 42 ) ) ", "42");
- EXPECT_PARSE("(ExprStmt (BasicLit 0600 ) ) ", "0600");
- EXPECT_PARSE("(ExprStmt (BasicLit 0xBadFace ) ) ", "0xBadFace");
- EXPECT_PARSE("(ExprStmt (BasicLit 170141183460469231731687303715884105727 ) ) ",
- "170141183460469231731687303715884105727");
-
- EXPECT_PARSE("(ExprStmt (BasicLit 0. ) ) ", "0.");
- EXPECT_PARSE("(ExprStmt (BasicLit 72.40 ) ) ", "72.40");
- EXPECT_PARSE("(ExprStmt (BasicLit 072.40 ) ) ", "072.40");
- EXPECT_PARSE("(ExprStmt (BasicLit 2.71828 ) ) ", "2.71828");
- EXPECT_PARSE("(ExprStmt (BasicLit 1.e+0 ) ) ", "1.e+0");
- EXPECT_PARSE("(ExprStmt (BasicLit 6.67428e-11 ) ) ", "6.67428e-11");
- EXPECT_PARSE("(ExprStmt (BasicLit 1E6 ) ) ", "1E6");
- EXPECT_PARSE("(ExprStmt (BasicLit .12345E+6 ) ) ", ".12345E+6");
-
- EXPECT_PARSE("(ExprStmt (BasicLit 0i ) ) ", "0i");
- EXPECT_PARSE("(ExprStmt (BasicLit 011i ) ) ", "011i");
- EXPECT_PARSE("(ExprStmt (BasicLit 0.i ) ) ", "0.i");
- EXPECT_PARSE("(ExprStmt (BasicLit 2.71828i ) ) ", "2.71828i");
- EXPECT_PARSE("(ExprStmt (BasicLit 6.67428e-11i ) ) ", "6.67428e-11i");
- EXPECT_PARSE("(ExprStmt (BasicLit 1E6i ) ) ", "1E6i");
- EXPECT_PARSE("(ExprStmt (BasicLit .12345E+6i ) ) ", ".12345E+6i");
-
- EXPECT_PARSE("(ExprStmt (BasicLit 'a' ) ) ", "'a'");
- EXPECT_PARSE("(ExprStmt (BasicLit '本' ) ) ", "'本'");
- EXPECT_PARSE("(ExprStmt (BasicLit \"abc\" ) ) ", "\"abc\"");
- EXPECT_PARSE("(ExprStmt (BasicLit `abc` ) ) ", "`abc`");
- EXPECT_PARSE("(ExprStmt (BasicLit `ab\nc` ) ) ", "`ab\nc`");
-}
-
-TEST(GoParserTest, ParseOperand)
-{
- EXPECT_PARSE("(ExprStmt (Ident a ) ) ", "a");
- EXPECT_PARSE("(ExprStmt (Ident _x9 ) ) ", "_x9");
- EXPECT_PARSE("(ExprStmt (Ident ThisVariableIsExported ) ) ", "ThisVariableIsExported");
- EXPECT_PARSE("(ExprStmt (Ident αβ ) ) ", "αβ");
-
- EXPECT_PARSE("(ExprStmt (SelectorExpr (Ident math ) (Ident Sin ) ) ) ", "math.Sin");
-}
-
-TEST(GoParserTest, ParseCompositeLiterals)
-{
- EXPECT_PARSE("(ExprStmt (CompositeLit (Ident Point3D ) ) ) ", "Point3D{}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (Ident Line ) (Ident origin ) (CompositeLit (Ident Point3D ) (KeyValueExpr "
- "(Ident y ) (UnaryExpr (BasicLit 4 ) - ) ) (KeyValueExpr (Ident z ) (BasicLit 12.3 ) ) ) ) ) ",
- "Line{origin, Point3D{y: -4, z: 12.3}}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 10 ) (Ident string ) ) ) ) ", "[10]string{}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 6 ) (Ident int ) ) (BasicLit 1 ) (BasicLit 2 ) "
- "(BasicLit 3 ) (BasicLit 5 ) ) ) ",
- "[6]int {1, 2, 3, 5}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType nil (Ident int ) ) (BasicLit 2 ) (BasicLit 3 ) (BasicLit 5 ) "
- "(BasicLit 7 ) (BasicLit 9 ) (BasicLit 2147483647 ) ) ) ",
- "[]int{2, 3, 5, 7, 9, 2147483647}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 128 ) (Ident bool ) ) (KeyValueExpr (BasicLit 'a' ) "
- "(Ident true ) ) (KeyValueExpr (BasicLit 'e' ) (Ident true ) ) (KeyValueExpr (BasicLit 'i' ) (Ident "
- "true ) ) (KeyValueExpr (BasicLit 'o' ) (Ident true ) ) (KeyValueExpr (BasicLit 'u' ) (Ident true ) ) "
- "(KeyValueExpr (BasicLit 'y' ) (Ident true ) ) ) ) ",
- "[128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 10 ) (Ident float32 ) ) (UnaryExpr (BasicLit 1 ) - ) "
- "(KeyValueExpr (BasicLit 4 ) (UnaryExpr (BasicLit 0.1 ) - ) ) (UnaryExpr (BasicLit 0.1 ) - ) "
- "(KeyValueExpr (BasicLit 9 ) (UnaryExpr (BasicLit 1 ) - ) ) ) ) ",
- "[10]float32{-1, 4: -0.1, -0.1, 9: -1}");
-}
-
-TEST(GoParserTest, ParseEllipsisArray)
-{
- EXPECT_PARSE(
- "(ExprStmt (CompositeLit (ArrayType (Ellipsis nil ) (Ident string ) ) (BasicLit `Sat` ) (BasicLit `Sun` ) ) ) ",
- "[...]string {`Sat`, `Sun`}");
- EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (Ellipsis nil ) (Ident Point ) ) (CompositeLit nil (BasicLit 1.5 "
- ") (UnaryExpr (BasicLit 3.5 ) - ) ) (CompositeLit nil (BasicLit 0 ) (BasicLit 0 ) ) ) ) ",
- "[...]Point{{1.5, -3.5}, {0, 0}}");
-}
-
-TEST(GoParserTest, ParseMap)
-{
- EXPECT_PARSE("(ExprStmt (CompositeLit (MapType (Ident string ) (Ident float32 ) ) (KeyValueExpr (BasicLit `C0` ) "
- "(BasicLit 16.35 ) ) (KeyValueExpr (BasicLit `D0` ) (BasicLit 18.35 ) ) ) ) ",
- "map[string]float32{`C0`: 16.35, `D0`: 18.35, }");
-}
-
-TEST(GoParserTest, UnaryExpr)
-{
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) + ) ) ", "+x");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) - ) ) ", "-x");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) ! ) ) ", "!x");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) ^ ) ) ", "^x");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) & ) ) ", "&x");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) <- ) ) ", "<-x");
- EXPECT_PARSE("(ExprStmt (StarExpr (Ident x ) ) ) ", "*x");
-}
-
-TEST(GoParserTest, BinaryExpr)
-{
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) || ) ) ", "a || b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) && ) ) ", "a && b");
-
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) == ) ) ", "a == b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) != ) ) ", "a != b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) < ) ) ", "a < b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) <= ) ) ", "a <= b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) > ) ) ", "a > b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) >= ) ) ", "a >= b");
-
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) + ) ) ", "a + b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) - ) ) ", "a - b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) | ) ) ", "a | b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) ^ ) ) ", "a ^ b");
-
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) * ) ) ", "a * b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) / ) ) ", "a / b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) % ) ) ", "a % b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) << ) ) ", "a << b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) >> ) ) ", "a >> b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) & ) ) ", "a & b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) &^ ) ) ", "a &^ b");
-
- EXPECT_PARSE(
- "(ExprStmt (BinaryExpr (BasicLit 23 ) (BinaryExpr (BasicLit 3 ) (IndexExpr (Ident x ) (Ident i ) ) * ) + ) ) ",
- "23 + 3*x[i]");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (UnaryExpr (UnaryExpr (Ident a ) + ) + ) + ) ) ", "a + + + a");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (UnaryExpr (Ident a ) ^ ) (Ident b ) >> ) ) ", "^a >> b");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (CallExpr (Ident f ) ) (CallExpr (Ident g ) ) || ) ) ", "f() || g()");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (BinaryExpr (Ident x ) (BinaryExpr (Ident y ) (BasicLit 1 ) + ) == ) "
- "(BinaryExpr (UnaryExpr (Ident chanPtr ) <- ) (BasicLit 0 ) > ) && ) ) ",
- "x == y+1 && <-chanPtr > 0");
-}
-
-TEST(GoParserTest, PrimaryExpr)
-{
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident x ) (CallExpr (Ident f ) ) <= ) ) ", "x <= f()");
- EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident s ) (BasicLit `.txt` ) + ) ) ", "(s + `.txt`)");
- EXPECT_PARSE("(ExprStmt (CallExpr (Ident f ) (BasicLit 3.1415 ) (Ident true ) ) ) ", "f(3.1415, true)");
- EXPECT_PARSE("(ExprStmt (CallExpr (Ident f ) (BasicLit 3.1415 ) (Ident a ) ... ) ) ", "f(3.1415, a...)");
- EXPECT_PARSE("(ExprStmt (IndexExpr (Ident m ) (BasicLit '1' ) ) ) ", "m['1']");
- EXPECT_PARSE("(ExprStmt (SliceExpr (Ident s ) (Ident i ) (BinaryExpr (Ident j ) (BasicLit 1 ) + ) nil 0 ) ) ",
- "s[i : j + 1]");
- EXPECT_PARSE("(ExprStmt (SelectorExpr (Ident obj ) (Ident color ) ) ) ", "obj.color");
- EXPECT_PARSE("(ExprStmt (CallExpr (SelectorExpr (IndexExpr (SelectorExpr (Ident f ) (Ident p ) ) (Ident i ) ) "
- "(Ident x ) ) ) ) ",
- "f.p[i].x()");
-}
-
-TEST(GoParserTest, Conversions)
-{
- EXPECT_PARSE("(ExprStmt (StarExpr (CallExpr (Ident Point ) (Ident p ) ) ) ) ", "*Point(p)");
- EXPECT_PARSE("(ExprStmt (CallExpr (StarExpr (Ident Point ) ) (Ident p ) ) ) ", "(*Point)(p)");
- EXPECT_PARSE("(ExprStmt (UnaryExpr (CallExpr (ChanType (Ident int ) 0 ) (Ident c ) ) <- ) ) ", "<-chan int(c)");
- EXPECT_PARSE("(ExprStmt (TypeAssertExpr (Ident y ) (SelectorExpr (Ident io ) (Ident Reader ) ) ) ) ",
- "y.(io.Reader)");
+TEST(GoParserTest, ParseBasicLiterals) {
+ EXPECT_PARSE("(ExprStmt (BasicLit 0 ) ) ", "0");
+ EXPECT_PARSE("(ExprStmt (BasicLit 42 ) ) ", "42");
+ EXPECT_PARSE("(ExprStmt (BasicLit 0600 ) ) ", "0600");
+ EXPECT_PARSE("(ExprStmt (BasicLit 0xBadFace ) ) ", "0xBadFace");
+ EXPECT_PARSE(
+ "(ExprStmt (BasicLit 170141183460469231731687303715884105727 ) ) ",
+ "170141183460469231731687303715884105727");
+
+ EXPECT_PARSE("(ExprStmt (BasicLit 0. ) ) ", "0.");
+ EXPECT_PARSE("(ExprStmt (BasicLit 72.40 ) ) ", "72.40");
+ EXPECT_PARSE("(ExprStmt (BasicLit 072.40 ) ) ", "072.40");
+ EXPECT_PARSE("(ExprStmt (BasicLit 2.71828 ) ) ", "2.71828");
+ EXPECT_PARSE("(ExprStmt (BasicLit 1.e+0 ) ) ", "1.e+0");
+ EXPECT_PARSE("(ExprStmt (BasicLit 6.67428e-11 ) ) ", "6.67428e-11");
+ EXPECT_PARSE("(ExprStmt (BasicLit 1E6 ) ) ", "1E6");
+ EXPECT_PARSE("(ExprStmt (BasicLit .12345E+6 ) ) ", ".12345E+6");
+
+ EXPECT_PARSE("(ExprStmt (BasicLit 0i ) ) ", "0i");
+ EXPECT_PARSE("(ExprStmt (BasicLit 011i ) ) ", "011i");
+ EXPECT_PARSE("(ExprStmt (BasicLit 0.i ) ) ", "0.i");
+ EXPECT_PARSE("(ExprStmt (BasicLit 2.71828i ) ) ", "2.71828i");
+ EXPECT_PARSE("(ExprStmt (BasicLit 6.67428e-11i ) ) ", "6.67428e-11i");
+ EXPECT_PARSE("(ExprStmt (BasicLit 1E6i ) ) ", "1E6i");
+ EXPECT_PARSE("(ExprStmt (BasicLit .12345E+6i ) ) ", ".12345E+6i");
+
+ EXPECT_PARSE("(ExprStmt (BasicLit 'a' ) ) ", "'a'");
+ EXPECT_PARSE("(ExprStmt (BasicLit '本' ) ) ", "'本'");
+ EXPECT_PARSE("(ExprStmt (BasicLit \"abc\" ) ) ", "\"abc\"");
+ EXPECT_PARSE("(ExprStmt (BasicLit `abc` ) ) ", "`abc`");
+ EXPECT_PARSE("(ExprStmt (BasicLit `ab\nc` ) ) ", "`ab\nc`");
+}
+
+TEST(GoParserTest, ParseOperand) {
+ EXPECT_PARSE("(ExprStmt (Ident a ) ) ", "a");
+ EXPECT_PARSE("(ExprStmt (Ident _x9 ) ) ", "_x9");
+ EXPECT_PARSE("(ExprStmt (Ident ThisVariableIsExported ) ) ",
+ "ThisVariableIsExported");
+ EXPECT_PARSE("(ExprStmt (Ident αβ ) ) ", "αβ");
+
+ EXPECT_PARSE("(ExprStmt (SelectorExpr (Ident math ) (Ident Sin ) ) ) ",
+ "math.Sin");
+}
+
+TEST(GoParserTest, ParseCompositeLiterals) {
+ EXPECT_PARSE("(ExprStmt (CompositeLit (Ident Point3D ) ) ) ", "Point3D{}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (Ident Line ) (Ident origin ) "
+ "(CompositeLit (Ident Point3D ) (KeyValueExpr "
+ "(Ident y ) (UnaryExpr (BasicLit 4 ) - ) ) (KeyValueExpr (Ident "
+ "z ) (BasicLit 12.3 ) ) ) ) ) ",
+ "Line{origin, Point3D{y: -4, z: 12.3}}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 10 ) (Ident "
+ "string ) ) ) ) ",
+ "[10]string{}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 6 ) (Ident int ) "
+ ") (BasicLit 1 ) (BasicLit 2 ) "
+ "(BasicLit 3 ) (BasicLit 5 ) ) ) ",
+ "[6]int {1, 2, 3, 5}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType nil (Ident int ) ) "
+ "(BasicLit 2 ) (BasicLit 3 ) (BasicLit 5 ) "
+ "(BasicLit 7 ) (BasicLit 9 ) (BasicLit 2147483647 ) ) ) ",
+ "[]int{2, 3, 5, 7, 9, 2147483647}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (BasicLit 128 ) (Ident bool "
+ ") ) (KeyValueExpr (BasicLit 'a' ) "
+ "(Ident true ) ) (KeyValueExpr (BasicLit 'e' ) (Ident true ) ) "
+ "(KeyValueExpr (BasicLit 'i' ) (Ident "
+ "true ) ) (KeyValueExpr (BasicLit 'o' ) (Ident true ) ) "
+ "(KeyValueExpr (BasicLit 'u' ) (Ident true ) ) "
+ "(KeyValueExpr (BasicLit 'y' ) (Ident true ) ) ) ) ",
+ "[128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': "
+ "true, 'y': true}");
+ EXPECT_PARSE(
+ "(ExprStmt (CompositeLit (ArrayType (BasicLit 10 ) (Ident float32 ) ) "
+ "(UnaryExpr (BasicLit 1 ) - ) "
+ "(KeyValueExpr (BasicLit 4 ) (UnaryExpr (BasicLit 0.1 ) - ) ) (UnaryExpr "
+ "(BasicLit 0.1 ) - ) "
+ "(KeyValueExpr (BasicLit 9 ) (UnaryExpr (BasicLit 1 ) - ) ) ) ) ",
+ "[10]float32{-1, 4: -0.1, -0.1, 9: -1}");
+}
+
+TEST(GoParserTest, ParseEllipsisArray) {
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (Ellipsis nil ) (Ident "
+ "string ) ) (BasicLit `Sat` ) (BasicLit `Sun` ) ) ) ",
+ "[...]string {`Sat`, `Sun`}");
+ EXPECT_PARSE("(ExprStmt (CompositeLit (ArrayType (Ellipsis nil ) (Ident "
+ "Point ) ) (CompositeLit nil (BasicLit 1.5 "
+ ") (UnaryExpr (BasicLit 3.5 ) - ) ) (CompositeLit nil (BasicLit "
+ "0 ) (BasicLit 0 ) ) ) ) ",
+ "[...]Point{{1.5, -3.5}, {0, 0}}");
+}
+
+TEST(GoParserTest, ParseMap) {
+ EXPECT_PARSE("(ExprStmt (CompositeLit (MapType (Ident string ) (Ident "
+ "float32 ) ) (KeyValueExpr (BasicLit `C0` ) "
+ "(BasicLit 16.35 ) ) (KeyValueExpr (BasicLit `D0` ) (BasicLit "
+ "18.35 ) ) ) ) ",
+ "map[string]float32{`C0`: 16.35, `D0`: 18.35, }");
+}
+
+TEST(GoParserTest, UnaryExpr) {
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) + ) ) ", "+x");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) - ) ) ", "-x");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) ! ) ) ", "!x");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) ^ ) ) ", "^x");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) & ) ) ", "&x");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (Ident x ) <- ) ) ", "<-x");
+ EXPECT_PARSE("(ExprStmt (StarExpr (Ident x ) ) ) ", "*x");
+}
+
+TEST(GoParserTest, BinaryExpr) {
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) || ) ) ", "a || b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) && ) ) ", "a && b");
+
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) == ) ) ", "a == b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) != ) ) ", "a != b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) < ) ) ", "a < b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) <= ) ) ", "a <= b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) > ) ) ", "a > b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) >= ) ) ", "a >= b");
+
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) + ) ) ", "a + b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) - ) ) ", "a - b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) | ) ) ", "a | b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) ^ ) ) ", "a ^ b");
+
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) * ) ) ", "a * b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) / ) ) ", "a / b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) % ) ) ", "a % b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) << ) ) ", "a << b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) >> ) ) ", "a >> b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) & ) ) ", "a & b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (Ident b ) &^ ) ) ", "a &^ b");
+
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (BasicLit 23 ) (BinaryExpr (BasicLit 3 ) "
+ "(IndexExpr (Ident x ) (Ident i ) ) * ) + ) ) ",
+ "23 + 3*x[i]");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident a ) (UnaryExpr (UnaryExpr (Ident "
+ "a ) + ) + ) + ) ) ",
+ "a + + + a");
+ EXPECT_PARSE(
+ "(ExprStmt (BinaryExpr (UnaryExpr (Ident a ) ^ ) (Ident b ) >> ) ) ",
+ "^a >> b");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (CallExpr (Ident f ) ) (CallExpr (Ident "
+ "g ) ) || ) ) ",
+ "f() || g()");
+ EXPECT_PARSE(
+ "(ExprStmt (BinaryExpr (BinaryExpr (Ident x ) (BinaryExpr (Ident y ) "
+ "(BasicLit 1 ) + ) == ) "
+ "(BinaryExpr (UnaryExpr (Ident chanPtr ) <- ) (BasicLit 0 ) > ) && ) ) ",
+ "x == y+1 && <-chanPtr > 0");
+}
+
+TEST(GoParserTest, PrimaryExpr) {
+ EXPECT_PARSE(
+ "(ExprStmt (BinaryExpr (Ident x ) (CallExpr (Ident f ) ) <= ) ) ",
+ "x <= f()");
+ EXPECT_PARSE("(ExprStmt (BinaryExpr (Ident s ) (BasicLit `.txt` ) + ) ) ",
+ "(s + `.txt`)");
+ EXPECT_PARSE(
+ "(ExprStmt (CallExpr (Ident f ) (BasicLit 3.1415 ) (Ident true ) ) ) ",
+ "f(3.1415, true)");
+ EXPECT_PARSE(
+ "(ExprStmt (CallExpr (Ident f ) (BasicLit 3.1415 ) (Ident a ) ... ) ) ",
+ "f(3.1415, a...)");
+ EXPECT_PARSE("(ExprStmt (IndexExpr (Ident m ) (BasicLit '1' ) ) ) ",
+ "m['1']");
+ EXPECT_PARSE("(ExprStmt (SliceExpr (Ident s ) (Ident i ) (BinaryExpr (Ident "
+ "j ) (BasicLit 1 ) + ) nil 0 ) ) ",
+ "s[i : j + 1]");
+ EXPECT_PARSE("(ExprStmt (SelectorExpr (Ident obj ) (Ident color ) ) ) ",
+ "obj.color");
+ EXPECT_PARSE("(ExprStmt (CallExpr (SelectorExpr (IndexExpr (SelectorExpr "
+ "(Ident f ) (Ident p ) ) (Ident i ) ) "
+ "(Ident x ) ) ) ) ",
+ "f.p[i].x()");
+}
+
+TEST(GoParserTest, Conversions) {
+ EXPECT_PARSE(
+ "(ExprStmt (StarExpr (CallExpr (Ident Point ) (Ident p ) ) ) ) ",
+ "*Point(p)");
+ EXPECT_PARSE(
+ "(ExprStmt (CallExpr (StarExpr (Ident Point ) ) (Ident p ) ) ) ",
+ "(*Point)(p)");
+ EXPECT_PARSE("(ExprStmt (UnaryExpr (CallExpr (ChanType (Ident int ) 0 ) "
+ "(Ident c ) ) <- ) ) ",
+ "<-chan int(c)");
+ EXPECT_PARSE("(ExprStmt (TypeAssertExpr (Ident y ) (SelectorExpr (Ident io ) "
+ "(Ident Reader ) ) ) ) ",
+ "y.(io.Reader)");
}
Modified: lldb/trunk/unittests/Host/FileSpecTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Host/FileSpecTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Host/FileSpecTest.cpp (original)
+++ lldb/trunk/unittests/Host/FileSpecTest.cpp Tue Sep 6 15:57:50 2016
@@ -13,105 +13,115 @@
using namespace lldb_private;
-TEST(FileSpecTest, FileAndDirectoryComponents)
-{
- FileSpec fs_posix("/foo/bar", false, FileSpec::ePathSyntaxPosix);
- EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
- EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
- EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
-
- FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
- EXPECT_STREQ("F:\\bar", fs_windows.GetCString());
- // EXPECT_STREQ("F:\\", fs_windows.GetDirectory().GetCString()); // It returns "F:/"
- EXPECT_STREQ("bar", fs_windows.GetFilename().GetCString());
-
- FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
- EXPECT_STREQ("/", fs_posix_root.GetCString());
- EXPECT_EQ(nullptr, fs_posix_root.GetDirectory().GetCString());
- EXPECT_STREQ("/", fs_posix_root.GetFilename().GetCString());
-
- FileSpec fs_windows_drive("F:", false, FileSpec::ePathSyntaxWindows);
- EXPECT_STREQ("F:", fs_windows_drive.GetCString());
- EXPECT_EQ(nullptr, fs_windows_drive.GetDirectory().GetCString());
- EXPECT_STREQ("F:", fs_windows_drive.GetFilename().GetCString());
-
- FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
- EXPECT_STREQ("F:\\", fs_windows_root.GetCString());
- EXPECT_STREQ("F:", fs_windows_root.GetDirectory().GetCString());
- // EXPECT_STREQ("\\", fs_windows_root.GetFilename().GetCString()); // It returns "/"
-
- FileSpec fs_posix_long("/foo/bar/baz", false, FileSpec::ePathSyntaxPosix);
- EXPECT_STREQ("/foo/bar/baz", fs_posix_long.GetCString());
- EXPECT_STREQ("/foo/bar", fs_posix_long.GetDirectory().GetCString());
- EXPECT_STREQ("baz", fs_posix_long.GetFilename().GetCString());
-
- FileSpec fs_windows_long("F:\\bar\\baz", false, FileSpec::ePathSyntaxWindows);
- EXPECT_STREQ("F:\\bar\\baz", fs_windows_long.GetCString());
- // EXPECT_STREQ("F:\\bar", fs_windows_long.GetDirectory().GetCString()); // It returns "F:/bar"
- EXPECT_STREQ("baz", fs_windows_long.GetFilename().GetCString());
-
- FileSpec fs_posix_trailing_slash("/foo/bar/", false, FileSpec::ePathSyntaxPosix);
- EXPECT_STREQ("/foo/bar/.", fs_posix_trailing_slash.GetCString());
- EXPECT_STREQ("/foo/bar", fs_posix_trailing_slash.GetDirectory().GetCString());
- EXPECT_STREQ(".", fs_posix_trailing_slash.GetFilename().GetCString());
-
- FileSpec fs_windows_trailing_slash("F:\\bar\\", false, FileSpec::ePathSyntaxWindows);
- EXPECT_STREQ("F:\\bar\\.", fs_windows_trailing_slash.GetCString());
- // EXPECT_STREQ("F:\\bar", fs_windows_trailing_slash.GetDirectory().GetCString()); // It returns "F:/bar"
- EXPECT_STREQ(".", fs_windows_trailing_slash.GetFilename().GetCString());
+TEST(FileSpecTest, FileAndDirectoryComponents) {
+ FileSpec fs_posix("/foo/bar", false, FileSpec::ePathSyntaxPosix);
+ EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
+ EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
+ EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
+
+ FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
+ EXPECT_STREQ("F:\\bar", fs_windows.GetCString());
+ // EXPECT_STREQ("F:\\", fs_windows.GetDirectory().GetCString()); // It returns
+ // "F:/"
+ EXPECT_STREQ("bar", fs_windows.GetFilename().GetCString());
+
+ FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
+ EXPECT_STREQ("/", fs_posix_root.GetCString());
+ EXPECT_EQ(nullptr, fs_posix_root.GetDirectory().GetCString());
+ EXPECT_STREQ("/", fs_posix_root.GetFilename().GetCString());
+
+ FileSpec fs_windows_drive("F:", false, FileSpec::ePathSyntaxWindows);
+ EXPECT_STREQ("F:", fs_windows_drive.GetCString());
+ EXPECT_EQ(nullptr, fs_windows_drive.GetDirectory().GetCString());
+ EXPECT_STREQ("F:", fs_windows_drive.GetFilename().GetCString());
+
+ FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
+ EXPECT_STREQ("F:\\", fs_windows_root.GetCString());
+ EXPECT_STREQ("F:", fs_windows_root.GetDirectory().GetCString());
+ // EXPECT_STREQ("\\", fs_windows_root.GetFilename().GetCString()); // It
+ // returns "/"
+
+ FileSpec fs_posix_long("/foo/bar/baz", false, FileSpec::ePathSyntaxPosix);
+ EXPECT_STREQ("/foo/bar/baz", fs_posix_long.GetCString());
+ EXPECT_STREQ("/foo/bar", fs_posix_long.GetDirectory().GetCString());
+ EXPECT_STREQ("baz", fs_posix_long.GetFilename().GetCString());
+
+ FileSpec fs_windows_long("F:\\bar\\baz", false, FileSpec::ePathSyntaxWindows);
+ EXPECT_STREQ("F:\\bar\\baz", fs_windows_long.GetCString());
+ // EXPECT_STREQ("F:\\bar", fs_windows_long.GetDirectory().GetCString()); // It
+ // returns "F:/bar"
+ EXPECT_STREQ("baz", fs_windows_long.GetFilename().GetCString());
+
+ FileSpec fs_posix_trailing_slash("/foo/bar/", false,
+ FileSpec::ePathSyntaxPosix);
+ EXPECT_STREQ("/foo/bar/.", fs_posix_trailing_slash.GetCString());
+ EXPECT_STREQ("/foo/bar", fs_posix_trailing_slash.GetDirectory().GetCString());
+ EXPECT_STREQ(".", fs_posix_trailing_slash.GetFilename().GetCString());
+
+ FileSpec fs_windows_trailing_slash("F:\\bar\\", false,
+ FileSpec::ePathSyntaxWindows);
+ EXPECT_STREQ("F:\\bar\\.", fs_windows_trailing_slash.GetCString());
+ // EXPECT_STREQ("F:\\bar",
+ // fs_windows_trailing_slash.GetDirectory().GetCString()); // It returns
+ // "F:/bar"
+ EXPECT_STREQ(".", fs_windows_trailing_slash.GetFilename().GetCString());
}
-TEST(FileSpecTest, AppendPathComponent)
-{
- FileSpec fs_posix("/foo", false, FileSpec::ePathSyntaxPosix);
- fs_posix.AppendPathComponent("bar");
- EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
- EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
- EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
-
- FileSpec fs_posix_2("/foo", false, FileSpec::ePathSyntaxPosix);
- fs_posix_2.AppendPathComponent("//bar/baz");
- EXPECT_STREQ("/foo/bar/baz", fs_posix_2.GetCString());
- EXPECT_STREQ("/foo/bar", fs_posix_2.GetDirectory().GetCString());
- EXPECT_STREQ("baz", fs_posix_2.GetFilename().GetCString());
-
- FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
- fs_windows.AppendPathComponent("baz");
- EXPECT_STREQ("F:\\bar\\baz", fs_windows.GetCString());
- // EXPECT_STREQ("F:\\bar", fs_windows.GetDirectory().GetCString()); // It returns "F:/bar"
- EXPECT_STREQ("baz", fs_windows.GetFilename().GetCString());
-
- FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
- fs_posix_root.AppendPathComponent("bar");
- EXPECT_STREQ("/bar", fs_posix_root.GetCString());
- EXPECT_STREQ("/", fs_posix_root.GetDirectory().GetCString());
- EXPECT_STREQ("bar", fs_posix_root.GetFilename().GetCString());
-
- FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
- fs_windows_root.AppendPathComponent("bar");
- EXPECT_STREQ("F:\\bar", fs_windows_root.GetCString());
- // EXPECT_STREQ("F:\\", fs_windows_root.GetDirectory().GetCString()); // It returns "F:/"
- EXPECT_STREQ("bar", fs_windows_root.GetFilename().GetCString());
+TEST(FileSpecTest, AppendPathComponent) {
+ FileSpec fs_posix("/foo", false, FileSpec::ePathSyntaxPosix);
+ fs_posix.AppendPathComponent("bar");
+ EXPECT_STREQ("/foo/bar", fs_posix.GetCString());
+ EXPECT_STREQ("/foo", fs_posix.GetDirectory().GetCString());
+ EXPECT_STREQ("bar", fs_posix.GetFilename().GetCString());
+
+ FileSpec fs_posix_2("/foo", false, FileSpec::ePathSyntaxPosix);
+ fs_posix_2.AppendPathComponent("//bar/baz");
+ EXPECT_STREQ("/foo/bar/baz", fs_posix_2.GetCString());
+ EXPECT_STREQ("/foo/bar", fs_posix_2.GetDirectory().GetCString());
+ EXPECT_STREQ("baz", fs_posix_2.GetFilename().GetCString());
+
+ FileSpec fs_windows("F:\\bar", false, FileSpec::ePathSyntaxWindows);
+ fs_windows.AppendPathComponent("baz");
+ EXPECT_STREQ("F:\\bar\\baz", fs_windows.GetCString());
+ // EXPECT_STREQ("F:\\bar", fs_windows.GetDirectory().GetCString()); // It
+ // returns "F:/bar"
+ EXPECT_STREQ("baz", fs_windows.GetFilename().GetCString());
+
+ FileSpec fs_posix_root("/", false, FileSpec::ePathSyntaxPosix);
+ fs_posix_root.AppendPathComponent("bar");
+ EXPECT_STREQ("/bar", fs_posix_root.GetCString());
+ EXPECT_STREQ("/", fs_posix_root.GetDirectory().GetCString());
+ EXPECT_STREQ("bar", fs_posix_root.GetFilename().GetCString());
+
+ FileSpec fs_windows_root("F:\\", false, FileSpec::ePathSyntaxWindows);
+ fs_windows_root.AppendPathComponent("bar");
+ EXPECT_STREQ("F:\\bar", fs_windows_root.GetCString());
+ // EXPECT_STREQ("F:\\", fs_windows_root.GetDirectory().GetCString()); // It
+ // returns "F:/"
+ EXPECT_STREQ("bar", fs_windows_root.GetFilename().GetCString());
}
-TEST(FileSpecTest, CopyByAppendingPathComponent)
-{
- FileSpec fs = FileSpec("/foo", false, FileSpec::ePathSyntaxPosix).CopyByAppendingPathComponent("bar");
- EXPECT_STREQ("/foo/bar", fs.GetCString());
- EXPECT_STREQ("/foo", fs.GetDirectory().GetCString());
- EXPECT_STREQ("bar", fs.GetFilename().GetCString());
+TEST(FileSpecTest, CopyByAppendingPathComponent) {
+ FileSpec fs = FileSpec("/foo", false, FileSpec::ePathSyntaxPosix)
+ .CopyByAppendingPathComponent("bar");
+ EXPECT_STREQ("/foo/bar", fs.GetCString());
+ EXPECT_STREQ("/foo", fs.GetDirectory().GetCString());
+ EXPECT_STREQ("bar", fs.GetFilename().GetCString());
}
-TEST(FileSpecTest, Equal)
-{
- FileSpec backward("C:\\foo\\bar", false, FileSpec::ePathSyntaxWindows);
- FileSpec forward("C:/foo/bar", false, FileSpec::ePathSyntaxWindows);
- EXPECT_EQ(forward, backward);
-
- const bool full_match = true;
- const bool remove_backup_dots = true;
- EXPECT_TRUE(FileSpec::Equal(forward, backward, full_match, remove_backup_dots));
- EXPECT_TRUE(FileSpec::Equal(forward, backward, full_match, !remove_backup_dots));
- EXPECT_TRUE(FileSpec::Equal(forward, backward, !full_match, remove_backup_dots));
- EXPECT_TRUE(FileSpec::Equal(forward, backward, !full_match, !remove_backup_dots));
+TEST(FileSpecTest, Equal) {
+ FileSpec backward("C:\\foo\\bar", false, FileSpec::ePathSyntaxWindows);
+ FileSpec forward("C:/foo/bar", false, FileSpec::ePathSyntaxWindows);
+ EXPECT_EQ(forward, backward);
+
+ const bool full_match = true;
+ const bool remove_backup_dots = true;
+ EXPECT_TRUE(
+ FileSpec::Equal(forward, backward, full_match, remove_backup_dots));
+ EXPECT_TRUE(
+ FileSpec::Equal(forward, backward, full_match, !remove_backup_dots));
+ EXPECT_TRUE(
+ FileSpec::Equal(forward, backward, !full_match, remove_backup_dots));
+ EXPECT_TRUE(
+ FileSpec::Equal(forward, backward, !full_match, !remove_backup_dots));
}
Modified: lldb/trunk/unittests/Host/SocketAddressTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Host/SocketAddressTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Host/SocketAddressTest.cpp (original)
+++ lldb/trunk/unittests/Host/SocketAddressTest.cpp Tue Sep 6 15:57:50 2016
@@ -7,68 +7,64 @@
//
//===----------------------------------------------------------------------===//
-
#include "gtest/gtest.h"
#include "lldb/Host/SocketAddress.h"
-namespace
-{
- class SocketAddressTest: public ::testing::Test
- {
- };
+namespace {
+class SocketAddressTest : public ::testing::Test {};
}
using namespace lldb_private;
-TEST_F (SocketAddressTest, Set)
-{
- SocketAddress sa;
- ASSERT_TRUE (sa.SetToLocalhost (AF_INET, 1138));
- ASSERT_STREQ ("127.0.0.1", sa.GetIPAddress ().c_str ());
- ASSERT_EQ (1138, sa.GetPort ());
-
- ASSERT_TRUE (sa.SetToAnyAddress (AF_INET, 0));
- ASSERT_STREQ ("0.0.0.0", sa.GetIPAddress ().c_str ());
- ASSERT_EQ (0, sa.GetPort ());
-
- ASSERT_TRUE (sa.SetToLocalhost (AF_INET6, 1139));
- ASSERT_TRUE(sa.GetIPAddress() == "::1" || sa.GetIPAddress() == "0:0:0:0:0:0:0:1") << "Address was: "
- << sa.GetIPAddress();
- ASSERT_EQ (1139, sa.GetPort ());
+TEST_F(SocketAddressTest, Set) {
+ SocketAddress sa;
+ ASSERT_TRUE(sa.SetToLocalhost(AF_INET, 1138));
+ ASSERT_STREQ("127.0.0.1", sa.GetIPAddress().c_str());
+ ASSERT_EQ(1138, sa.GetPort());
+
+ ASSERT_TRUE(sa.SetToAnyAddress(AF_INET, 0));
+ ASSERT_STREQ("0.0.0.0", sa.GetIPAddress().c_str());
+ ASSERT_EQ(0, sa.GetPort());
+
+ ASSERT_TRUE(sa.SetToLocalhost(AF_INET6, 1139));
+ ASSERT_TRUE(sa.GetIPAddress() == "::1" ||
+ sa.GetIPAddress() == "0:0:0:0:0:0:0:1")
+ << "Address was: " << sa.GetIPAddress();
+ ASSERT_EQ(1139, sa.GetPort());
}
#ifdef _WIN32
// we need to test our inet_ntop implementation for Windows XP
-const char* inet_ntop (int af, const void * src,
- char * dst, socklen_t size);
+const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
-TEST_F (SocketAddressTest, inet_ntop)
-{
- const uint8_t address4[4] = {255, 0, 1, 100};
- const uint8_t address6[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 255, 0};
-
- char buffer[INET6_ADDRSTRLEN];
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ ("1:203:405:607:809:a0b:c0d:ff00", inet_ntop (AF_INET6, address6, buffer, sizeof (buffer)));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ ("1:203:405:607:809:a0b:c0d:ff00", inet_ntop (AF_INET6, address6, buffer, 31));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ (nullptr, inet_ntop (AF_INET6, address6, buffer, 0));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ (nullptr, inet_ntop (AF_INET6, address6, buffer, 30));
-
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ ("255.0.1.100", inet_ntop (AF_INET, address4, buffer, sizeof (buffer)));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ ("255.0.1.100", inet_ntop (AF_INET, address4, buffer, 12));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ (nullptr, inet_ntop (AF_INET, address4, buffer, 0));
- memset (buffer, 'x', sizeof (buffer));
- EXPECT_STREQ (nullptr, inet_ntop (AF_INET, address4, buffer, 11));
+TEST_F(SocketAddressTest, inet_ntop) {
+ const uint8_t address4[4] = {255, 0, 1, 100};
+ const uint8_t address6[16] = {0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 255, 0};
+
+ char buffer[INET6_ADDRSTRLEN];
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ("1:203:405:607:809:a0b:c0d:ff00",
+ inet_ntop(AF_INET6, address6, buffer, sizeof(buffer)));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ("1:203:405:607:809:a0b:c0d:ff00",
+ inet_ntop(AF_INET6, address6, buffer, 31));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ(nullptr, inet_ntop(AF_INET6, address6, buffer, 0));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ(nullptr, inet_ntop(AF_INET6, address6, buffer, 30));
+
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ("255.0.1.100",
+ inet_ntop(AF_INET, address4, buffer, sizeof(buffer)));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ("255.0.1.100", inet_ntop(AF_INET, address4, buffer, 12));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ(nullptr, inet_ntop(AF_INET, address4, buffer, 0));
+ memset(buffer, 'x', sizeof(buffer));
+ EXPECT_STREQ(nullptr, inet_ntop(AF_INET, address4, buffer, 11));
}
#endif
-
-
Modified: lldb/trunk/unittests/Host/SocketTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Host/SocketTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Host/SocketTest.cpp (original)
+++ lldb/trunk/unittests/Host/SocketTest.cpp Tue Sep 6 15:57:50 2016
@@ -8,7 +8,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -30,182 +31,189 @@
using namespace lldb_private;
-class SocketTest : public testing::Test
-{
- public:
- void
- SetUp() override
- {
+class SocketTest : public testing::Test {
+public:
+ void SetUp() override {
#if defined(_MSC_VER)
- WSADATA data;
- ::WSAStartup(MAKEWORD(2, 2), &data);
+ WSADATA data;
+ ::WSAStartup(MAKEWORD(2, 2), &data);
#endif
- }
+ }
- void
- TearDown() override
- {
+ void TearDown() override {
#if defined(_MSC_VER)
- ::WSACleanup();
+ ::WSACleanup();
#endif
- }
+ }
- protected:
- static void
- AcceptThread(Socket *listen_socket, const char *listen_remote_address, bool child_processes_inherit,
- Socket **accept_socket, Error *error)
- {
- *error = listen_socket->Accept(listen_remote_address, child_processes_inherit, *accept_socket);
- }
-
- template<typename SocketType>
- void
- CreateConnectedSockets(const char *listen_remote_address, const std::function<std::string(const SocketType&)> &get_connect_addr, std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up)
- {
- bool child_processes_inherit = false;
- Error error;
- std::unique_ptr<SocketType> listen_socket_up(new SocketType(child_processes_inherit, error));
- EXPECT_FALSE(error.Fail());
- error = listen_socket_up->Listen(listen_remote_address, 5);
- EXPECT_FALSE(error.Fail());
- EXPECT_TRUE(listen_socket_up->IsValid());
-
- Error accept_error;
- Socket *accept_socket;
- std::thread accept_thread(AcceptThread, listen_socket_up.get(), listen_remote_address, child_processes_inherit,
- &accept_socket, &accept_error);
-
- std::string connect_remote_address = get_connect_addr(*listen_socket_up);
- std::unique_ptr<SocketType> connect_socket_up(new SocketType(child_processes_inherit, error));
- EXPECT_FALSE(error.Fail());
- error = connect_socket_up->Connect(connect_remote_address.c_str());
- EXPECT_FALSE(error.Fail());
- EXPECT_TRUE(connect_socket_up->IsValid());
-
- a_up->swap(connect_socket_up);
- EXPECT_TRUE(error.Success());
- EXPECT_NE(nullptr, a_up->get());
- EXPECT_TRUE((*a_up)->IsValid());
-
- accept_thread.join();
- b_up->reset(static_cast<SocketType*>(accept_socket));
- EXPECT_TRUE(accept_error.Success());
- EXPECT_NE(nullptr, b_up->get());
- EXPECT_TRUE((*b_up)->IsValid());
+protected:
+ static void AcceptThread(Socket *listen_socket,
+ const char *listen_remote_address,
+ bool child_processes_inherit, Socket **accept_socket,
+ Error *error) {
+ *error = listen_socket->Accept(listen_remote_address,
+ child_processes_inherit, *accept_socket);
+ }
+
+ template <typename SocketType>
+ void CreateConnectedSockets(
+ const char *listen_remote_address,
+ const std::function<std::string(const SocketType &)> &get_connect_addr,
+ std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {
+ bool child_processes_inherit = false;
+ Error error;
+ std::unique_ptr<SocketType> listen_socket_up(
+ new SocketType(child_processes_inherit, error));
+ EXPECT_FALSE(error.Fail());
+ error = listen_socket_up->Listen(listen_remote_address, 5);
+ EXPECT_FALSE(error.Fail());
+ EXPECT_TRUE(listen_socket_up->IsValid());
+
+ Error accept_error;
+ Socket *accept_socket;
+ std::thread accept_thread(AcceptThread, listen_socket_up.get(),
+ listen_remote_address, child_processes_inherit,
+ &accept_socket, &accept_error);
+
+ std::string connect_remote_address = get_connect_addr(*listen_socket_up);
+ std::unique_ptr<SocketType> connect_socket_up(
+ new SocketType(child_processes_inherit, error));
+ EXPECT_FALSE(error.Fail());
+ error = connect_socket_up->Connect(connect_remote_address.c_str());
+ EXPECT_FALSE(error.Fail());
+ EXPECT_TRUE(connect_socket_up->IsValid());
+
+ a_up->swap(connect_socket_up);
+ EXPECT_TRUE(error.Success());
+ EXPECT_NE(nullptr, a_up->get());
+ EXPECT_TRUE((*a_up)->IsValid());
- listen_socket_up.reset();
- }
+ accept_thread.join();
+ b_up->reset(static_cast<SocketType *>(accept_socket));
+ EXPECT_TRUE(accept_error.Success());
+ EXPECT_NE(nullptr, b_up->get());
+ EXPECT_TRUE((*b_up)->IsValid());
+
+ listen_socket_up.reset();
+ }
};
-TEST_F (SocketTest, DecodeHostAndPort)
-{
- std::string host_str;
- std::string port_str;
- int32_t port;
- Error error;
- EXPECT_TRUE (Socket::DecodeHostAndPort ("localhost:1138", host_str, port_str, port, &error));
- EXPECT_STREQ ("localhost", host_str.c_str ());
- EXPECT_STREQ ("1138", port_str.c_str ());
- EXPECT_EQ (1138, port);
- EXPECT_TRUE (error.Success ());
-
- EXPECT_FALSE (Socket::DecodeHostAndPort ("google.com:65536", host_str, port_str, port, &error));
- EXPECT_TRUE (error.Fail ());
- EXPECT_STREQ ("invalid host:port specification: 'google.com:65536'", error.AsCString ());
-
- EXPECT_FALSE (Socket::DecodeHostAndPort ("google.com:-1138", host_str, port_str, port, &error));
- EXPECT_TRUE (error.Fail ());
- EXPECT_STREQ ("invalid host:port specification: 'google.com:-1138'", error.AsCString ());
-
- EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str, port, &error));
- EXPECT_TRUE(error.Fail());
- EXPECT_STREQ("invalid host:port specification: 'google.com:65536'", error.AsCString());
-
- EXPECT_TRUE (Socket::DecodeHostAndPort ("12345", host_str, port_str, port, &error));
- EXPECT_STREQ ("", host_str.c_str ());
- EXPECT_STREQ ("12345", port_str.c_str ());
- EXPECT_EQ (12345, port);
- EXPECT_TRUE (error.Success ());
-
- EXPECT_TRUE (Socket::DecodeHostAndPort ("*:0", host_str, port_str, port, &error));
- EXPECT_STREQ ("*", host_str.c_str ());
- EXPECT_STREQ ("0", port_str.c_str ());
- EXPECT_EQ (0, port);
- EXPECT_TRUE (error.Success ());
-
- EXPECT_TRUE(Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
- EXPECT_STREQ("*", host_str.c_str());
- EXPECT_STREQ("65535", port_str.c_str());
- EXPECT_EQ(65535, port);
- EXPECT_TRUE(error.Success());
+TEST_F(SocketTest, DecodeHostAndPort) {
+ std::string host_str;
+ std::string port_str;
+ int32_t port;
+ Error error;
+ EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
+ port, &error));
+ EXPECT_STREQ("localhost", host_str.c_str());
+ EXPECT_STREQ("1138", port_str.c_str());
+ EXPECT_EQ(1138, port);
+ EXPECT_TRUE(error.Success());
+
+ EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
+ port, &error));
+ EXPECT_TRUE(error.Fail());
+ EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
+ error.AsCString());
+
+ EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
+ port, &error));
+ EXPECT_TRUE(error.Fail());
+ EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
+ error.AsCString());
+
+ EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
+ port, &error));
+ EXPECT_TRUE(error.Fail());
+ EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
+ error.AsCString());
+
+ EXPECT_TRUE(
+ Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
+ EXPECT_STREQ("", host_str.c_str());
+ EXPECT_STREQ("12345", port_str.c_str());
+ EXPECT_EQ(12345, port);
+ EXPECT_TRUE(error.Success());
+
+ EXPECT_TRUE(
+ Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
+ EXPECT_STREQ("*", host_str.c_str());
+ EXPECT_STREQ("0", port_str.c_str());
+ EXPECT_EQ(0, port);
+ EXPECT_TRUE(error.Success());
+
+ EXPECT_TRUE(
+ Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
+ EXPECT_STREQ("*", host_str.c_str());
+ EXPECT_STREQ("65535", port_str.c_str());
+ EXPECT_EQ(65535, port);
+ EXPECT_TRUE(error.Success());
}
#ifndef LLDB_DISABLE_POSIX
-TEST_F (SocketTest, DomainListenConnectAccept)
-{
- char* file_name_str = tempnam(nullptr, nullptr);
- EXPECT_NE (nullptr, file_name_str);
- const std::string file_name(file_name_str);
- free(file_name_str);
-
- std::unique_ptr<DomainSocket> socket_a_up;
- std::unique_ptr<DomainSocket> socket_b_up;
- CreateConnectedSockets<DomainSocket>(file_name.c_str(),
- [=](const DomainSocket &)
- {
- return file_name;
- },
- &socket_a_up, &socket_b_up);
+TEST_F(SocketTest, DomainListenConnectAccept) {
+ char *file_name_str = tempnam(nullptr, nullptr);
+ EXPECT_NE(nullptr, file_name_str);
+ const std::string file_name(file_name_str);
+ free(file_name_str);
+
+ std::unique_ptr<DomainSocket> socket_a_up;
+ std::unique_ptr<DomainSocket> socket_b_up;
+ CreateConnectedSockets<DomainSocket>(
+ file_name.c_str(), [=](const DomainSocket &) { return file_name; },
+ &socket_a_up, &socket_b_up);
}
#endif
-TEST_F (SocketTest, TCPListen0ConnectAccept)
-{
- std::unique_ptr<TCPSocket> socket_a_up;
- std::unique_ptr<TCPSocket> socket_b_up;
- CreateConnectedSockets<TCPSocket>("127.0.0.1:0",
- [=](const TCPSocket &s)
- {
- char connect_remote_address[64];
- snprintf(connect_remote_address, sizeof(connect_remote_address), "localhost:%u", s.GetLocalPortNumber());
- return std::string(connect_remote_address);
- },
- &socket_a_up, &socket_b_up);
+TEST_F(SocketTest, TCPListen0ConnectAccept) {
+ std::unique_ptr<TCPSocket> socket_a_up;
+ std::unique_ptr<TCPSocket> socket_b_up;
+ CreateConnectedSockets<TCPSocket>(
+ "127.0.0.1:0",
+ [=](const TCPSocket &s) {
+ char connect_remote_address[64];
+ snprintf(connect_remote_address, sizeof(connect_remote_address),
+ "localhost:%u", s.GetLocalPortNumber());
+ return std::string(connect_remote_address);
+ },
+ &socket_a_up, &socket_b_up);
}
-TEST_F (SocketTest, TCPGetAddress)
-{
- std::unique_ptr<TCPSocket> socket_a_up;
- std::unique_ptr<TCPSocket> socket_b_up;
- CreateConnectedSockets<TCPSocket>("127.0.0.1:0",
- [=](const TCPSocket &s)
- {
- char connect_remote_address[64];
- snprintf(connect_remote_address, sizeof(connect_remote_address), "localhost:%u", s.GetLocalPortNumber());
- return std::string(connect_remote_address);
- },
- &socket_a_up,
- &socket_b_up);
-
- EXPECT_EQ (socket_a_up->GetLocalPortNumber (), socket_b_up->GetRemotePortNumber ());
- EXPECT_EQ (socket_b_up->GetLocalPortNumber (), socket_a_up->GetRemotePortNumber ());
- EXPECT_NE (socket_a_up->GetLocalPortNumber (), socket_b_up->GetLocalPortNumber ());
- EXPECT_STREQ ("127.0.0.1", socket_a_up->GetRemoteIPAddress ().c_str ());
- EXPECT_STREQ ("127.0.0.1", socket_b_up->GetRemoteIPAddress ().c_str ());
+TEST_F(SocketTest, TCPGetAddress) {
+ std::unique_ptr<TCPSocket> socket_a_up;
+ std::unique_ptr<TCPSocket> socket_b_up;
+ CreateConnectedSockets<TCPSocket>(
+ "127.0.0.1:0",
+ [=](const TCPSocket &s) {
+ char connect_remote_address[64];
+ snprintf(connect_remote_address, sizeof(connect_remote_address),
+ "localhost:%u", s.GetLocalPortNumber());
+ return std::string(connect_remote_address);
+ },
+ &socket_a_up, &socket_b_up);
+
+ EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
+ socket_b_up->GetRemotePortNumber());
+ EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
+ socket_a_up->GetRemotePortNumber());
+ EXPECT_NE(socket_a_up->GetLocalPortNumber(),
+ socket_b_up->GetLocalPortNumber());
+ EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
+ EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}
-TEST_F (SocketTest, UDPConnect)
-{
- Socket* socket_a;
- Socket* socket_b;
-
- bool child_processes_inherit = false;
- auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit, socket_a, socket_b);
-
- std::unique_ptr<Socket> a_up(socket_a);
- std::unique_ptr<Socket> b_up(socket_b);
-
- EXPECT_TRUE(error.Success ());
- EXPECT_TRUE(a_up->IsValid());
- EXPECT_TRUE(b_up->IsValid());
+TEST_F(SocketTest, UDPConnect) {
+ Socket *socket_a;
+ Socket *socket_b;
+
+ bool child_processes_inherit = false;
+ auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
+ socket_a, socket_b);
+
+ std::unique_ptr<Socket> a_up(socket_a);
+ std::unique_ptr<Socket> b_up(socket_b);
+
+ EXPECT_TRUE(error.Success());
+ EXPECT_TRUE(a_up->IsValid());
+ EXPECT_TRUE(b_up->IsValid());
}
Modified: lldb/trunk/unittests/Host/SymbolsTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Host/SymbolsTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Host/SymbolsTest.cpp (original)
+++ lldb/trunk/unittests/Host/SymbolsTest.cpp Tue Sep 6 15:57:50 2016
@@ -7,24 +7,25 @@
//
//===----------------------------------------------------------------------===//
-#include "gtest/gtest.h"
#include "lldb/Host/Symbols.h"
#include "lldb/Core/ModuleSpec.h"
+#include "gtest/gtest.h"
using namespace lldb_private;
-TEST(SymbolsTest, LocateExecutableSymbolFileForUnknownExecutableAndUnknownSymbolFile)
-{
- ModuleSpec module_spec;
- FileSpec symbol_file_spec = Symbols::LocateExecutableSymbolFile(module_spec);
- EXPECT_TRUE(symbol_file_spec.GetFilename().IsEmpty());
+TEST(SymbolsTest,
+ LocateExecutableSymbolFileForUnknownExecutableAndUnknownSymbolFile) {
+ ModuleSpec module_spec;
+ FileSpec symbol_file_spec = Symbols::LocateExecutableSymbolFile(module_spec);
+ EXPECT_TRUE(symbol_file_spec.GetFilename().IsEmpty());
}
-TEST(SymbolsTest, LocateExecutableSymbolFileForUnknownExecutableAndMissingSymbolFile)
-{
- ModuleSpec module_spec;
- // using a GUID here because the symbol file shouldn't actually exist on disk
- module_spec.GetSymbolFileSpec().SetFile("4A524676-B24B-4F4E-968A-551D465EBAF1.so", false);
- FileSpec symbol_file_spec = Symbols::LocateExecutableSymbolFile(module_spec);
- EXPECT_TRUE(symbol_file_spec.GetFilename().IsEmpty());
+TEST(SymbolsTest,
+ LocateExecutableSymbolFileForUnknownExecutableAndMissingSymbolFile) {
+ ModuleSpec module_spec;
+ // using a GUID here because the symbol file shouldn't actually exist on disk
+ module_spec.GetSymbolFileSpec().SetFile(
+ "4A524676-B24B-4F4E-968A-551D465EBAF1.so", false);
+ FileSpec symbol_file_spec = Symbols::LocateExecutableSymbolFile(module_spec);
+ EXPECT_TRUE(symbol_file_spec.GetFilename().IsEmpty());
}
Modified: lldb/trunk/unittests/Interpreter/TestArgs.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Interpreter/TestArgs.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Interpreter/TestArgs.cpp (original)
+++ lldb/trunk/unittests/Interpreter/TestArgs.cpp Tue Sep 6 15:57:50 2016
@@ -13,58 +13,52 @@
using namespace lldb_private;
-TEST(ArgsTest, TestSingleArg)
-{
- Args args;
- args.SetCommandString("arg");
- EXPECT_EQ(1u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg");
-}
-
-TEST(ArgsTest, TestSingleQuotedArgWithSpace)
-{
- Args args;
- args.SetCommandString("\"arg with space\"");
- EXPECT_EQ(1u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg with space");
-}
-
-TEST(ArgsTest, TestSingleArgWithQuotedSpace)
-{
- Args args;
- args.SetCommandString("arg\\ with\\ space");
- EXPECT_EQ(1u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg with space");
-}
-
-TEST(ArgsTest, TestMultipleArgs)
-{
- Args args;
- args.SetCommandString("this has multiple args");
- EXPECT_EQ(4u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "this");
- EXPECT_STREQ(args.GetArgumentAtIndex(1), "has");
- EXPECT_STREQ(args.GetArgumentAtIndex(2), "multiple");
- EXPECT_STREQ(args.GetArgumentAtIndex(3), "args");
-}
-
-TEST(ArgsTest, TestOverwriteArgs)
-{
- Args args;
- args.SetCommandString("this has multiple args");
- EXPECT_EQ(4u, args.GetArgumentCount());
- args.SetCommandString("arg");
- EXPECT_EQ(1u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg");
-}
-
-TEST(ArgsTest, TestAppendArg)
-{
- Args args;
- args.SetCommandString("first_arg");
- EXPECT_EQ(1u, args.GetArgumentCount());
- args.AppendArgument("second_arg");
- EXPECT_EQ(2u, args.GetArgumentCount());
- EXPECT_STREQ(args.GetArgumentAtIndex(0), "first_arg");
- EXPECT_STREQ(args.GetArgumentAtIndex(1), "second_arg");
+TEST(ArgsTest, TestSingleArg) {
+ Args args;
+ args.SetCommandString("arg");
+ EXPECT_EQ(1u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg");
+}
+
+TEST(ArgsTest, TestSingleQuotedArgWithSpace) {
+ Args args;
+ args.SetCommandString("\"arg with space\"");
+ EXPECT_EQ(1u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg with space");
+}
+
+TEST(ArgsTest, TestSingleArgWithQuotedSpace) {
+ Args args;
+ args.SetCommandString("arg\\ with\\ space");
+ EXPECT_EQ(1u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg with space");
+}
+
+TEST(ArgsTest, TestMultipleArgs) {
+ Args args;
+ args.SetCommandString("this has multiple args");
+ EXPECT_EQ(4u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "this");
+ EXPECT_STREQ(args.GetArgumentAtIndex(1), "has");
+ EXPECT_STREQ(args.GetArgumentAtIndex(2), "multiple");
+ EXPECT_STREQ(args.GetArgumentAtIndex(3), "args");
+}
+
+TEST(ArgsTest, TestOverwriteArgs) {
+ Args args;
+ args.SetCommandString("this has multiple args");
+ EXPECT_EQ(4u, args.GetArgumentCount());
+ args.SetCommandString("arg");
+ EXPECT_EQ(1u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "arg");
+}
+
+TEST(ArgsTest, TestAppendArg) {
+ Args args;
+ args.SetCommandString("first_arg");
+ EXPECT_EQ(1u, args.GetArgumentCount());
+ args.AppendArgument("second_arg");
+ EXPECT_EQ(2u, args.GetArgumentCount());
+ EXPECT_STREQ(args.GetArgumentAtIndex(0), "first_arg");
+ EXPECT_STREQ(args.GetArgumentAtIndex(1), "second_arg");
}
Modified: lldb/trunk/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp (original)
+++ lldb/trunk/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp Tue Sep 6 15:57:50 2016
@@ -13,29 +13,28 @@
using namespace lldb_private;
-TEST(CPlusPlusLanguage, MethodName)
-{
- struct TestCase {
- std::string input;
- std::string context, basename, arguments, qualifiers, scope_qualified_name;
- };
+TEST(CPlusPlusLanguage, MethodName) {
+ struct TestCase {
+ std::string input;
+ std::string context, basename, arguments, qualifiers, scope_qualified_name;
+ };
- TestCase test_cases[] = {{"foo::bar(baz)", "foo", "bar", "(baz)", "", "foo::bar"},
- {"std::basic_ostream<char, std::char_traits<char> >& "
- "std::operator<<<std::char_traits<char> >"
- "(std::basic_ostream<char, std::char_traits<char> >&, char const*)",
- "std", "operator<<<std::char_traits<char> >",
- "(std::basic_ostream<char, std::char_traits<char> >&, char const*)", "",
- "std::operator<<<std::char_traits<char> >"}};
+ TestCase test_cases[] = {
+ {"foo::bar(baz)", "foo", "bar", "(baz)", "", "foo::bar"},
+ {"std::basic_ostream<char, std::char_traits<char> >& "
+ "std::operator<<<std::char_traits<char> >"
+ "(std::basic_ostream<char, std::char_traits<char> >&, char const*)",
+ "std", "operator<<<std::char_traits<char> >",
+ "(std::basic_ostream<char, std::char_traits<char> >&, char const*)", "",
+ "std::operator<<<std::char_traits<char> >"}};
- for (const auto &test: test_cases)
- {
- CPlusPlusLanguage::MethodName method(ConstString(test.input));
- EXPECT_TRUE(method.IsValid());
- EXPECT_EQ(test.context, method.GetContext());
- EXPECT_EQ(test.basename, method.GetBasename());
- EXPECT_EQ(test.arguments, method.GetArguments());
- EXPECT_EQ(test.qualifiers, method.GetQualifiers());
- EXPECT_EQ(test.scope_qualified_name, method.GetScopeQualifiedName());
- }
+ for (const auto &test : test_cases) {
+ CPlusPlusLanguage::MethodName method(ConstString(test.input));
+ EXPECT_TRUE(method.IsValid());
+ EXPECT_EQ(test.context, method.GetContext());
+ EXPECT_EQ(test.basename, method.GetBasename());
+ EXPECT_EQ(test.arguments, method.GetArguments());
+ EXPECT_EQ(test.qualifiers, method.GetQualifiers());
+ EXPECT_EQ(test.scope_qualified_name, method.GetScopeQualifiedName());
+ }
}
Modified: lldb/trunk/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp (original)
+++ lldb/trunk/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp Tue Sep 6 15:57:50 2016
@@ -8,7 +8,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -28,338 +29,320 @@ using namespace lldb_private;
using namespace lldb;
typedef GDBRemoteCommunication::PacketResult PacketResult;
-namespace
-{
-
-struct MockDelegate : public GDBRemoteClientBase::ContinueDelegate
-{
- std::string output;
- std::string misc_data;
- unsigned stop_reply_called = 0;
-
- void
- HandleAsyncStdout(llvm::StringRef out)
- {
- output += out;
- }
- void
- HandleAsyncMisc(llvm::StringRef data)
- {
- misc_data += data;
- }
- void
- HandleStopReply()
- {
- ++stop_reply_called;
- }
-
- bool
- HandleAsyncStructuredData(const StructuredData::ObjectSP
- &object_sp)
- {
- // TODO work in a test here after I fix the gtest breakage.
- return true;
- }
+namespace {
+struct MockDelegate : public GDBRemoteClientBase::ContinueDelegate {
+ std::string output;
+ std::string misc_data;
+ unsigned stop_reply_called = 0;
+
+ void HandleAsyncStdout(llvm::StringRef out) { output += out; }
+ void HandleAsyncMisc(llvm::StringRef data) { misc_data += data; }
+ void HandleStopReply() { ++stop_reply_called; }
+
+ bool HandleAsyncStructuredData(const StructuredData::ObjectSP &object_sp) {
+ // TODO work in a test here after I fix the gtest breakage.
+ return true;
+ }
};
-struct TestClient : public GDBRemoteClientBase
-{
- TestClient() : GDBRemoteClientBase("test.client", "test.client.listener") { m_send_acks = false; }
+struct TestClient : public GDBRemoteClientBase {
+ TestClient() : GDBRemoteClientBase("test.client", "test.client.listener") {
+ m_send_acks = false;
+ }
};
-struct ContinueFixture
-{
- MockDelegate delegate;
- TestClient client;
- MockServer server;
- ListenerSP listener_sp;
-
- ContinueFixture();
-
- StateType
- SendCPacket(StringExtractorGDBRemote &response)
- {
- return client.SendContinuePacketAndWaitForResponse(delegate, LinuxSignals(), "c", response);
- }
-
- void
- WaitForRunEvent()
- {
- EventSP event_sp;
- listener_sp->WaitForEventForBroadcasterWithType(std::chrono::microseconds(0), &client,
- TestClient::eBroadcastBitRunPacketSent, event_sp);
- }
+struct ContinueFixture {
+ MockDelegate delegate;
+ TestClient client;
+ MockServer server;
+ ListenerSP listener_sp;
+
+ ContinueFixture();
+
+ StateType SendCPacket(StringExtractorGDBRemote &response) {
+ return client.SendContinuePacketAndWaitForResponse(delegate, LinuxSignals(),
+ "c", response);
+ }
+
+ void WaitForRunEvent() {
+ EventSP event_sp;
+ listener_sp->WaitForEventForBroadcasterWithType(
+ std::chrono::microseconds(0), &client,
+ TestClient::eBroadcastBitRunPacketSent, event_sp);
+ }
};
-ContinueFixture::ContinueFixture() : listener_sp(Listener::MakeListener("listener"))
-{
- Connect(client, server);
- listener_sp->StartListeningForEvents(&client, TestClient::eBroadcastBitRunPacketSent);
+ContinueFixture::ContinueFixture()
+ : listener_sp(Listener::MakeListener("listener")) {
+ Connect(client, server);
+ listener_sp->StartListeningForEvents(&client,
+ TestClient::eBroadcastBitRunPacketSent);
}
} // end anonymous namespace
-class GDBRemoteClientBaseTest : public GDBRemoteTest
-{
-};
+class GDBRemoteClientBaseTest : public GDBRemoteTest {};
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndWait)
-{
- StringExtractorGDBRemote response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Continue. The inferior will stop with a signal.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
- ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
- ASSERT_EQ("T01", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
-
- // Continue. The inferior will exit.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("W01"));
- ASSERT_EQ(eStateExited, fix.SendCPacket(response));
- ASSERT_EQ("W01", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
-
- // Continue. The inferior will get killed.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("X01"));
- ASSERT_EQ(eStateExited, fix.SendCPacket(response));
- ASSERT_EQ("X01", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndWait) {
+ StringExtractorGDBRemote response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Continue. The inferior will stop with a signal.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
+ ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
+ ASSERT_EQ("T01", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+
+ // Continue. The inferior will exit.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("W01"));
+ ASSERT_EQ(eStateExited, fix.SendCPacket(response));
+ ASSERT_EQ("W01", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+
+ // Continue. The inferior will get killed.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("X01"));
+ ASSERT_EQ(eStateExited, fix.SendCPacket(response));
+ ASSERT_EQ("X01", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndAsyncSignal)
-{
- StringExtractorGDBRemote continue_response, response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // SendAsyncSignal should do nothing when we are not running.
- ASSERT_FALSE(fix.client.SendAsyncSignal(0x47));
-
- // Continue. After the run packet is sent, send an async signal.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- std::future<bool> async_result = std::async(std::launch::async, [&] { return fix.client.SendAsyncSignal(0x47); });
-
- // First we'll get interrupted.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
-
- // Then we get the signal packet.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("C47", response.GetStringRef());
- ASSERT_TRUE(async_result.get());
-
- // And we report back a signal stop.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T47"));
- ASSERT_EQ(eStateStopped, continue_state.get());
- ASSERT_EQ("T47", continue_response.GetStringRef());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndAsyncSignal) {
+ StringExtractorGDBRemote continue_response, response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // SendAsyncSignal should do nothing when we are not running.
+ ASSERT_FALSE(fix.client.SendAsyncSignal(0x47));
+
+ // Continue. After the run packet is sent, send an async signal.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ std::future<bool> async_result = std::async(
+ std::launch::async, [&] { return fix.client.SendAsyncSignal(0x47); });
+
+ // First we'll get interrupted.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
+
+ // Then we get the signal packet.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("C47", response.GetStringRef());
+ ASSERT_TRUE(async_result.get());
+
+ // And we report back a signal stop.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T47"));
+ ASSERT_EQ(eStateStopped, continue_state.get());
+ ASSERT_EQ("T47", continue_response.GetStringRef());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndAsyncPacket)
-{
- StringExtractorGDBRemote continue_response, async_response, response;
- const bool send_async = true;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Continue. After the run packet is sent, send an async packet.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- // Sending without async enabled should fail.
- ASSERT_EQ(PacketResult::ErrorSendFailed, fix.client.SendPacketAndWaitForResponse("qTest1", response, !send_async));
-
- std::future<PacketResult> async_result = std::async(std::launch::async, [&] {
- return fix.client.SendPacketAndWaitForResponse("qTest2", async_response, send_async);
- });
-
- // First we'll get interrupted.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
-
- // Then we get the async packet.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("qTest2", response.GetStringRef());
-
- // Send the response and receive it.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("QTest2"));
- ASSERT_EQ(PacketResult::Success, async_result.get());
- ASSERT_EQ("QTest2", async_response.GetStringRef());
-
- // And we get resumed again.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
- ASSERT_EQ(eStateStopped, continue_state.get());
- ASSERT_EQ("T01", continue_response.GetStringRef());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndAsyncPacket) {
+ StringExtractorGDBRemote continue_response, async_response, response;
+ const bool send_async = true;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Continue. After the run packet is sent, send an async packet.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ // Sending without async enabled should fail.
+ ASSERT_EQ(
+ PacketResult::ErrorSendFailed,
+ fix.client.SendPacketAndWaitForResponse("qTest1", response, !send_async));
+
+ std::future<PacketResult> async_result = std::async(std::launch::async, [&] {
+ return fix.client.SendPacketAndWaitForResponse("qTest2", async_response,
+ send_async);
+ });
+
+ // First we'll get interrupted.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
+
+ // Then we get the async packet.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("qTest2", response.GetStringRef());
+
+ // Send the response and receive it.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("QTest2"));
+ ASSERT_EQ(PacketResult::Success, async_result.get());
+ ASSERT_EQ("QTest2", async_response.GetStringRef());
+
+ // And we get resumed again.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
+ ASSERT_EQ(eStateStopped, continue_state.get());
+ ASSERT_EQ("T01", continue_response.GetStringRef());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndInterrupt)
-{
- StringExtractorGDBRemote continue_response, response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Interrupt should do nothing when we're not running.
- ASSERT_FALSE(fix.client.Interrupt());
-
- // Continue. After the run packet is sent, send an interrupt.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- std::future<bool> async_result = std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
-
- // We get interrupted.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
-
- // And that's it.
- ASSERT_EQ(eStateStopped, continue_state.get());
- ASSERT_EQ("T13", continue_response.GetStringRef());
- ASSERT_TRUE(async_result.get());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndInterrupt) {
+ StringExtractorGDBRemote continue_response, response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Interrupt should do nothing when we're not running.
+ ASSERT_FALSE(fix.client.Interrupt());
+
+ // Continue. After the run packet is sent, send an interrupt.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ std::future<bool> async_result =
+ std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
+
+ // We get interrupted.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
+
+ // And that's it.
+ ASSERT_EQ(eStateStopped, continue_state.get());
+ ASSERT_EQ("T13", continue_response.GetStringRef());
+ ASSERT_TRUE(async_result.get());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndLateInterrupt)
-{
- StringExtractorGDBRemote continue_response, response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Continue. After the run packet is sent, send an interrupt.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- std::future<bool> async_result = std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
-
- // However, the target stops due to a different reason than the original interrupt.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
- ASSERT_EQ(eStateStopped, continue_state.get());
- ASSERT_EQ("T01", continue_response.GetStringRef());
- ASSERT_TRUE(async_result.get());
-
- // The subsequent continue packet should work normally.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
- ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
- ASSERT_EQ("T01", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndLateInterrupt) {
+ StringExtractorGDBRemote continue_response, response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Continue. After the run packet is sent, send an interrupt.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ std::future<bool> async_result =
+ std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
+
+ // However, the target stops due to a different reason than the original
+ // interrupt.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
+ ASSERT_EQ(eStateStopped, continue_state.get());
+ ASSERT_EQ("T01", continue_response.GetStringRef());
+ ASSERT_TRUE(async_result.get());
+
+ // The subsequent continue packet should work normally.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
+ ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
+ ASSERT_EQ("T01", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueAndInterrupt2PacketBug)
-{
- StringExtractorGDBRemote continue_response, async_response, response;
- const bool send_async = true;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Interrupt should do nothing when we're not running.
- ASSERT_FALSE(fix.client.Interrupt());
-
- // Continue. After the run packet is sent, send an async signal.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- std::future<bool> interrupt_result = std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
-
- // We get interrupted. We'll send two packets to simulate a buggy stub.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
-
- // We should stop.
- ASSERT_EQ(eStateStopped, continue_state.get());
- ASSERT_EQ("T13", continue_response.GetStringRef());
- ASSERT_TRUE(interrupt_result.get());
-
- // Packet stream should remain synchronized.
- std::future<PacketResult> send_result = std::async(std::launch::async, [&] {
- return fix.client.SendPacketAndWaitForResponse("qTest", async_response, !send_async);
- });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("qTest", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("QTest"));
- ASSERT_EQ(PacketResult::Success, send_result.get());
- ASSERT_EQ("QTest", async_response.GetStringRef());
+TEST_F(GDBRemoteClientBaseTest, SendContinueAndInterrupt2PacketBug) {
+ StringExtractorGDBRemote continue_response, async_response, response;
+ const bool send_async = true;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Interrupt should do nothing when we're not running.
+ ASSERT_FALSE(fix.client.Interrupt());
+
+ // Continue. After the run packet is sent, send an async signal.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ std::future<bool> interrupt_result =
+ std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
+
+ // We get interrupted. We'll send two packets to simulate a buggy stub.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T13"));
+
+ // We should stop.
+ ASSERT_EQ(eStateStopped, continue_state.get());
+ ASSERT_EQ("T13", continue_response.GetStringRef());
+ ASSERT_TRUE(interrupt_result.get());
+
+ // Packet stream should remain synchronized.
+ std::future<PacketResult> send_result = std::async(std::launch::async, [&] {
+ return fix.client.SendPacketAndWaitForResponse("qTest", async_response,
+ !send_async);
+ });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("qTest", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("QTest"));
+ ASSERT_EQ(PacketResult::Success, send_result.get());
+ ASSERT_EQ("QTest", async_response.GetStringRef());
}
-TEST_F(GDBRemoteClientBaseTest, SendContinueDelegateInterface)
-{
- StringExtractorGDBRemote response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Continue. We'll have the server send a bunch of async packets before it stops.
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("O4142"));
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("Apro"));
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("O4344"));
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("Afile"));
- ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
- ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
- ASSERT_EQ("T01", response.GetStringRef());
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
-
- EXPECT_EQ("ABCD", fix.delegate.output);
- EXPECT_EQ("profile", fix.delegate.misc_data);
- EXPECT_EQ(1u, fix.delegate.stop_reply_called);
+TEST_F(GDBRemoteClientBaseTest, SendContinueDelegateInterface) {
+ StringExtractorGDBRemote response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Continue. We'll have the server send a bunch of async packets before it
+ // stops.
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("O4142"));
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("Apro"));
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("O4344"));
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("Afile"));
+ ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01"));
+ ASSERT_EQ(eStateStopped, fix.SendCPacket(response));
+ ASSERT_EQ("T01", response.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+
+ EXPECT_EQ("ABCD", fix.delegate.output);
+ EXPECT_EQ("profile", fix.delegate.misc_data);
+ EXPECT_EQ(1u, fix.delegate.stop_reply_called);
}
-TEST_F(GDBRemoteClientBaseTest, InterruptNoResponse)
-{
- StringExtractorGDBRemote continue_response, response;
- ContinueFixture fix;
- if (HasFailure())
- return;
-
- // Continue. After the run packet is sent, send an interrupt.
- std::future<StateType> continue_state =
- std::async(std::launch::async, [&] { return fix.SendCPacket(continue_response); });
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("c", response.GetStringRef());
- fix.WaitForRunEvent();
-
- std::future<bool> async_result = std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
-
- // We get interrupted, but we don't send a stop packet.
- ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
- ASSERT_EQ("\x03", response.GetStringRef());
-
- // The functions should still terminate (after a timeout).
- ASSERT_TRUE(async_result.get());
- ASSERT_EQ(eStateInvalid, continue_state.get());
+TEST_F(GDBRemoteClientBaseTest, InterruptNoResponse) {
+ StringExtractorGDBRemote continue_response, response;
+ ContinueFixture fix;
+ if (HasFailure())
+ return;
+
+ // Continue. After the run packet is sent, send an interrupt.
+ std::future<StateType> continue_state = std::async(
+ std::launch::async, [&] { return fix.SendCPacket(continue_response); });
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("c", response.GetStringRef());
+ fix.WaitForRunEvent();
+
+ std::future<bool> async_result =
+ std::async(std::launch::async, [&] { return fix.client.Interrupt(); });
+
+ // We get interrupted, but we don't send a stop packet.
+ ASSERT_EQ(PacketResult::Success, fix.server.GetPacket(response));
+ ASSERT_EQ("\x03", response.GetStringRef());
+
+ // The functions should still terminate (after a timeout).
+ ASSERT_TRUE(async_result.get());
+ ASSERT_EQ(eStateInvalid, continue_state.get());
}
Modified: lldb/trunk/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp (original)
+++ lldb/trunk/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp Tue Sep 6 15:57:50 2016
@@ -8,7 +8,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -26,159 +27,162 @@ using namespace lldb_private::process_gd
using namespace lldb_private;
using namespace lldb;
-namespace
-{
+namespace {
typedef GDBRemoteCommunication::PacketResult PacketResult;
-struct TestClient : public GDBRemoteCommunicationClient
-{
- TestClient() { m_send_acks = false; }
+struct TestClient : public GDBRemoteCommunicationClient {
+ TestClient() { m_send_acks = false; }
};
-void
-Handle_QThreadSuffixSupported(MockServer &server, bool supported)
-{
- StringExtractorGDBRemote request;
- ASSERT_EQ(PacketResult::Success, server.GetPacket(request));
- ASSERT_EQ("QThreadSuffixSupported", request.GetStringRef());
- if (supported)
- ASSERT_EQ(PacketResult::Success, server.SendOKResponse());
- else
- ASSERT_EQ(PacketResult::Success, server.SendUnimplementedResponse(nullptr));
-}
-
-void
-HandlePacket(MockServer &server, llvm::StringRef expected, llvm::StringRef response)
-{
- StringExtractorGDBRemote request;
- ASSERT_EQ(PacketResult::Success, server.GetPacket(request));
- ASSERT_EQ(expected, request.GetStringRef());
- ASSERT_EQ(PacketResult::Success, server.SendPacket(response));
+void Handle_QThreadSuffixSupported(MockServer &server, bool supported) {
+ StringExtractorGDBRemote request;
+ ASSERT_EQ(PacketResult::Success, server.GetPacket(request));
+ ASSERT_EQ("QThreadSuffixSupported", request.GetStringRef());
+ if (supported)
+ ASSERT_EQ(PacketResult::Success, server.SendOKResponse());
+ else
+ ASSERT_EQ(PacketResult::Success, server.SendUnimplementedResponse(nullptr));
+}
+
+void HandlePacket(MockServer &server, llvm::StringRef expected,
+ llvm::StringRef response) {
+ StringExtractorGDBRemote request;
+ ASSERT_EQ(PacketResult::Success, server.GetPacket(request));
+ ASSERT_EQ(expected, request.GetStringRef());
+ ASSERT_EQ(PacketResult::Success, server.SendPacket(response));
}
-uint8_t all_registers[] = {'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'};
+uint8_t all_registers[] = {'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
+ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'};
std::string all_registers_hex = "404142434445464748494a4b4c4d4e4f";
uint8_t one_register[] = {'A', 'B', 'C', 'D'};
std::string one_register_hex = "41424344";
} // end anonymous namespace
-class GDBRemoteCommunicationClientTest : public GDBRemoteTest
-{
-};
+class GDBRemoteCommunicationClientTest : public GDBRemoteTest {};
-TEST_F(GDBRemoteCommunicationClientTest, WriteRegister)
-{
- TestClient client;
- MockServer server;
- Connect(client, server);
- if (HasFailure())
- return;
-
- const lldb::tid_t tid = 0x47;
- const uint32_t reg_num = 4;
- std::future<bool> write_result =
- std::async(std::launch::async, [&] { return client.WriteRegister(tid, reg_num, one_register); });
-
- Handle_QThreadSuffixSupported(server, true);
-
- HandlePacket(server, "P4=" + one_register_hex + ";thread:0047;", "OK");
- ASSERT_TRUE(write_result.get());
-
- write_result = std::async(std::launch::async, [&] { return client.WriteAllRegisters(tid, all_registers); });
-
- HandlePacket(server, "G" + all_registers_hex + ";thread:0047;", "OK");
- ASSERT_TRUE(write_result.get());
-}
-
-TEST_F(GDBRemoteCommunicationClientTest, WriteRegisterNoSuffix)
-{
- TestClient client;
- MockServer server;
- Connect(client, server);
- if (HasFailure())
- return;
-
- const lldb::tid_t tid = 0x47;
- const uint32_t reg_num = 4;
- std::future<bool> write_result =
- std::async(std::launch::async, [&] { return client.WriteRegister(tid, reg_num, one_register); });
-
- Handle_QThreadSuffixSupported(server, false);
- HandlePacket(server, "Hg47", "OK");
- HandlePacket(server, "P4=" + one_register_hex, "OK");
- ASSERT_TRUE(write_result.get());
-
- write_result = std::async(std::launch::async, [&] { return client.WriteAllRegisters(tid, all_registers); });
-
- HandlePacket(server, "G" + all_registers_hex, "OK");
- ASSERT_TRUE(write_result.get());
-}
-
-TEST_F(GDBRemoteCommunicationClientTest, ReadRegister)
-{
- TestClient client;
- MockServer server;
- Connect(client, server);
- if (HasFailure())
- return;
-
- const lldb::tid_t tid = 0x47;
- const uint32_t reg_num = 4;
- std::future<bool> async_result = std::async(std::launch::async, [&] { return client.GetpPacketSupported(tid); });
- Handle_QThreadSuffixSupported(server, true);
- HandlePacket(server, "p0;thread:0047;", one_register_hex);
- ASSERT_TRUE(async_result.get());
-
- std::future<DataBufferSP> read_result =
- std::async(std::launch::async, [&] { return client.ReadRegister(tid, reg_num); });
- HandlePacket(server, "p4;thread:0047;", "41424344");
- auto buffer_sp = read_result.get();
- ASSERT_TRUE(bool(buffer_sp));
- ASSERT_EQ(0, memcmp(buffer_sp->GetBytes(), one_register, sizeof one_register));
-
- read_result = std::async(std::launch::async, [&] { return client.ReadAllRegisters(tid); });
- HandlePacket(server, "g;thread:0047;", all_registers_hex);
- buffer_sp = read_result.get();
- ASSERT_TRUE(bool(buffer_sp));
- ASSERT_EQ(0, memcmp(buffer_sp->GetBytes(), all_registers, sizeof all_registers));
-}
-
-TEST_F(GDBRemoteCommunicationClientTest, SaveRestoreRegistersNoSuffix)
-{
- TestClient client;
- MockServer server;
- Connect(client, server);
- if (HasFailure())
- return;
-
- const lldb::tid_t tid = 0x47;
- uint32_t save_id;
- std::future<bool> async_result =
- std::async(std::launch::async, [&] { return client.SaveRegisterState(tid, save_id); });
- Handle_QThreadSuffixSupported(server, false);
- HandlePacket(server, "Hg47", "OK");
- HandlePacket(server, "QSaveRegisterState", "1");
- ASSERT_TRUE(async_result.get());
- EXPECT_EQ(1u, save_id);
-
- async_result = std::async(std::launch::async, [&] { return client.RestoreRegisterState(tid, save_id); });
- HandlePacket(server, "QRestoreRegisterState:1", "OK");
- ASSERT_TRUE(async_result.get());
-}
-
-TEST_F(GDBRemoteCommunicationClientTest, SyncThreadState)
-{
- TestClient client;
- MockServer server;
- Connect(client, server);
- if (HasFailure())
- return;
-
- const lldb::tid_t tid = 0x47;
- std::future<bool> async_result = std::async(std::launch::async, [&] { return client.SyncThreadState(tid); });
- HandlePacket(server, "qSyncThreadStateSupported", "OK");
- HandlePacket(server, "QSyncThreadState:0047;", "OK");
- ASSERT_TRUE(async_result.get());
+TEST_F(GDBRemoteCommunicationClientTest, WriteRegister) {
+ TestClient client;
+ MockServer server;
+ Connect(client, server);
+ if (HasFailure())
+ return;
+
+ const lldb::tid_t tid = 0x47;
+ const uint32_t reg_num = 4;
+ std::future<bool> write_result = std::async(std::launch::async, [&] {
+ return client.WriteRegister(tid, reg_num, one_register);
+ });
+
+ Handle_QThreadSuffixSupported(server, true);
+
+ HandlePacket(server, "P4=" + one_register_hex + ";thread:0047;", "OK");
+ ASSERT_TRUE(write_result.get());
+
+ write_result = std::async(std::launch::async, [&] {
+ return client.WriteAllRegisters(tid, all_registers);
+ });
+
+ HandlePacket(server, "G" + all_registers_hex + ";thread:0047;", "OK");
+ ASSERT_TRUE(write_result.get());
+}
+
+TEST_F(GDBRemoteCommunicationClientTest, WriteRegisterNoSuffix) {
+ TestClient client;
+ MockServer server;
+ Connect(client, server);
+ if (HasFailure())
+ return;
+
+ const lldb::tid_t tid = 0x47;
+ const uint32_t reg_num = 4;
+ std::future<bool> write_result = std::async(std::launch::async, [&] {
+ return client.WriteRegister(tid, reg_num, one_register);
+ });
+
+ Handle_QThreadSuffixSupported(server, false);
+ HandlePacket(server, "Hg47", "OK");
+ HandlePacket(server, "P4=" + one_register_hex, "OK");
+ ASSERT_TRUE(write_result.get());
+
+ write_result = std::async(std::launch::async, [&] {
+ return client.WriteAllRegisters(tid, all_registers);
+ });
+
+ HandlePacket(server, "G" + all_registers_hex, "OK");
+ ASSERT_TRUE(write_result.get());
+}
+
+TEST_F(GDBRemoteCommunicationClientTest, ReadRegister) {
+ TestClient client;
+ MockServer server;
+ Connect(client, server);
+ if (HasFailure())
+ return;
+
+ const lldb::tid_t tid = 0x47;
+ const uint32_t reg_num = 4;
+ std::future<bool> async_result = std::async(
+ std::launch::async, [&] { return client.GetpPacketSupported(tid); });
+ Handle_QThreadSuffixSupported(server, true);
+ HandlePacket(server, "p0;thread:0047;", one_register_hex);
+ ASSERT_TRUE(async_result.get());
+
+ std::future<DataBufferSP> read_result = std::async(
+ std::launch::async, [&] { return client.ReadRegister(tid, reg_num); });
+ HandlePacket(server, "p4;thread:0047;", "41424344");
+ auto buffer_sp = read_result.get();
+ ASSERT_TRUE(bool(buffer_sp));
+ ASSERT_EQ(0,
+ memcmp(buffer_sp->GetBytes(), one_register, sizeof one_register));
+
+ read_result = std::async(std::launch::async,
+ [&] { return client.ReadAllRegisters(tid); });
+ HandlePacket(server, "g;thread:0047;", all_registers_hex);
+ buffer_sp = read_result.get();
+ ASSERT_TRUE(bool(buffer_sp));
+ ASSERT_EQ(0,
+ memcmp(buffer_sp->GetBytes(), all_registers, sizeof all_registers));
+}
+
+TEST_F(GDBRemoteCommunicationClientTest, SaveRestoreRegistersNoSuffix) {
+ TestClient client;
+ MockServer server;
+ Connect(client, server);
+ if (HasFailure())
+ return;
+
+ const lldb::tid_t tid = 0x47;
+ uint32_t save_id;
+ std::future<bool> async_result = std::async(std::launch::async, [&] {
+ return client.SaveRegisterState(tid, save_id);
+ });
+ Handle_QThreadSuffixSupported(server, false);
+ HandlePacket(server, "Hg47", "OK");
+ HandlePacket(server, "QSaveRegisterState", "1");
+ ASSERT_TRUE(async_result.get());
+ EXPECT_EQ(1u, save_id);
+
+ async_result = std::async(std::launch::async, [&] {
+ return client.RestoreRegisterState(tid, save_id);
+ });
+ HandlePacket(server, "QRestoreRegisterState:1", "OK");
+ ASSERT_TRUE(async_result.get());
+}
+
+TEST_F(GDBRemoteCommunicationClientTest, SyncThreadState) {
+ TestClient client;
+ MockServer server;
+ Connect(client, server);
+ if (HasFailure())
+ return;
+
+ const lldb::tid_t tid = 0x47;
+ std::future<bool> async_result = std::async(
+ std::launch::async, [&] { return client.SyncThreadState(tid); });
+ HandlePacket(server, "qSyncThreadStateSupported", "OK");
+ HandlePacket(server, "QSyncThreadState:0047;", "OK");
+ ASSERT_TRUE(async_result.get());
}
Modified: lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp (original)
+++ lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp Tue Sep 6 15:57:50 2016
@@ -8,7 +8,8 @@
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
-// Workaround for MSVC standard library bug, which fails to include <thread> when
+// Workaround for MSVC standard library bug, which fails to include <thread>
+// when
// exceptions are disabled.
#include <eh.h>
#endif
@@ -20,53 +21,48 @@
#include <future>
-namespace lldb_private
-{
-namespace process_gdb_remote
-{
-
-void
-GDBRemoteTest::SetUpTestCase()
-{
+namespace lldb_private {
+namespace process_gdb_remote {
+
+void GDBRemoteTest::SetUpTestCase() {
#if defined(_MSC_VER)
- WSADATA data;
- ::WSAStartup(MAKEWORD(2, 2), &data);
+ WSADATA data;
+ ::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}
-void
-GDBRemoteTest::TearDownTestCase()
-{
+void GDBRemoteTest::TearDownTestCase() {
#if defined(_MSC_VER)
- ::WSACleanup();
+ ::WSACleanup();
#endif
}
-void
-Connect(GDBRemoteCommunication &client, GDBRemoteCommunication &server)
-{
- bool child_processes_inherit = false;
- Error error;
- TCPSocket listen_socket(child_processes_inherit, error);
- ASSERT_FALSE(error.Fail());
- error = listen_socket.Listen("127.0.0.1:0", 5);
- ASSERT_FALSE(error.Fail());
-
- Socket *accept_socket;
- std::future<Error> accept_error = std::async(std::launch::async, [&] {
- return listen_socket.Accept("127.0.0.1:0", child_processes_inherit, accept_socket);
- });
-
- char connect_remote_address[64];
- snprintf(connect_remote_address, sizeof(connect_remote_address), "connect://localhost:%u",
- listen_socket.GetLocalPortNumber());
-
- std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
- ASSERT_EQ(conn_ap->Connect(connect_remote_address, nullptr), lldb::eConnectionStatusSuccess);
-
- client.SetConnection(conn_ap.release());
- ASSERT_TRUE(accept_error.get().Success());
- server.SetConnection(new ConnectionFileDescriptor(accept_socket));
+void Connect(GDBRemoteCommunication &client, GDBRemoteCommunication &server) {
+ bool child_processes_inherit = false;
+ Error error;
+ TCPSocket listen_socket(child_processes_inherit, error);
+ ASSERT_FALSE(error.Fail());
+ error = listen_socket.Listen("127.0.0.1:0", 5);
+ ASSERT_FALSE(error.Fail());
+
+ Socket *accept_socket;
+ std::future<Error> accept_error = std::async(std::launch::async, [&] {
+ return listen_socket.Accept("127.0.0.1:0", child_processes_inherit,
+ accept_socket);
+ });
+
+ char connect_remote_address[64];
+ snprintf(connect_remote_address, sizeof(connect_remote_address),
+ "connect://localhost:%u", listen_socket.GetLocalPortNumber());
+
+ std::unique_ptr<ConnectionFileDescriptor> conn_ap(
+ new ConnectionFileDescriptor());
+ ASSERT_EQ(conn_ap->Connect(connect_remote_address, nullptr),
+ lldb::eConnectionStatusSuccess);
+
+ client.SetConnection(conn_ap.release());
+ ASSERT_TRUE(accept_error.get().Success());
+ server.SetConnection(new ConnectionFileDescriptor(accept_socket));
}
} // namespace process_gdb_remote
Modified: lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.h?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.h (original)
+++ lldb/trunk/unittests/Process/gdb-remote/GDBRemoteTestUtils.h Tue Sep 6 15:57:50 2016
@@ -9,47 +9,40 @@
#ifndef lldb_unittests_Process_gdb_remote_GDBRemoteTestUtils_h
#define lldb_unittests_Process_gdb_remote_GDBRemoteTestUtils_h
-#include "gtest/gtest.h"
#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h"
+#include "gtest/gtest.h"
-namespace lldb_private
-{
-namespace process_gdb_remote
-{
+namespace lldb_private {
+namespace process_gdb_remote {
-class GDBRemoteTest : public testing::Test
-{
+class GDBRemoteTest : public testing::Test {
public:
- static void
- SetUpTestCase();
+ static void SetUpTestCase();
- static void
- TearDownTestCase();
+ static void TearDownTestCase();
};
-void
-Connect(GDBRemoteCommunication &client, GDBRemoteCommunication &server);
+void Connect(GDBRemoteCommunication &client, GDBRemoteCommunication &server);
-struct MockServer : public GDBRemoteCommunicationServer
-{
- MockServer() : GDBRemoteCommunicationServer("mock-server", "mock-server.listener") { m_send_acks = false; }
-
- PacketResult
- SendPacket(llvm::StringRef payload)
- {
- return GDBRemoteCommunicationServer::SendPacketNoLock(payload);
- }
-
- PacketResult
- GetPacket(StringExtractorGDBRemote &response)
- {
- const unsigned timeout_usec = 1000000; // 1s
- const bool sync_on_timeout = false;
- return WaitForPacketWithTimeoutMicroSecondsNoLock(response, timeout_usec, sync_on_timeout);
- }
+struct MockServer : public GDBRemoteCommunicationServer {
+ MockServer()
+ : GDBRemoteCommunicationServer("mock-server", "mock-server.listener") {
+ m_send_acks = false;
+ }
+
+ PacketResult SendPacket(llvm::StringRef payload) {
+ return GDBRemoteCommunicationServer::SendPacketNoLock(payload);
+ }
+
+ PacketResult GetPacket(StringExtractorGDBRemote &response) {
+ const unsigned timeout_usec = 1000000; // 1s
+ const bool sync_on_timeout = false;
+ return WaitForPacketWithTimeoutMicroSecondsNoLock(response, timeout_usec,
+ sync_on_timeout);
+ }
- using GDBRemoteCommunicationServer::SendOKResponse;
- using GDBRemoteCommunicationServer::SendUnimplementedResponse;
+ using GDBRemoteCommunicationServer::SendOKResponse;
+ using GDBRemoteCommunicationServer::SendUnimplementedResponse;
};
} // namespace process_gdb_remote
Modified: lldb/trunk/unittests/Process/minidump/Inputs/linux-x86_64.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/minidump/Inputs/linux-x86_64.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/minidump/Inputs/linux-x86_64.cpp (original)
+++ lldb/trunk/unittests/Process/minidump/Inputs/linux-x86_64.cpp Tue Sep 6 15:57:50 2016
@@ -7,19 +7,22 @@
#include "client/linux/handler/exception_handler.h"
-
-static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor,
-void* context, bool succeeded) {
- printf("Dump path: %s\n", descriptor.path());
- return succeeded;
+static bool dumpCallback(const google_breakpad::MinidumpDescriptor &descriptor,
+ void *context, bool succeeded) {
+ printf("Dump path: %s\n", descriptor.path());
+ return succeeded;
}
-void crash() { volatile int* a = (int*)(NULL); *a = 1; }
+void crash() {
+ volatile int *a = (int *)(NULL);
+ *a = 1;
+}
-int main(int argc, char* argv[]) {
- google_breakpad::MinidumpDescriptor descriptor("/tmp");
- google_breakpad::ExceptionHandler eh(descriptor, NULL, dumpCallback, NULL, true, -1);
- printf("pid: %d\n", getpid());
- crash();
- return 0;
+int main(int argc, char *argv[]) {
+ google_breakpad::MinidumpDescriptor descriptor("/tmp");
+ google_breakpad::ExceptionHandler eh(descriptor, NULL, dumpCallback, NULL,
+ true, -1);
+ printf("pid: %d\n", getpid());
+ crash();
+ return 0;
}
Modified: lldb/trunk/unittests/Process/minidump/MinidumpParserTest.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/Process/minidump/MinidumpParserTest.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/Process/minidump/MinidumpParserTest.cpp (original)
+++ lldb/trunk/unittests/Process/minidump/MinidumpParserTest.cpp Tue Sep 6 15:57:50 2016
@@ -32,66 +32,60 @@ extern const char *TestMainArgv0;
using namespace lldb_private;
using namespace minidump;
-class MinidumpParserTest : public testing::Test
-{
+class MinidumpParserTest : public testing::Test {
public:
- void
- SetUp() override
- {
- llvm::StringRef dmp_folder = llvm::sys::path::parent_path(TestMainArgv0);
- inputs_folder = dmp_folder;
- llvm::sys::path::append(inputs_folder, "Inputs");
- }
-
- void
- SetUpData(const char *minidump_filename, size_t load_size = SIZE_MAX)
- {
- llvm::SmallString<128> filename = inputs_folder;
- llvm::sys::path::append(filename, minidump_filename);
- FileSpec minidump_file(filename.c_str(), false);
- lldb::DataBufferSP data_sp(minidump_file.MemoryMapFileContents(0, load_size));
- llvm::Optional<MinidumpParser> optional_parser = MinidumpParser::Create(data_sp);
- ASSERT_TRUE(optional_parser.hasValue());
- parser.reset(new MinidumpParser(optional_parser.getValue()));
- ASSERT_GT(parser->GetByteSize(), 0UL);
- }
+ void SetUp() override {
+ llvm::StringRef dmp_folder = llvm::sys::path::parent_path(TestMainArgv0);
+ inputs_folder = dmp_folder;
+ llvm::sys::path::append(inputs_folder, "Inputs");
+ }
+
+ void SetUpData(const char *minidump_filename, size_t load_size = SIZE_MAX) {
+ llvm::SmallString<128> filename = inputs_folder;
+ llvm::sys::path::append(filename, minidump_filename);
+ FileSpec minidump_file(filename.c_str(), false);
+ lldb::DataBufferSP data_sp(
+ minidump_file.MemoryMapFileContents(0, load_size));
+ llvm::Optional<MinidumpParser> optional_parser =
+ MinidumpParser::Create(data_sp);
+ ASSERT_TRUE(optional_parser.hasValue());
+ parser.reset(new MinidumpParser(optional_parser.getValue()));
+ ASSERT_GT(parser->GetByteSize(), 0UL);
+ }
- llvm::SmallString<128> inputs_folder;
- std::unique_ptr<MinidumpParser> parser;
+ llvm::SmallString<128> inputs_folder;
+ std::unique_ptr<MinidumpParser> parser;
};
-TEST_F(MinidumpParserTest, GetThreads)
-{
- SetUpData("linux-x86_64.dmp");
- llvm::Optional<std::vector<const MinidumpThread *>> thread_list;
-
- thread_list = parser->GetThreads();
- ASSERT_TRUE(thread_list.hasValue());
- ASSERT_EQ(1UL, thread_list->size());
+TEST_F(MinidumpParserTest, GetThreads) {
+ SetUpData("linux-x86_64.dmp");
+ llvm::Optional<std::vector<const MinidumpThread *>> thread_list;
+
+ thread_list = parser->GetThreads();
+ ASSERT_TRUE(thread_list.hasValue());
+ ASSERT_EQ(1UL, thread_list->size());
- const MinidumpThread *thread = thread_list.getValue()[0];
- ASSERT_EQ(16001UL, thread->thread_id);
+ const MinidumpThread *thread = thread_list.getValue()[0];
+ ASSERT_EQ(16001UL, thread->thread_id);
}
-TEST_F(MinidumpParserTest, GetThreadsTruncatedFile)
-{
- SetUpData("linux-x86_64.dmp", 200);
- llvm::Optional<std::vector<const MinidumpThread *>> thread_list;
+TEST_F(MinidumpParserTest, GetThreadsTruncatedFile) {
+ SetUpData("linux-x86_64.dmp", 200);
+ llvm::Optional<std::vector<const MinidumpThread *>> thread_list;
- thread_list = parser->GetThreads();
- ASSERT_FALSE(thread_list.hasValue());
+ thread_list = parser->GetThreads();
+ ASSERT_FALSE(thread_list.hasValue());
}
-TEST_F(MinidumpParserTest, GetArchitecture)
-{
- SetUpData("linux-x86_64.dmp");
- ASSERT_EQ(llvm::Triple::ArchType::x86_64, parser->GetArchitecture().GetTriple().getArch());
+TEST_F(MinidumpParserTest, GetArchitecture) {
+ SetUpData("linux-x86_64.dmp");
+ ASSERT_EQ(llvm::Triple::ArchType::x86_64,
+ parser->GetArchitecture().GetTriple().getArch());
}
-TEST_F(MinidumpParserTest, GetMiscInfo)
-{
- SetUpData("linux-x86_64.dmp");
- const MinidumpMiscInfo *misc_info = parser->GetMiscInfo();
- ASSERT_EQ(nullptr, misc_info);
- // linux breakpad generated minidump files don't have misc info stream
+TEST_F(MinidumpParserTest, GetMiscInfo) {
+ SetUpData("linux-x86_64.dmp");
+ const MinidumpMiscInfo *misc_info = parser->GetMiscInfo();
+ ASSERT_EQ(nullptr, misc_info);
+ // linux breakpad generated minidump files don't have misc info stream
}
Modified: lldb/trunk/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp?rev=280751&r1=280750&r2=280751&view=diff
==============================================================================
--- lldb/trunk/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp (original)
+++ lldb/trunk/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp Tue Sep 6 15:57:50 2016
@@ -7,615 +7,593 @@
//
//===----------------------------------------------------------------------===//
-#include "gtest/gtest.h"
#include "Plugins/ScriptInterpreter/Python/lldb-python.h"
+#include "gtest/gtest.h"
+#include "Plugins/ScriptInterpreter/Python/PythonDataObjects.h"
+#include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h"
#include "lldb/Host/File.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostInfo.h"
-#include "Plugins/ScriptInterpreter/Python/PythonDataObjects.h"
-#include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h"
#include "PythonTestSuite.h"
using namespace lldb_private;
-class PythonDataObjectsTest : public PythonTestSuite
-{
- public:
- void
- SetUp() override
- {
- PythonTestSuite::SetUp();
-
- PythonString sys_module("sys");
- m_sys_module.Reset(PyRefType::Owned, PyImport_Import(sys_module.get()));
- m_main_module = PythonModule::MainModule();
- m_builtins_module = PythonModule::BuiltinsModule();
- }
-
- void
- TearDown() override
- {
- m_sys_module.Reset();
- m_main_module.Reset();
- m_builtins_module.Reset();
-
- PythonTestSuite::TearDown();
- }
-
- protected:
- PythonModule m_sys_module;
- PythonModule m_main_module;
- PythonModule m_builtins_module;
+class PythonDataObjectsTest : public PythonTestSuite {
+public:
+ void SetUp() override {
+ PythonTestSuite::SetUp();
+
+ PythonString sys_module("sys");
+ m_sys_module.Reset(PyRefType::Owned, PyImport_Import(sys_module.get()));
+ m_main_module = PythonModule::MainModule();
+ m_builtins_module = PythonModule::BuiltinsModule();
+ }
+
+ void TearDown() override {
+ m_sys_module.Reset();
+ m_main_module.Reset();
+ m_builtins_module.Reset();
+
+ PythonTestSuite::TearDown();
+ }
+
+protected:
+ PythonModule m_sys_module;
+ PythonModule m_main_module;
+ PythonModule m_builtins_module;
};
-TEST_F(PythonDataObjectsTest, TestOwnedReferences)
-{
- // After creating a new object, the refcount should be >= 1
- PyObject *obj = PyLong_FromLong(3);
- Py_ssize_t original_refcnt = obj->ob_refcnt;
- EXPECT_LE(1, original_refcnt);
+TEST_F(PythonDataObjectsTest, TestOwnedReferences) {
+ // After creating a new object, the refcount should be >= 1
+ PyObject *obj = PyLong_FromLong(3);
+ Py_ssize_t original_refcnt = obj->ob_refcnt;
+ EXPECT_LE(1, original_refcnt);
- // If we take an owned reference, the refcount should be the same
- PythonObject owned_long(PyRefType::Owned, obj);
- EXPECT_EQ(original_refcnt, owned_long.get()->ob_refcnt);
+ // If we take an owned reference, the refcount should be the same
+ PythonObject owned_long(PyRefType::Owned, obj);
+ EXPECT_EQ(original_refcnt, owned_long.get()->ob_refcnt);
- // Take another reference and verify that the refcount increases by 1
- PythonObject strong_ref(owned_long);
- EXPECT_EQ(original_refcnt + 1, strong_ref.get()->ob_refcnt);
+ // Take another reference and verify that the refcount increases by 1
+ PythonObject strong_ref(owned_long);
+ EXPECT_EQ(original_refcnt + 1, strong_ref.get()->ob_refcnt);
- // If we reset the first one, the refcount should be the original value.
- owned_long.Reset();
- EXPECT_EQ(original_refcnt, strong_ref.get()->ob_refcnt);
+ // If we reset the first one, the refcount should be the original value.
+ owned_long.Reset();
+ EXPECT_EQ(original_refcnt, strong_ref.get()->ob_refcnt);
}
-TEST_F(PythonDataObjectsTest, TestResetting)
-{
- PythonDictionary dict(PyInitialValue::Empty);
+TEST_F(PythonDataObjectsTest, TestResetting) {
+ PythonDictionary dict(PyInitialValue::Empty);
- PyObject *new_dict = PyDict_New();
- dict.Reset(PyRefType::Owned, new_dict);
- EXPECT_EQ(new_dict, dict.get());
+ PyObject *new_dict = PyDict_New();
+ dict.Reset(PyRefType::Owned, new_dict);
+ EXPECT_EQ(new_dict, dict.get());
- dict.Reset(PyRefType::Owned, nullptr);
- EXPECT_EQ(nullptr, dict.get());
+ dict.Reset(PyRefType::Owned, nullptr);
+ EXPECT_EQ(nullptr, dict.get());
- dict.Reset(PyRefType::Owned, PyDict_New());
- EXPECT_NE(nullptr, dict.get());
- dict.Reset();
- EXPECT_EQ(nullptr, dict.get());
+ dict.Reset(PyRefType::Owned, PyDict_New());
+ EXPECT_NE(nullptr, dict.get());
+ dict.Reset();
+ EXPECT_EQ(nullptr, dict.get());
}
-TEST_F(PythonDataObjectsTest, TestBorrowedReferences)
-{
- PythonInteger long_value(PyRefType::Owned, PyLong_FromLong(3));
- Py_ssize_t original_refcnt = long_value.get()->ob_refcnt;
- EXPECT_LE(1, original_refcnt);
+TEST_F(PythonDataObjectsTest, TestBorrowedReferences) {
+ PythonInteger long_value(PyRefType::Owned, PyLong_FromLong(3));
+ Py_ssize_t original_refcnt = long_value.get()->ob_refcnt;
+ EXPECT_LE(1, original_refcnt);
- PythonInteger borrowed_long(PyRefType::Borrowed, long_value.get());
- EXPECT_EQ(original_refcnt + 1, borrowed_long.get()->ob_refcnt);
+ PythonInteger borrowed_long(PyRefType::Borrowed, long_value.get());
+ EXPECT_EQ(original_refcnt + 1, borrowed_long.get()->ob_refcnt);
}
-TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionNoDot)
-{
- PythonObject sys_module = m_main_module.ResolveName("sys");
- EXPECT_EQ(m_sys_module.get(), sys_module.get());
- EXPECT_TRUE(sys_module.IsAllocated());
- EXPECT_TRUE(PythonModule::Check(sys_module.get()));
+TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionNoDot) {
+ PythonObject sys_module = m_main_module.ResolveName("sys");
+ EXPECT_EQ(m_sys_module.get(), sys_module.get());
+ EXPECT_TRUE(sys_module.IsAllocated());
+ EXPECT_TRUE(PythonModule::Check(sys_module.get()));
}
-TEST_F(PythonDataObjectsTest, TestModuleNameResolutionNoDot)
-{
- PythonObject sys_path = m_sys_module.ResolveName("path");
- PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
- EXPECT_TRUE(sys_path.IsAllocated());
- EXPECT_TRUE(sys_version_info.IsAllocated());
+TEST_F(PythonDataObjectsTest, TestModuleNameResolutionNoDot) {
+ PythonObject sys_path = m_sys_module.ResolveName("path");
+ PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
+ EXPECT_TRUE(sys_path.IsAllocated());
+ EXPECT_TRUE(sys_version_info.IsAllocated());
- EXPECT_TRUE(PythonList::Check(sys_path.get()));
+ EXPECT_TRUE(PythonList::Check(sys_path.get()));
}
-TEST_F(PythonDataObjectsTest, TestTypeNameResolutionNoDot)
-{
- PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
+TEST_F(PythonDataObjectsTest, TestTypeNameResolutionNoDot) {
+ PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
- PythonObject version_info_type(PyRefType::Owned, PyObject_Type(sys_version_info.get()));
- EXPECT_TRUE(version_info_type.IsAllocated());
- PythonObject major_version_field = version_info_type.ResolveName("major");
- EXPECT_TRUE(major_version_field.IsAllocated());
+ PythonObject version_info_type(PyRefType::Owned,
+ PyObject_Type(sys_version_info.get()));
+ EXPECT_TRUE(version_info_type.IsAllocated());
+ PythonObject major_version_field = version_info_type.ResolveName("major");
+ EXPECT_TRUE(major_version_field.IsAllocated());
}
-TEST_F(PythonDataObjectsTest, TestInstanceNameResolutionNoDot)
-{
- PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
- PythonObject major_version_field = sys_version_info.ResolveName("major");
- PythonObject minor_version_field = sys_version_info.ResolveName("minor");
+TEST_F(PythonDataObjectsTest, TestInstanceNameResolutionNoDot) {
+ PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
+ PythonObject major_version_field = sys_version_info.ResolveName("major");
+ PythonObject minor_version_field = sys_version_info.ResolveName("minor");
- EXPECT_TRUE(major_version_field.IsAllocated());
- EXPECT_TRUE(minor_version_field.IsAllocated());
+ EXPECT_TRUE(major_version_field.IsAllocated());
+ EXPECT_TRUE(minor_version_field.IsAllocated());
- PythonInteger major_version_value = major_version_field.AsType<PythonInteger>();
- PythonInteger minor_version_value = minor_version_field.AsType<PythonInteger>();
+ PythonInteger major_version_value =
+ major_version_field.AsType<PythonInteger>();
+ PythonInteger minor_version_value =
+ minor_version_field.AsType<PythonInteger>();
- EXPECT_EQ(PY_MAJOR_VERSION, major_version_value.GetInteger());
- EXPECT_EQ(PY_MINOR_VERSION, minor_version_value.GetInteger());
+ EXPECT_EQ(PY_MAJOR_VERSION, major_version_value.GetInteger());
+ EXPECT_EQ(PY_MINOR_VERSION, minor_version_value.GetInteger());
}
-TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionWithDot)
-{
- PythonObject sys_path = m_main_module.ResolveName("sys.path");
- EXPECT_TRUE(sys_path.IsAllocated());
- EXPECT_TRUE(PythonList::Check(sys_path.get()));
+TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionWithDot) {
+ PythonObject sys_path = m_main_module.ResolveName("sys.path");
+ EXPECT_TRUE(sys_path.IsAllocated());
+ EXPECT_TRUE(PythonList::Check(sys_path.get()));
- PythonInteger version_major = m_main_module.ResolveName(
- "sys.version_info.major").AsType<PythonInteger>();
- PythonInteger version_minor = m_main_module.ResolveName(
- "sys.version_info.minor").AsType<PythonInteger>();
- EXPECT_TRUE(version_major.IsAllocated());
- EXPECT_TRUE(version_minor.IsAllocated());
- EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
- EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
+ PythonInteger version_major =
+ m_main_module.ResolveName("sys.version_info.major")
+ .AsType<PythonInteger>();
+ PythonInteger version_minor =
+ m_main_module.ResolveName("sys.version_info.minor")
+ .AsType<PythonInteger>();
+ EXPECT_TRUE(version_major.IsAllocated());
+ EXPECT_TRUE(version_minor.IsAllocated());
+ EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
+ EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
}
-TEST_F(PythonDataObjectsTest, TestDictionaryResolutionWithDot)
-{
- // Make up a custom dictionary with "sys" pointing to the `sys` module.
- PythonDictionary dict(PyInitialValue::Empty);
- dict.SetItemForKey(PythonString("sys"), m_sys_module);
+TEST_F(PythonDataObjectsTest, TestDictionaryResolutionWithDot) {
+ // Make up a custom dictionary with "sys" pointing to the `sys` module.
+ PythonDictionary dict(PyInitialValue::Empty);
+ dict.SetItemForKey(PythonString("sys"), m_sys_module);
- // Now use that dictionary to resolve `sys.version_info.major`
- PythonInteger version_major = PythonObject::ResolveNameWithDictionary(
- "sys.version_info.major", dict).AsType<PythonInteger>();
- PythonInteger version_minor = PythonObject::ResolveNameWithDictionary(
- "sys.version_info.minor", dict).AsType<PythonInteger>();
- EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
- EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
+ // Now use that dictionary to resolve `sys.version_info.major`
+ PythonInteger version_major =
+ PythonObject::ResolveNameWithDictionary("sys.version_info.major", dict)
+ .AsType<PythonInteger>();
+ PythonInteger version_minor =
+ PythonObject::ResolveNameWithDictionary("sys.version_info.minor", dict)
+ .AsType<PythonInteger>();
+ EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
+ EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
}
-TEST_F(PythonDataObjectsTest, TestPythonInteger)
-{
+TEST_F(PythonDataObjectsTest, TestPythonInteger) {
// Test that integers behave correctly when wrapped by a PythonInteger.
#if PY_MAJOR_VERSION < 3
- // Verify that `PythonInt` works correctly when given a PyInt object.
- // Note that PyInt doesn't exist in Python 3.x, so this is only for 2.x
- PyObject *py_int = PyInt_FromLong(12);
- EXPECT_TRUE(PythonInteger::Check(py_int));
- PythonInteger python_int(PyRefType::Owned, py_int);
+ // Verify that `PythonInt` works correctly when given a PyInt object.
+ // Note that PyInt doesn't exist in Python 3.x, so this is only for 2.x
+ PyObject *py_int = PyInt_FromLong(12);
+ EXPECT_TRUE(PythonInteger::Check(py_int));
+ PythonInteger python_int(PyRefType::Owned, py_int);
- EXPECT_EQ(PyObjectType::Integer, python_int.GetObjectType());
- EXPECT_EQ(12, python_int.GetInteger());
+ EXPECT_EQ(PyObjectType::Integer, python_int.GetObjectType());
+ EXPECT_EQ(12, python_int.GetInteger());
#endif
- // Verify that `PythonInteger` works correctly when given a PyLong object.
- PyObject *py_long = PyLong_FromLong(12);
- EXPECT_TRUE(PythonInteger::Check(py_long));
- PythonInteger python_long(PyRefType::Owned, py_long);
- EXPECT_EQ(PyObjectType::Integer, python_long.GetObjectType());
-
- // Verify that you can reset the value and that it is reflected properly.
- python_long.SetInteger(40);
- EXPECT_EQ(40, python_long.GetInteger());
-
- // Test that creating a `PythonInteger` object works correctly with the
- // int constructor.
- PythonInteger constructed_int(7);
- EXPECT_EQ(7, constructed_int.GetInteger());
-}
-
-TEST_F(PythonDataObjectsTest, TestPythonBytes)
-{
- static const char *test_bytes = "PythonDataObjectsTest::TestPythonBytes";
- PyObject *py_bytes = PyBytes_FromString(test_bytes);
- EXPECT_TRUE(PythonBytes::Check(py_bytes));
- PythonBytes python_bytes(PyRefType::Owned, py_bytes);
+ // Verify that `PythonInteger` works correctly when given a PyLong object.
+ PyObject *py_long = PyLong_FromLong(12);
+ EXPECT_TRUE(PythonInteger::Check(py_long));
+ PythonInteger python_long(PyRefType::Owned, py_long);
+ EXPECT_EQ(PyObjectType::Integer, python_long.GetObjectType());
+
+ // Verify that you can reset the value and that it is reflected properly.
+ python_long.SetInteger(40);
+ EXPECT_EQ(40, python_long.GetInteger());
+
+ // Test that creating a `PythonInteger` object works correctly with the
+ // int constructor.
+ PythonInteger constructed_int(7);
+ EXPECT_EQ(7, constructed_int.GetInteger());
+}
+
+TEST_F(PythonDataObjectsTest, TestPythonBytes) {
+ static const char *test_bytes = "PythonDataObjectsTest::TestPythonBytes";
+ PyObject *py_bytes = PyBytes_FromString(test_bytes);
+ EXPECT_TRUE(PythonBytes::Check(py_bytes));
+ PythonBytes python_bytes(PyRefType::Owned, py_bytes);
#if PY_MAJOR_VERSION < 3
- EXPECT_TRUE(PythonString::Check(py_bytes));
- EXPECT_EQ(PyObjectType::String, python_bytes.GetObjectType());
+ EXPECT_TRUE(PythonString::Check(py_bytes));
+ EXPECT_EQ(PyObjectType::String, python_bytes.GetObjectType());
#else
- EXPECT_FALSE(PythonString::Check(py_bytes));
- EXPECT_EQ(PyObjectType::Bytes, python_bytes.GetObjectType());
+ EXPECT_FALSE(PythonString::Check(py_bytes));
+ EXPECT_EQ(PyObjectType::Bytes, python_bytes.GetObjectType());
#endif
- llvm::ArrayRef<uint8_t> bytes = python_bytes.GetBytes();
- EXPECT_EQ(bytes.size(), strlen(test_bytes));
- EXPECT_EQ(0, ::memcmp(bytes.data(), test_bytes, bytes.size()));
-}
-
-TEST_F(PythonDataObjectsTest, TestPythonByteArray)
-{
- static const char *test_bytes = "PythonDataObjectsTest::TestPythonByteArray";
- llvm::StringRef orig_bytes(test_bytes);
- PyObject *py_bytes = PyByteArray_FromStringAndSize(test_bytes, orig_bytes.size());
- EXPECT_TRUE(PythonByteArray::Check(py_bytes));
- PythonByteArray python_bytes(PyRefType::Owned, py_bytes);
- EXPECT_EQ(PyObjectType::ByteArray, python_bytes.GetObjectType());
-
- llvm::ArrayRef<uint8_t> after_bytes = python_bytes.GetBytes();
- EXPECT_EQ(after_bytes.size(), orig_bytes.size());
- EXPECT_EQ(0, ::memcmp(orig_bytes.data(), test_bytes, orig_bytes.size()));
-}
-
-TEST_F(PythonDataObjectsTest, TestPythonString)
-{
- // Test that strings behave correctly when wrapped by a PythonString.
+ llvm::ArrayRef<uint8_t> bytes = python_bytes.GetBytes();
+ EXPECT_EQ(bytes.size(), strlen(test_bytes));
+ EXPECT_EQ(0, ::memcmp(bytes.data(), test_bytes, bytes.size()));
+}
+
+TEST_F(PythonDataObjectsTest, TestPythonByteArray) {
+ static const char *test_bytes = "PythonDataObjectsTest::TestPythonByteArray";
+ llvm::StringRef orig_bytes(test_bytes);
+ PyObject *py_bytes =
+ PyByteArray_FromStringAndSize(test_bytes, orig_bytes.size());
+ EXPECT_TRUE(PythonByteArray::Check(py_bytes));
+ PythonByteArray python_bytes(PyRefType::Owned, py_bytes);
+ EXPECT_EQ(PyObjectType::ByteArray, python_bytes.GetObjectType());
+
+ llvm::ArrayRef<uint8_t> after_bytes = python_bytes.GetBytes();
+ EXPECT_EQ(after_bytes.size(), orig_bytes.size());
+ EXPECT_EQ(0, ::memcmp(orig_bytes.data(), test_bytes, orig_bytes.size()));
+}
+
+TEST_F(PythonDataObjectsTest, TestPythonString) {
+ // Test that strings behave correctly when wrapped by a PythonString.
- static const char *test_string = "PythonDataObjectsTest::TestPythonString1";
- static const char *test_string2 = "PythonDataObjectsTest::TestPythonString2";
+ static const char *test_string = "PythonDataObjectsTest::TestPythonString1";
+ static const char *test_string2 = "PythonDataObjectsTest::TestPythonString2";
#if PY_MAJOR_VERSION < 3
- // Verify that `PythonString` works correctly when given a PyString object.
- // Note that PyString doesn't exist in Python 3.x, so this is only for 2.x
- PyObject *py_string = PyString_FromString(test_string);
- EXPECT_TRUE(PythonString::Check(py_string));
- PythonString python_string(PyRefType::Owned, py_string);
+ // Verify that `PythonString` works correctly when given a PyString object.
+ // Note that PyString doesn't exist in Python 3.x, so this is only for 2.x
+ PyObject *py_string = PyString_FromString(test_string);
+ EXPECT_TRUE(PythonString::Check(py_string));
+ PythonString python_string(PyRefType::Owned, py_string);
- EXPECT_EQ(PyObjectType::String, python_string.GetObjectType());
- EXPECT_STREQ(test_string, python_string.GetString().data());
+ EXPECT_EQ(PyObjectType::String, python_string.GetObjectType());
+ EXPECT_STREQ(test_string, python_string.GetString().data());
#else
- // Verify that `PythonString` works correctly when given a PyUnicode object.
- PyObject *py_unicode = PyUnicode_FromString(test_string);
- EXPECT_TRUE(PythonString::Check(py_unicode));
- PythonString python_unicode(PyRefType::Owned, py_unicode);
- EXPECT_EQ(PyObjectType::String, python_unicode.GetObjectType());
- EXPECT_STREQ(test_string, python_unicode.GetString().data());
+ // Verify that `PythonString` works correctly when given a PyUnicode object.
+ PyObject *py_unicode = PyUnicode_FromString(test_string);
+ EXPECT_TRUE(PythonString::Check(py_unicode));
+ PythonString python_unicode(PyRefType::Owned, py_unicode);
+ EXPECT_EQ(PyObjectType::String, python_unicode.GetObjectType());
+ EXPECT_STREQ(test_string, python_unicode.GetString().data());
#endif
- // Test that creating a `PythonString` object works correctly with the
- // string constructor
- PythonString constructed_string(test_string2);
- EXPECT_STREQ(test_string2, constructed_string.GetString().str().c_str());
+ // Test that creating a `PythonString` object works correctly with the
+ // string constructor
+ PythonString constructed_string(test_string2);
+ EXPECT_STREQ(test_string2, constructed_string.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonStringToStr)
-{
- const char *c_str = "PythonDataObjectsTest::TestPythonStringToStr";
+TEST_F(PythonDataObjectsTest, TestPythonStringToStr) {
+ const char *c_str = "PythonDataObjectsTest::TestPythonStringToStr";
- PythonString str(c_str);
- EXPECT_STREQ(c_str, str.GetString().str().c_str());
+ PythonString str(c_str);
+ EXPECT_STREQ(c_str, str.GetString().str().c_str());
- PythonString str_str = str.Str();
- EXPECT_STREQ(c_str, str_str.GetString().str().c_str());
+ PythonString str_str = str.Str();
+ EXPECT_STREQ(c_str, str_str.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonIntegerToStr)
-{
-}
+TEST_F(PythonDataObjectsTest, TestPythonIntegerToStr) {}
-TEST_F(PythonDataObjectsTest, TestPythonIntegerToStructuredInteger)
-{
- PythonInteger integer(7);
- auto int_sp = integer.CreateStructuredInteger();
- EXPECT_EQ(7U, int_sp->GetValue());
+TEST_F(PythonDataObjectsTest, TestPythonIntegerToStructuredInteger) {
+ PythonInteger integer(7);
+ auto int_sp = integer.CreateStructuredInteger();
+ EXPECT_EQ(7U, int_sp->GetValue());
}
-TEST_F(PythonDataObjectsTest, TestPythonStringToStructuredString)
-{
- static const char *test_string = "PythonDataObjectsTest::TestPythonStringToStructuredString";
- PythonString constructed_string(test_string);
- auto string_sp = constructed_string.CreateStructuredString();
- EXPECT_STREQ(test_string, string_sp->GetStringValue().c_str());
+TEST_F(PythonDataObjectsTest, TestPythonStringToStructuredString) {
+ static const char *test_string =
+ "PythonDataObjectsTest::TestPythonStringToStructuredString";
+ PythonString constructed_string(test_string);
+ auto string_sp = constructed_string.CreateStructuredString();
+ EXPECT_STREQ(test_string, string_sp->GetStringValue().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonListValueEquality)
-{
- // Test that a list which is built through the native
- // Python API behaves correctly when wrapped by a PythonList.
- static const unsigned list_size = 2;
- static const long long_value0 = 5;
- static const char *const string_value1 = "String Index 1";
+TEST_F(PythonDataObjectsTest, TestPythonListValueEquality) {
+ // Test that a list which is built through the native
+ // Python API behaves correctly when wrapped by a PythonList.
+ static const unsigned list_size = 2;
+ static const long long_value0 = 5;
+ static const char *const string_value1 = "String Index 1";
- PyObject *py_list = PyList_New(2);
- EXPECT_TRUE(PythonList::Check(py_list));
- PythonList list(PyRefType::Owned, py_list);
+ PyObject *py_list = PyList_New(2);
+ EXPECT_TRUE(PythonList::Check(py_list));
+ PythonList list(PyRefType::Owned, py_list);
- PythonObject list_items[list_size];
- list_items[0].Reset(PythonInteger(long_value0));
- list_items[1].Reset(PythonString(string_value1));
+ PythonObject list_items[list_size];
+ list_items[0].Reset(PythonInteger(long_value0));
+ list_items[1].Reset(PythonString(string_value1));
- for (unsigned i = 0; i < list_size; ++i)
- list.SetItemAtIndex(i, list_items[i]);
+ for (unsigned i = 0; i < list_size; ++i)
+ list.SetItemAtIndex(i, list_items[i]);
- EXPECT_EQ(list_size, list.GetSize());
- EXPECT_EQ(PyObjectType::List, list.GetObjectType());
+ EXPECT_EQ(list_size, list.GetSize());
+ EXPECT_EQ(PyObjectType::List, list.GetObjectType());
- // Verify that the values match
- PythonObject chk_value1 = list.GetItemAtIndex(0);
- PythonObject chk_value2 = list.GetItemAtIndex(1);
- EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
- EXPECT_TRUE(PythonString::Check(chk_value2.get()));
+ // Verify that the values match
+ PythonObject chk_value1 = list.GetItemAtIndex(0);
+ PythonObject chk_value2 = list.GetItemAtIndex(1);
+ EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
+ EXPECT_TRUE(PythonString::Check(chk_value2.get()));
- PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
- PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
+ PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
+ PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
- EXPECT_EQ(long_value0, chk_int.GetInteger());
- EXPECT_STREQ(string_value1, chk_str.GetString().str().c_str());
+ EXPECT_EQ(long_value0, chk_int.GetInteger());
+ EXPECT_STREQ(string_value1, chk_str.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonListManipulation)
-{
- // Test that manipulation of a PythonList behaves correctly when
- // wrapped by a PythonDictionary.
+TEST_F(PythonDataObjectsTest, TestPythonListManipulation) {
+ // Test that manipulation of a PythonList behaves correctly when
+ // wrapped by a PythonDictionary.
- static const long long_value0 = 5;
- static const char *const string_value1 = "String Index 1";
+ static const long long_value0 = 5;
+ static const char *const string_value1 = "String Index 1";
- PythonList list(PyInitialValue::Empty);
- PythonInteger integer(long_value0);
- PythonString string(string_value1);
+ PythonList list(PyInitialValue::Empty);
+ PythonInteger integer(long_value0);
+ PythonString string(string_value1);
- list.AppendItem(integer);
- list.AppendItem(string);
- EXPECT_EQ(2U, list.GetSize());
+ list.AppendItem(integer);
+ list.AppendItem(string);
+ EXPECT_EQ(2U, list.GetSize());
- // Verify that the values match
- PythonObject chk_value1 = list.GetItemAtIndex(0);
- PythonObject chk_value2 = list.GetItemAtIndex(1);
- EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
- EXPECT_TRUE(PythonString::Check(chk_value2.get()));
+ // Verify that the values match
+ PythonObject chk_value1 = list.GetItemAtIndex(0);
+ PythonObject chk_value2 = list.GetItemAtIndex(1);
+ EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
+ EXPECT_TRUE(PythonString::Check(chk_value2.get()));
- PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
- PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
+ PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
+ PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
- EXPECT_EQ(long_value0, chk_int.GetInteger());
- EXPECT_STREQ(string_value1, chk_str.GetString().str().c_str());
+ EXPECT_EQ(long_value0, chk_int.GetInteger());
+ EXPECT_STREQ(string_value1, chk_str.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonListToStructuredList)
-{
- static const long long_value0 = 5;
- static const char *const string_value1 = "String Index 1";
+TEST_F(PythonDataObjectsTest, TestPythonListToStructuredList) {
+ static const long long_value0 = 5;
+ static const char *const string_value1 = "String Index 1";
- PythonList list(PyInitialValue::Empty);
- list.AppendItem(PythonInteger(long_value0));
- list.AppendItem(PythonString(string_value1));
+ PythonList list(PyInitialValue::Empty);
+ list.AppendItem(PythonInteger(long_value0));
+ list.AppendItem(PythonString(string_value1));
- auto array_sp = list.CreateStructuredArray();
- EXPECT_EQ(StructuredData::Type::eTypeInteger, array_sp->GetItemAtIndex(0)->GetType());
- EXPECT_EQ(StructuredData::Type::eTypeString, array_sp->GetItemAtIndex(1)->GetType());
+ auto array_sp = list.CreateStructuredArray();
+ EXPECT_EQ(StructuredData::Type::eTypeInteger,
+ array_sp->GetItemAtIndex(0)->GetType());
+ EXPECT_EQ(StructuredData::Type::eTypeString,
+ array_sp->GetItemAtIndex(1)->GetType());
- auto int_sp = array_sp->GetItemAtIndex(0)->GetAsInteger();
- auto string_sp = array_sp->GetItemAtIndex(1)->GetAsString();
+ auto int_sp = array_sp->GetItemAtIndex(0)->GetAsInteger();
+ auto string_sp = array_sp->GetItemAtIndex(1)->GetAsString();
- EXPECT_EQ(long_value0, long(int_sp->GetValue()));
- EXPECT_STREQ(string_value1, string_sp->GetValue().c_str());
+ EXPECT_EQ(long_value0, long(int_sp->GetValue()));
+ EXPECT_STREQ(string_value1, string_sp->GetValue().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonTupleSize)
-{
- PythonTuple tuple(PyInitialValue::Empty);
- EXPECT_EQ(0U, tuple.GetSize());
+TEST_F(PythonDataObjectsTest, TestPythonTupleSize) {
+ PythonTuple tuple(PyInitialValue::Empty);
+ EXPECT_EQ(0U, tuple.GetSize());
- tuple = PythonTuple(3);
- EXPECT_EQ(3U, tuple.GetSize());
+ tuple = PythonTuple(3);
+ EXPECT_EQ(3U, tuple.GetSize());
}
-TEST_F(PythonDataObjectsTest, TestPythonTupleValues)
-{
- PythonTuple tuple(3);
+TEST_F(PythonDataObjectsTest, TestPythonTupleValues) {
+ PythonTuple tuple(3);
- PythonInteger int_value(1);
- PythonString string_value("Test");
- PythonObject none_value(PyRefType::Borrowed, Py_None);
+ PythonInteger int_value(1);
+ PythonString string_value("Test");
+ PythonObject none_value(PyRefType::Borrowed, Py_None);
- tuple.SetItemAtIndex(0, int_value);
- tuple.SetItemAtIndex(1, string_value);
- tuple.SetItemAtIndex(2, none_value);
+ tuple.SetItemAtIndex(0, int_value);
+ tuple.SetItemAtIndex(1, string_value);
+ tuple.SetItemAtIndex(2, none_value);
- EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
}
-TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList)
-{
- PythonInteger int_value(1);
- PythonString string_value("Test");
- PythonObject none_value(PyRefType::Borrowed, Py_None);
- PythonTuple tuple{ int_value, string_value, none_value };
- EXPECT_EQ(3U, tuple.GetSize());
+TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList) {
+ PythonInteger int_value(1);
+ PythonString string_value("Test");
+ PythonObject none_value(PyRefType::Borrowed, Py_None);
+ PythonTuple tuple{int_value, string_value, none_value};
+ EXPECT_EQ(3U, tuple.GetSize());
- EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
}
-TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList2)
-{
- PythonInteger int_value(1);
- PythonString string_value("Test");
- PythonObject none_value(PyRefType::Borrowed, Py_None);
+TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList2) {
+ PythonInteger int_value(1);
+ PythonString string_value("Test");
+ PythonObject none_value(PyRefType::Borrowed, Py_None);
- PythonTuple tuple{ int_value.get(), string_value.get(), none_value.get() };
- EXPECT_EQ(3U, tuple.GetSize());
+ PythonTuple tuple{int_value.get(), string_value.get(), none_value.get()};
+ EXPECT_EQ(3U, tuple.GetSize());
- EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
- EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
+ EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
}
-TEST_F(PythonDataObjectsTest, TestPythonTupleToStructuredList)
-{
- PythonInteger int_value(1);
- PythonString string_value("Test");
+TEST_F(PythonDataObjectsTest, TestPythonTupleToStructuredList) {
+ PythonInteger int_value(1);
+ PythonString string_value("Test");
- PythonTuple tuple{ int_value.get(), string_value.get() };
+ PythonTuple tuple{int_value.get(), string_value.get()};
- auto array_sp = tuple.CreateStructuredArray();
- EXPECT_EQ(tuple.GetSize(), array_sp->GetSize());
- EXPECT_EQ(StructuredData::Type::eTypeInteger, array_sp->GetItemAtIndex(0)->GetType());
- EXPECT_EQ(StructuredData::Type::eTypeString, array_sp->GetItemAtIndex(1)->GetType());
+ auto array_sp = tuple.CreateStructuredArray();
+ EXPECT_EQ(tuple.GetSize(), array_sp->GetSize());
+ EXPECT_EQ(StructuredData::Type::eTypeInteger,
+ array_sp->GetItemAtIndex(0)->GetType());
+ EXPECT_EQ(StructuredData::Type::eTypeString,
+ array_sp->GetItemAtIndex(1)->GetType());
}
-TEST_F(PythonDataObjectsTest, TestPythonDictionaryValueEquality)
-{
- // Test that a dictionary which is built through the native
- // Python API behaves correctly when wrapped by a PythonDictionary.
- static const unsigned dict_entries = 2;
- const char *key_0 = "Key 0";
- int key_1 = 1;
- const int value_0 = 0;
- const char *value_1 = "Value 1";
+TEST_F(PythonDataObjectsTest, TestPythonDictionaryValueEquality) {
+ // Test that a dictionary which is built through the native
+ // Python API behaves correctly when wrapped by a PythonDictionary.
+ static const unsigned dict_entries = 2;
+ const char *key_0 = "Key 0";
+ int key_1 = 1;
+ const int value_0 = 0;
+ const char *value_1 = "Value 1";
- PythonObject py_keys[dict_entries];
- PythonObject py_values[dict_entries];
+ PythonObject py_keys[dict_entries];
+ PythonObject py_values[dict_entries];
- py_keys[0].Reset(PythonString(key_0));
- py_keys[1].Reset(PythonInteger(key_1));
- py_values[0].Reset(PythonInteger(value_0));
- py_values[1].Reset(PythonString(value_1));
+ py_keys[0].Reset(PythonString(key_0));
+ py_keys[1].Reset(PythonInteger(key_1));
+ py_values[0].Reset(PythonInteger(value_0));
+ py_values[1].Reset(PythonString(value_1));
- PyObject *py_dict = PyDict_New();
- EXPECT_TRUE(PythonDictionary::Check(py_dict));
- PythonDictionary dict(PyRefType::Owned, py_dict);
+ PyObject *py_dict = PyDict_New();
+ EXPECT_TRUE(PythonDictionary::Check(py_dict));
+ PythonDictionary dict(PyRefType::Owned, py_dict);
- for (unsigned i = 0; i < dict_entries; ++i)
- PyDict_SetItem(py_dict, py_keys[i].get(), py_values[i].get());
- EXPECT_EQ(dict.GetSize(), dict_entries);
- EXPECT_EQ(PyObjectType::Dictionary, dict.GetObjectType());
+ for (unsigned i = 0; i < dict_entries; ++i)
+ PyDict_SetItem(py_dict, py_keys[i].get(), py_values[i].get());
+ EXPECT_EQ(dict.GetSize(), dict_entries);
+ EXPECT_EQ(PyObjectType::Dictionary, dict.GetObjectType());
- // Verify that the values match
- PythonObject chk_value1 = dict.GetItemForKey(py_keys[0]);
- PythonObject chk_value2 = dict.GetItemForKey(py_keys[1]);
- EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
- EXPECT_TRUE(PythonString::Check(chk_value2.get()));
+ // Verify that the values match
+ PythonObject chk_value1 = dict.GetItemForKey(py_keys[0]);
+ PythonObject chk_value2 = dict.GetItemForKey(py_keys[1]);
+ EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
+ EXPECT_TRUE(PythonString::Check(chk_value2.get()));
- PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
- PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
+ PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
+ PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
- EXPECT_EQ(value_0, chk_int.GetInteger());
- EXPECT_STREQ(value_1, chk_str.GetString().str().c_str());
+ EXPECT_EQ(value_0, chk_int.GetInteger());
+ EXPECT_STREQ(value_1, chk_str.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonDictionaryManipulation)
-{
- // Test that manipulation of a dictionary behaves correctly when wrapped
- // by a PythonDictionary.
- static const unsigned dict_entries = 2;
+TEST_F(PythonDataObjectsTest, TestPythonDictionaryManipulation) {
+ // Test that manipulation of a dictionary behaves correctly when wrapped
+ // by a PythonDictionary.
+ static const unsigned dict_entries = 2;
- const char *const key_0 = "Key 0";
- const char *const key_1 = "Key 1";
- const long value_0 = 1;
- const char *const value_1 = "Value 1";
+ const char *const key_0 = "Key 0";
+ const char *const key_1 = "Key 1";
+ const long value_0 = 1;
+ const char *const value_1 = "Value 1";
- PythonString keys[dict_entries];
- PythonObject values[dict_entries];
+ PythonString keys[dict_entries];
+ PythonObject values[dict_entries];
- keys[0].Reset(PythonString(key_0));
- keys[1].Reset(PythonString(key_1));
- values[0].Reset(PythonInteger(value_0));
- values[1].Reset(PythonString(value_1));
+ keys[0].Reset(PythonString(key_0));
+ keys[1].Reset(PythonString(key_1));
+ values[0].Reset(PythonInteger(value_0));
+ values[1].Reset(PythonString(value_1));
- PythonDictionary dict(PyInitialValue::Empty);
- for (int i = 0; i < 2; ++i)
- dict.SetItemForKey(keys[i], values[i]);
+ PythonDictionary dict(PyInitialValue::Empty);
+ for (int i = 0; i < 2; ++i)
+ dict.SetItemForKey(keys[i], values[i]);
- EXPECT_EQ(dict_entries, dict.GetSize());
+ EXPECT_EQ(dict_entries, dict.GetSize());
- // Verify that the keys and values match
- PythonObject chk_value1 = dict.GetItemForKey(keys[0]);
- PythonObject chk_value2 = dict.GetItemForKey(keys[1]);
- EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
- EXPECT_TRUE(PythonString::Check(chk_value2.get()));
+ // Verify that the keys and values match
+ PythonObject chk_value1 = dict.GetItemForKey(keys[0]);
+ PythonObject chk_value2 = dict.GetItemForKey(keys[1]);
+ EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
+ EXPECT_TRUE(PythonString::Check(chk_value2.get()));
- PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
- PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
+ PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
+ PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
- EXPECT_EQ(value_0, chk_int.GetInteger());
- EXPECT_STREQ(value_1, chk_str.GetString().str().c_str());
+ EXPECT_EQ(value_0, chk_int.GetInteger());
+ EXPECT_STREQ(value_1, chk_str.GetString().str().c_str());
}
-TEST_F(PythonDataObjectsTest, TestPythonDictionaryToStructuredDictionary)
-{
- static const char *const string_key0 = "String Key 0";
- static const char *const string_key1 = "String Key 1";
+TEST_F(PythonDataObjectsTest, TestPythonDictionaryToStructuredDictionary) {
+ static const char *const string_key0 = "String Key 0";
+ static const char *const string_key1 = "String Key 1";
- static const char *const string_value0 = "String Value 0";
- static const long int_value1 = 7;
+ static const char *const string_value0 = "String Value 0";
+ static const long int_value1 = 7;
- PythonDictionary dict(PyInitialValue::Empty);
- dict.SetItemForKey(PythonString(string_key0), PythonString(string_value0));
- dict.SetItemForKey(PythonString(string_key1), PythonInteger(int_value1));
+ PythonDictionary dict(PyInitialValue::Empty);
+ dict.SetItemForKey(PythonString(string_key0), PythonString(string_value0));
+ dict.SetItemForKey(PythonString(string_key1), PythonInteger(int_value1));
- auto dict_sp = dict.CreateStructuredDictionary();
- EXPECT_EQ(2U, dict_sp->GetSize());
+ auto dict_sp = dict.CreateStructuredDictionary();
+ EXPECT_EQ(2U, dict_sp->GetSize());
- EXPECT_TRUE(dict_sp->HasKey(string_key0));
- EXPECT_TRUE(dict_sp->HasKey(string_key1));
+ EXPECT_TRUE(dict_sp->HasKey(string_key0));
+ EXPECT_TRUE(dict_sp->HasKey(string_key1));
- auto string_sp = dict_sp->GetValueForKey(string_key0)->GetAsString();
- auto int_sp = dict_sp->GetValueForKey(string_key1)->GetAsInteger();
+ auto string_sp = dict_sp->GetValueForKey(string_key0)->GetAsString();
+ auto int_sp = dict_sp->GetValueForKey(string_key1)->GetAsInteger();
- EXPECT_STREQ(string_value0, string_sp->GetValue().c_str());
- EXPECT_EQ(int_value1, long(int_sp->GetValue()));
+ EXPECT_STREQ(string_value0, string_sp->GetValue().c_str());
+ EXPECT_EQ(int_value1, long(int_sp->GetValue()));
}
-TEST_F(PythonDataObjectsTest, TestPythonCallableCheck)
-{
- PythonObject sys_exc_info = m_sys_module.ResolveName("exc_info");
- PythonObject none(PyRefType::Borrowed, Py_None);
+TEST_F(PythonDataObjectsTest, TestPythonCallableCheck) {
+ PythonObject sys_exc_info = m_sys_module.ResolveName("exc_info");
+ PythonObject none(PyRefType::Borrowed, Py_None);
- EXPECT_TRUE(PythonCallable::Check(sys_exc_info.get()));
- EXPECT_FALSE(PythonCallable::Check(none.get()));
+ EXPECT_TRUE(PythonCallable::Check(sys_exc_info.get()));
+ EXPECT_FALSE(PythonCallable::Check(none.get()));
}
-TEST_F(PythonDataObjectsTest, TestPythonCallableInvoke)
-{
- auto list = m_builtins_module.ResolveName("list").AsType<PythonCallable>();
- PythonInteger one(1);
- PythonString two("two");
- PythonTuple three = { one, two };
+TEST_F(PythonDataObjectsTest, TestPythonCallableInvoke) {
+ auto list = m_builtins_module.ResolveName("list").AsType<PythonCallable>();
+ PythonInteger one(1);
+ PythonString two("two");
+ PythonTuple three = {one, two};
- PythonTuple tuple_to_convert = { one, two, three };
- PythonObject result = list({ tuple_to_convert });
+ PythonTuple tuple_to_convert = {one, two, three};
+ PythonObject result = list({tuple_to_convert});
- EXPECT_TRUE(PythonList::Check(result.get()));
- auto list_result = result.AsType<PythonList>();
- EXPECT_EQ(3U, list_result.GetSize());
- EXPECT_EQ(one.get(), list_result.GetItemAtIndex(0).get());
- EXPECT_EQ(two.get(), list_result.GetItemAtIndex(1).get());
- EXPECT_EQ(three.get(), list_result.GetItemAtIndex(2).get());
+ EXPECT_TRUE(PythonList::Check(result.get()));
+ auto list_result = result.AsType<PythonList>();
+ EXPECT_EQ(3U, list_result.GetSize());
+ EXPECT_EQ(one.get(), list_result.GetItemAtIndex(0).get());
+ EXPECT_EQ(two.get(), list_result.GetItemAtIndex(1).get());
+ EXPECT_EQ(three.get(), list_result.GetItemAtIndex(2).get());
}
-TEST_F(PythonDataObjectsTest, TestPythonFile)
-{
- File file(FileSystem::DEV_NULL, File::eOpenOptionRead);
- PythonFile py_file(file, "r");
- EXPECT_TRUE(PythonFile::Check(py_file.get()));
+TEST_F(PythonDataObjectsTest, TestPythonFile) {
+ File file(FileSystem::DEV_NULL, File::eOpenOptionRead);
+ PythonFile py_file(file, "r");
+ EXPECT_TRUE(PythonFile::Check(py_file.get()));
}
-TEST_F(PythonDataObjectsTest, TestObjectAttributes)
-{
- PythonInteger py_int(42);
- EXPECT_TRUE(py_int.HasAttribute("numerator"));
- EXPECT_FALSE(py_int.HasAttribute("this_should_not_exist"));
+TEST_F(PythonDataObjectsTest, TestObjectAttributes) {
+ PythonInteger py_int(42);
+ EXPECT_TRUE(py_int.HasAttribute("numerator"));
+ EXPECT_FALSE(py_int.HasAttribute("this_should_not_exist"));
- PythonInteger numerator_attr = py_int.GetAttributeValue("numerator").AsType<PythonInteger>();
- EXPECT_TRUE(numerator_attr.IsAllocated());
- EXPECT_EQ(42, numerator_attr.GetInteger());
+ PythonInteger numerator_attr =
+ py_int.GetAttributeValue("numerator").AsType<PythonInteger>();
+ EXPECT_TRUE(numerator_attr.IsAllocated());
+ EXPECT_EQ(42, numerator_attr.GetInteger());
}
-TEST_F(PythonDataObjectsTest, TestExtractingUInt64ThroughStructuredData)
-{
- // Make up a custom dictionary with "sys" pointing to the `sys` module.
- const char *key_name = "addr";
- const uint64_t value = 0xf000000000000000ull;
- PythonDictionary python_dict(PyInitialValue::Empty);
- PythonInteger python_ull_value(PyRefType::Owned, PyLong_FromUnsignedLongLong(value));
- python_dict.SetItemForKey(PythonString(key_name), python_ull_value);
- StructuredData::ObjectSP structured_data_sp = python_dict.CreateStructuredObject();
- EXPECT_TRUE((bool)structured_data_sp);
- if (structured_data_sp)
- {
- StructuredData::Dictionary *structured_dict_ptr = structured_data_sp->GetAsDictionary();
- EXPECT_TRUE(structured_dict_ptr != nullptr);
- if (structured_dict_ptr)
- {
- StructuredData::ObjectSP structured_addr_value_sp = structured_dict_ptr->GetValueForKey(key_name);
- EXPECT_TRUE((bool)structured_addr_value_sp);
- const uint64_t extracted_value = structured_addr_value_sp->GetIntegerValue(123);
- EXPECT_TRUE(extracted_value == value);
- }
+TEST_F(PythonDataObjectsTest, TestExtractingUInt64ThroughStructuredData) {
+ // Make up a custom dictionary with "sys" pointing to the `sys` module.
+ const char *key_name = "addr";
+ const uint64_t value = 0xf000000000000000ull;
+ PythonDictionary python_dict(PyInitialValue::Empty);
+ PythonInteger python_ull_value(PyRefType::Owned,
+ PyLong_FromUnsignedLongLong(value));
+ python_dict.SetItemForKey(PythonString(key_name), python_ull_value);
+ StructuredData::ObjectSP structured_data_sp =
+ python_dict.CreateStructuredObject();
+ EXPECT_TRUE((bool)structured_data_sp);
+ if (structured_data_sp) {
+ StructuredData::Dictionary *structured_dict_ptr =
+ structured_data_sp->GetAsDictionary();
+ EXPECT_TRUE(structured_dict_ptr != nullptr);
+ if (structured_dict_ptr) {
+ StructuredData::ObjectSP structured_addr_value_sp =
+ structured_dict_ptr->GetValueForKey(key_name);
+ EXPECT_TRUE((bool)structured_addr_value_sp);
+ const uint64_t extracted_value =
+ structured_addr_value_sp->GetIntegerValue(123);
+ EXPECT_TRUE(extracted_value == value);
}
+ }
}
More information about the lldb-commits
mailing list