diff options
Diffstat (limited to 'lldb/unittests')
35 files changed, 3877 insertions, 3997 deletions
diff --git a/lldb/unittests/Core/BroadcasterTest.cpp b/lldb/unittests/Core/BroadcasterTest.cpp index 5650f710620..cc6f2417897 100644 --- a/lldb/unittests/Core/BroadcasterTest.cpp +++ b/lldb/unittests/Core/BroadcasterTest.cpp @@ -18,55 +18,56 @@ using namespace lldb; using namespace lldb_private; -TEST(BroadcasterTest, BroadcastEvent) -{ - EventSP event_sp; - Broadcaster broadcaster(nullptr, "test-broadcaster"); +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()); + // 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()); + { + // 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()); - } - - // 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"); +TEST(BroadcasterTest, EventTypeHasListeners) { + EventSP event_sp; + Broadcaster broadcaster(nullptr, "test-broadcaster"); - const uint32_t event_mask = 1; - EXPECT_FALSE(broadcaster.EventTypeHasListeners(event_mask)); + 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)); - } + { + 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)); } diff --git a/lldb/unittests/Core/DataExtractorTest.cpp b/lldb/unittests/Core/DataExtractorTest.cpp index 22438e59bea..d474e21dc0c 100644 --- a/lldb/unittests/Core/DataExtractorTest.cpp +++ b/lldb/unittests/Core/DataExtractorTest.cpp @@ -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); +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 + 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 + 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)); } diff --git a/lldb/unittests/Core/ScalarTest.cpp b/lldb/unittests/Core/ScalarTest.cpp index adff5b0ce8e..b79854f97ae 100644 --- a/lldb/unittests/Core/ScalarTest.cpp +++ b/lldb/unittests/Core/ScalarTest.cpp @@ -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, 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, 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, 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; +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))); + 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))); + 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(); +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())); +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("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("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())); + 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())); } diff --git a/lldb/unittests/Editline/EditlineTest.cpp b/lldb/unittests/Editline/EditlineTest.cpp index e2552ffdd3b..55dae525ddc 100644 --- a/lldb/unittests/Editline/EditlineTest.cpp +++ b/lldb/unittests/Editline/EditlineTest.cpp @@ -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; + std::unique_ptr<lldb_private::Editline> _editline_sp; - lldb_utility::PseudoTerminal _pty; - int _pty_master_fd; - int _pty_slave_fd; + lldb_utility::PseudoTerminal _pty; + int _pty_master_fd; + int _pty_slave_fd; - std::unique_ptr<FilePointer> _el_slave_file; + std::unique_ptr<FilePointer> _el_slave_file; }; -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(); +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); +} - _el_slave_file.reset (new FilePointer (fdopen (_pty_slave_fd, "rw"))); - EXPECT_FALSE (nullptr == *_el_slave_file); - if (*_el_slave_file == nullptr) - return; +void EditlineAdapter::CloseInput() { + if (_el_slave_file != nullptr) + _el_slave_file.reset(nullptr); +} - // 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 ("> "); +bool EditlineAdapter::SendLine(const std::string &line) { + // Ensure we're valid before proceeding. + if (!IsValid()) + return false; - // Hookup our input complete callback. - _editline_sp->SetIsInputCompleteCallback(IsInputComplete, this); -} + // 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)); -void -EditlineAdapter::CloseInput () -{ - if (_el_slave_file != nullptr) - _el_slave_file.reset (nullptr); -} + const char *eoln = "\n"; + const size_t eoln_length = strlen(eoln); + input_bytes_written = + ::write(_pty_master_fd, eoln, eoln_length * sizeof(char)); -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); + 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::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::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::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 TearDown() - { - _el_adapter.CloseInput(); - if (_sp_output_thread) - _sp_output_thread->join(); - } - - EditlineAdapter &GetEditlineAdapter() { return _el_adapter; } + 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(); + } + + 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)); +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); + // 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); + 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, 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 diff --git a/lldb/unittests/Expression/GoParserTest.cpp b/lldb/unittests/Expression/GoParserTest.cpp index 76483979f35..de489e43ef2 100644 --- a/lldb/unittests/Expression/GoParserTest.cpp +++ b/lldb/unittests/Expression/GoParserTest.cpp @@ -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); } - const std::string - str() const - { - return m_stream.str(); + void operator()(GoASTNode *n) { + if (n == nullptr) { + m_stream << "nil "; + return; } - std::stringstream m_stream; + 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; }; -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, 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 αβ ) ) ", "αβ"); +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"); + 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, 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, 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, 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, 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, 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, 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, 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)"); } diff --git a/lldb/unittests/Host/FileSpecTest.cpp b/lldb/unittests/Host/FileSpecTest.cpp index 522f4bc69ea..765dd9e0b5b 100644 --- a/lldb/unittests/Host/FileSpecTest.cpp +++ b/lldb/unittests/Host/FileSpecTest.cpp @@ -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)); } diff --git a/lldb/unittests/Host/SocketAddressTest.cpp b/lldb/unittests/Host/SocketAddressTest.cpp index 6b27e04ce70..3c18137ac06 100644 --- a/lldb/unittests/Host/SocketAddressTest.cpp +++ b/lldb/unittests/Host/SocketAddressTest.cpp @@ -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 ()); +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.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 ()); + 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}; -#endif + 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 diff --git a/lldb/unittests/Host/SocketTest.cpp b/lldb/unittests/Host/SocketTest.cpp index e3e52274476..b7ecf190b59 100644 --- a/lldb/unittests/Host/SocketTest.cpp +++ b/lldb/unittests/Host/SocketTest.cpp @@ -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()); - - listen_socket_up.reset(); - } -}; - -TEST_F (SocketTest, DecodeHostAndPort) -{ - std::string host_str; - std::string port_str; - int32_t port; + } + +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; - 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); + 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()); + + 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()); } #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; +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); - 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); + 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()); + EXPECT_TRUE(error.Success()); + EXPECT_TRUE(a_up->IsValid()); + EXPECT_TRUE(b_up->IsValid()); } diff --git a/lldb/unittests/Host/SymbolsTest.cpp b/lldb/unittests/Host/SymbolsTest.cpp index cb59b2c5653..ba100bdb507 100644 --- a/lldb/unittests/Host/SymbolsTest.cpp +++ b/lldb/unittests/Host/SymbolsTest.cpp @@ -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()); } diff --git a/lldb/unittests/Interpreter/TestArgs.cpp b/lldb/unittests/Interpreter/TestArgs.cpp index e2cf1c4d4a0..a14b8428aef 100644 --- a/lldb/unittests/Interpreter/TestArgs.cpp +++ b/lldb/unittests/Interpreter/TestArgs.cpp @@ -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, 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, 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, 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, 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, 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, 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"); } diff --git a/lldb/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp b/lldb/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp index 8b3cd50bbbf..26de31d52a3 100644 --- a/lldb/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp +++ b/lldb/unittests/Language/CPlusPlus/CPlusPlusLanguageTest.cpp @@ -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()); + } } diff --git a/lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp b/lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp index 6b56e5c506e..60397943a0e 100644 --- a/lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp +++ b/lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp @@ -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 -{ -}; - -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()); +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, 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()); } diff --git a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp index 0b1f60d33d0..d74ac66e15d 100644 --- a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp +++ b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp @@ -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_gdb_remote; 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 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 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; +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); }); + 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); + Handle_QThreadSuffixSupported(server, true); - HandlePacket(server, "P4=" + one_register_hex + ";thread:0047;", "OK"); - ASSERT_TRUE(write_result.get()); + 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); }); + 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()); + 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, 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, 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, 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, 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()); } diff --git a/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp b/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp index 3aee52e5332..58cc9f50586 100644 --- a/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp +++ b/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.cpp @@ -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 -{ +namespace lldb_private { +namespace process_gdb_remote { -void -GDBRemoteTest::SetUpTestCase() -{ +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()); +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); - }); + 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()); + 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); + 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)); + client.SetConnection(conn_ap.release()); + ASSERT_TRUE(accept_error.get().Success()); + server.SetConnection(new ConnectionFileDescriptor(accept_socket)); } } // namespace process_gdb_remote diff --git a/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.h b/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.h index 6ceeccfaf81..2aad2ae4972 100644 --- a/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.h +++ b/lldb/unittests/Process/gdb-remote/GDBRemoteTestUtils.h @@ -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); - -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; +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); + } + + using GDBRemoteCommunicationServer::SendOKResponse; + using GDBRemoteCommunicationServer::SendUnimplementedResponse; }; } // namespace process_gdb_remote diff --git a/lldb/unittests/Process/minidump/Inputs/linux-x86_64.cpp b/lldb/unittests/Process/minidump/Inputs/linux-x86_64.cpp index 9974a50310f..827fe67b503 100644 --- a/lldb/unittests/Process/minidump/Inputs/linux-x86_64.cpp +++ b/lldb/unittests/Process/minidump/Inputs/linux-x86_64.cpp @@ -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; } diff --git a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp index 753d631f747..3c273fb4a8e 100644 --- a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp +++ b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp @@ -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); - } - - llvm::SmallString<128> inputs_folder; - std::unique_ptr<MinidumpParser> parser; + 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; }; -TEST_F(MinidumpParserTest, GetThreads) -{ - SetUpData("linux-x86_64.dmp"); - llvm::Optional<std::vector<const MinidumpThread *>> thread_list; +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()); + 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 } diff --git a/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp b/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp index efd169e686d..590b143ec7a 100644 --- a/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp +++ b/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp @@ -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); - - EXPECT_EQ(PyObjectType::Integer, python_int.GetObjectType()); - EXPECT_EQ(12, python_int.GetInteger()); + // 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()); #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 `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()); + // 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 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); +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())); + 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()); +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())); + 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. +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); - - EXPECT_EQ(PyObjectType::String, python_string.GetObjectType()); - EXPECT_STREQ(test_string, python_string.GetString().data()); + // 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()); #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); + + tuple.SetItemAtIndex(0, int_value); + tuple.SetItemAtIndex(1, string_value); + tuple.SetItemAtIndex(2, none_value); - PythonInteger int_value(1); - PythonString string_value("Test"); - PythonObject none_value(PyRefType::Borrowed, Py_None); + 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()); +} - tuple.SetItemAtIndex(0, int_value); - tuple.SetItemAtIndex(1, string_value); - tuple.SetItemAtIndex(2, none_value); +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, 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, 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()); - 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, TestPythonTupleToStructuredList) { + PythonInteger int_value(1); + PythonString string_value("Test"); - PythonTuple tuple{ int_value.get(), string_value.get(), none_value.get() }; - EXPECT_EQ(3U, tuple.GetSize()); + PythonTuple tuple{int_value.get(), string_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()); + 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, TestPythonTupleToStructuredList) -{ - PythonInteger int_value(1); - PythonString string_value("Test"); +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]; + + 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); + + 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())); - PythonTuple tuple{ int_value.get(), string_value.get() }; + PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get()); + PythonString chk_str(PyRefType::Borrowed, chk_value2.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()); + EXPECT_EQ(value_0, chk_int.GetInteger()); + EXPECT_STREQ(value_1, chk_str.GetString().str().c_str()); } -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, TestPythonDictionaryManipulation) { + // Test that manipulation of a dictionary behaves correctly when wrapped + // by a PythonDictionary. + static const unsigned dict_entries = 2; - PythonObject py_keys[dict_entries]; - PythonObject py_values[dict_entries]; + 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"; - 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)); + PythonString keys[dict_entries]; + PythonObject values[dict_entries]; - PyObject *py_dict = PyDict_New(); - EXPECT_TRUE(PythonDictionary::Check(py_dict)); - PythonDictionary dict(PyRefType::Owned, py_dict); + keys[0].Reset(PythonString(key_0)); + keys[1].Reset(PythonString(key_1)); + values[0].Reset(PythonInteger(value_0)); + values[1].Reset(PythonString(value_1)); - 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()); + PythonDictionary dict(PyInitialValue::Empty); + for (int i = 0; i < 2; ++i) + dict.SetItemForKey(keys[i], values[i]); - // 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())); + EXPECT_EQ(dict_entries, dict.GetSize()); - PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get()); - PythonString chk_str(PyRefType::Borrowed, 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())); - EXPECT_EQ(value_0, chk_int.GetInteger()); - EXPECT_STREQ(value_1, chk_str.GetString().str().c_str()); + 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()); } -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, TestPythonDictionaryToStructuredDictionary) { + static const char *const string_key0 = "String Key 0"; + static const char *const string_key1 = "String Key 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"; + static const char *const string_value0 = "String Value 0"; + static const long int_value1 = 7; - PythonString keys[dict_entries]; - PythonObject values[dict_entries]; + 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()); - keys[0].Reset(PythonString(key_0)); - keys[1].Reset(PythonString(key_1)); - values[0].Reset(PythonInteger(value_0)); - values[1].Reset(PythonString(value_1)); + 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(); + + 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); + + EXPECT_TRUE(PythonCallable::Check(sys_exc_info.get())); + EXPECT_FALSE(PythonCallable::Check(none.get())); +} - PythonDictionary dict(PyInitialValue::Empty); - for (int i = 0; i < 2; ++i) - dict.SetItemForKey(keys[i], values[i]); +TEST_F(PythonDataObjectsTest, TestPythonCallableInvoke) { + auto list = m_builtins_module.ResolveName("list").AsType<PythonCallable>(); + PythonInteger one(1); + PythonString two("two"); + PythonTuple three = {one, two}; - EXPECT_EQ(dict_entries, dict.GetSize()); + PythonTuple tuple_to_convert = {one, two, three}; + PythonObject result = list({tuple_to_convert}); - // 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())); + 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()); +} - 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()); -} - -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; - - 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()); - - 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(); - - 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); - - 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 }; - - 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()); -} - -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")); - - 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, 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()); +} + +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); } + } } diff --git a/lldb/unittests/ScriptInterpreter/Python/PythonExceptionStateTests.cpp b/lldb/unittests/ScriptInterpreter/Python/PythonExceptionStateTests.cpp index ddac220c795..523a07ee807 100644 --- a/lldb/unittests/ScriptInterpreter/Python/PythonExceptionStateTests.cpp +++ b/lldb/unittests/ScriptInterpreter/Python/PythonExceptionStateTests.cpp @@ -1,4 +1,5 @@ -//===-- PythonExceptionStateTest.cpp ------------------------------*- C++ -*-===// +//===-- PythonExceptionStateTest.cpp ------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -9,166 +10,156 @@ #include "gtest/gtest.h" -#include "Plugins/ScriptInterpreter/Python/lldb-python.h" #include "Plugins/ScriptInterpreter/Python/PythonDataObjects.h" #include "Plugins/ScriptInterpreter/Python/PythonExceptionState.h" #include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h" +#include "Plugins/ScriptInterpreter/Python/lldb-python.h" #include "PythonTestSuite.h" using namespace lldb_private; -class PythonExceptionStateTest : public PythonTestSuite -{ - public: - protected: - void - RaiseException() - { - PyErr_SetString(PyExc_RuntimeError, "PythonExceptionStateTest test error"); - } +class PythonExceptionStateTest : public PythonTestSuite { +public: +protected: + void RaiseException() { + PyErr_SetString(PyExc_RuntimeError, "PythonExceptionStateTest test error"); + } }; -TEST_F(PythonExceptionStateTest, TestExceptionStateChecking) -{ - PyErr_Clear(); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); +TEST_F(PythonExceptionStateTest, TestExceptionStateChecking) { + PyErr_Clear(); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - RaiseException(); - EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); + RaiseException(); + EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - PyErr_Clear(); + PyErr_Clear(); } -TEST_F(PythonExceptionStateTest, TestAcquisitionSemantics) -{ - PyErr_Clear(); - PythonExceptionState no_error(false); - EXPECT_FALSE(no_error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - - PyErr_Clear(); - RaiseException(); - PythonExceptionState error(false); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error.Discard(); - - PyErr_Clear(); - RaiseException(); - error.Acquire(false); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - - PyErr_Clear(); +TEST_F(PythonExceptionStateTest, TestAcquisitionSemantics) { + PyErr_Clear(); + PythonExceptionState no_error(false); + EXPECT_FALSE(no_error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + + PyErr_Clear(); + RaiseException(); + PythonExceptionState error(false); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error.Discard(); + + PyErr_Clear(); + RaiseException(); + error.Acquire(false); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + + PyErr_Clear(); } -TEST_F(PythonExceptionStateTest, TestDiscardSemantics) -{ - PyErr_Clear(); +TEST_F(PythonExceptionStateTest, TestDiscardSemantics) { + PyErr_Clear(); - // Test that discarding an exception does not restore the exception - // state even when auto-restore==true is set - RaiseException(); - PythonExceptionState error(true); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + // Test that discarding an exception does not restore the exception + // state even when auto-restore==true is set + RaiseException(); + PythonExceptionState error(true); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error.Discard(); - EXPECT_FALSE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error.Discard(); + EXPECT_FALSE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); } -TEST_F(PythonExceptionStateTest, TestResetSemantics) -{ - PyErr_Clear(); - - // Resetting when auto-restore is true should restore. - RaiseException(); - PythonExceptionState error(true); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error.Reset(); - EXPECT_FALSE(error.IsError()); - EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); +TEST_F(PythonExceptionStateTest, TestResetSemantics) { + PyErr_Clear(); + + // Resetting when auto-restore is true should restore. + RaiseException(); + PythonExceptionState error(true); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error.Reset(); + EXPECT_FALSE(error.IsError()); + EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); + + PyErr_Clear(); + + // Resetting when auto-restore is false should discard. + RaiseException(); + PythonExceptionState error2(false); + EXPECT_TRUE(error2.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error2.Reset(); + EXPECT_FALSE(error2.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + + PyErr_Clear(); +} - PyErr_Clear(); +TEST_F(PythonExceptionStateTest, TestManualRestoreSemantics) { + PyErr_Clear(); + RaiseException(); + PythonExceptionState error(false); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - // Resetting when auto-restore is false should discard. - RaiseException(); - PythonExceptionState error2(false); - EXPECT_TRUE(error2.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error2.Reset(); - EXPECT_FALSE(error2.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error.Restore(); + EXPECT_FALSE(error.IsError()); + EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - PyErr_Clear(); + PyErr_Clear(); } -TEST_F(PythonExceptionStateTest, TestManualRestoreSemantics) -{ - PyErr_Clear(); +TEST_F(PythonExceptionStateTest, TestAutoRestoreSemantics) { + PyErr_Clear(); + // Test that using the auto-restore flag correctly restores the exception + // state on destruction, and not using the auto-restore flag correctly + // does NOT restore the state on destruction. + { RaiseException(); PythonExceptionState error(false); EXPECT_TRUE(error.IsError()); EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + } + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error.Restore(); - EXPECT_FALSE(error.IsError()); - EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - - PyErr_Clear(); -} - -TEST_F(PythonExceptionStateTest, TestAutoRestoreSemantics) -{ - PyErr_Clear(); - // Test that using the auto-restore flag correctly restores the exception - // state on destruction, and not using the auto-restore flag correctly - // does NOT restore the state on destruction. - { - RaiseException(); - PythonExceptionState error(false); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - } + PyErr_Clear(); + { + RaiseException(); + PythonExceptionState error(true); + EXPECT_TRUE(error.IsError()); EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + } + EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - PyErr_Clear(); - { - RaiseException(); - PythonExceptionState error(true); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - } - EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - - PyErr_Clear(); + PyErr_Clear(); } -TEST_F(PythonExceptionStateTest, TestAutoRestoreChanged) -{ - // Test that if we re-acquire with different auto-restore semantics, - // that the new semantics are respected. - PyErr_Clear(); +TEST_F(PythonExceptionStateTest, TestAutoRestoreChanged) { + // Test that if we re-acquire with different auto-restore semantics, + // that the new semantics are respected. + PyErr_Clear(); - RaiseException(); - PythonExceptionState error(false); - EXPECT_TRUE(error.IsError()); + RaiseException(); + PythonExceptionState error(false); + EXPECT_TRUE(error.IsError()); - error.Reset(); - EXPECT_FALSE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + error.Reset(); + EXPECT_FALSE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - RaiseException(); - error.Acquire(true); - EXPECT_TRUE(error.IsError()); - EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); + RaiseException(); + error.Acquire(true); + EXPECT_TRUE(error.IsError()); + EXPECT_FALSE(PythonExceptionState::HasErrorOccurred()); - error.Reset(); - EXPECT_FALSE(error.IsError()); - EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); + error.Reset(); + EXPECT_FALSE(error.IsError()); + EXPECT_TRUE(PythonExceptionState::HasErrorOccurred()); - PyErr_Clear(); + PyErr_Clear(); } diff --git a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp index 0f75bf28131..608f3ee45e5 100644 --- a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp +++ b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp @@ -7,37 +7,33 @@ // //===----------------------------------------------------------------------===// -#include "gtest/gtest.h" #include "Plugins/ScriptInterpreter/Python/lldb-python.h" +#include "gtest/gtest.h" -#include "lldb/Host/HostInfo.h" #include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h" +#include "lldb/Host/HostInfo.h" #include "PythonTestSuite.h" using namespace lldb_private; -void -PythonTestSuite::SetUp() -{ - HostInfoBase::Initialize(); - // ScriptInterpreterPython::Initialize() depends on HostInfo being - // initializedso it can compute the python directory etc. - ScriptInterpreterPython::Initialize(); - ScriptInterpreterPython::InitializePrivate(); - - // Although we don't care about concurrency for the purposes of running - // this test suite, Python requires the GIL to be locked even for - // deallocating memory, which can happen when you call Py_DECREF or - // Py_INCREF. So acquire the GIL for the entire duration of this - // test suite. - m_gil_state = PyGILState_Ensure(); +void PythonTestSuite::SetUp() { + HostInfoBase::Initialize(); + // ScriptInterpreterPython::Initialize() depends on HostInfo being + // initializedso it can compute the python directory etc. + ScriptInterpreterPython::Initialize(); + ScriptInterpreterPython::InitializePrivate(); + + // Although we don't care about concurrency for the purposes of running + // this test suite, Python requires the GIL to be locked even for + // deallocating memory, which can happen when you call Py_DECREF or + // Py_INCREF. So acquire the GIL for the entire duration of this + // test suite. + m_gil_state = PyGILState_Ensure(); } -void -PythonTestSuite::TearDown() -{ - PyGILState_Release(m_gil_state); +void PythonTestSuite::TearDown() { + PyGILState_Release(m_gil_state); - ScriptInterpreterPython::Terminate(); + ScriptInterpreterPython::Terminate(); } diff --git a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.h b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.h index 461fc1d5676..ad0478875be 100644 --- a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.h +++ b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.h @@ -11,16 +11,12 @@ using namespace lldb_private; -class PythonTestSuite : public testing::Test -{ +class PythonTestSuite : public testing::Test { public: - void - SetUp() override; + void SetUp() override; - void - TearDown() override; + void TearDown() override; private: - PyGILState_STATE m_gil_state; + PyGILState_STATE m_gil_state; }; - diff --git a/lldb/unittests/Symbol/TestClangASTContext.cpp b/lldb/unittests/Symbol/TestClangASTContext.cpp index 3f166ab9cc7..e1bd3a63fd5 100644 --- a/lldb/unittests/Symbol/TestClangASTContext.cpp +++ b/lldb/unittests/Symbol/TestClangASTContext.cpp @@ -1,4 +1,5 @@ -//===-- TestClangASTContext.cpp ---------------------------------------*- C++ -*-===// +//===-- TestClangASTContext.cpp ---------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure @@ -20,296 +21,358 @@ using namespace clang; using namespace lldb; using namespace lldb_private; -class TestClangASTContext : public testing::Test -{ +class TestClangASTContext : public testing::Test { public: - static void - SetUpTestCase() - { - HostInfo::Initialize(); - } - - static void - TearDownTestCase() - { - HostInfo::Terminate(); - } - - virtual void - SetUp() override - { - std::string triple = HostInfo::GetTargetTriple(); - m_ast.reset(new ClangASTContext(triple.c_str())); - } - - virtual void - TearDown() override - { - m_ast.reset(); - } + static void SetUpTestCase() { HostInfo::Initialize(); } + + static void TearDownTestCase() { HostInfo::Terminate(); } + + virtual void SetUp() override { + std::string triple = HostInfo::GetTargetTriple(); + m_ast.reset(new ClangASTContext(triple.c_str())); + } + + virtual void TearDown() override { m_ast.reset(); } protected: - std::unique_ptr<ClangASTContext> m_ast; - - QualType - GetBasicQualType(BasicType type) const - { - return ClangUtil::GetQualType(m_ast->GetBasicTypeFromAST(type)); - } - - QualType - GetBasicQualType(const char *name) const - { - return ClangUtil::GetQualType(m_ast->GetBuiltinTypeByName(ConstString(name))); - } + std::unique_ptr<ClangASTContext> m_ast; + + QualType GetBasicQualType(BasicType type) const { + return ClangUtil::GetQualType(m_ast->GetBasicTypeFromAST(type)); + } + + QualType GetBasicQualType(const char *name) const { + return ClangUtil::GetQualType( + m_ast->GetBuiltinTypeByName(ConstString(name))); + } }; -TEST_F(TestClangASTContext, TestGetBasicTypeFromEnum) -{ - clang::ASTContext *context = m_ast->getASTContext(); - - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeBool), context->BoolTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeChar), context->CharTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeChar16), context->Char16Ty)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeChar32), context->Char32Ty)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeDouble), context->DoubleTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeDoubleComplex), context->DoubleComplexTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeFloat), context->FloatTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeFloatComplex), context->FloatComplexTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeHalf), context->HalfTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeInt), context->IntTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeInt128), context->Int128Ty)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLong), context->LongTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLongDouble), context->LongDoubleTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLongDoubleComplex), context->LongDoubleComplexTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLongLong), context->LongLongTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeNullPtr), context->NullPtrTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCClass), context->getObjCClassType())); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCID), context->getObjCIdType())); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCSel), context->getObjCSelType())); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeShort), context->ShortTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeSignedChar), context->SignedCharTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedChar), context->UnsignedCharTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedInt), context->UnsignedIntTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedInt128), context->UnsignedInt128Ty)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedLong), context->UnsignedLongTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedLongLong), context->UnsignedLongLongTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedShort), context->UnsignedShortTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeVoid), context->VoidTy)); - EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeWChar), context->WCharTy)); +TEST_F(TestClangASTContext, TestGetBasicTypeFromEnum) { + clang::ASTContext *context = m_ast->getASTContext(); + + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeBool), context->BoolTy)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeChar), context->CharTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeChar16), + context->Char16Ty)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeChar32), + context->Char32Ty)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeDouble), + context->DoubleTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeDoubleComplex), + context->DoubleComplexTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeFloat), + context->FloatTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeFloatComplex), + context->FloatComplexTy)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeHalf), context->HalfTy)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeInt), context->IntTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeInt128), + context->Int128Ty)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeLong), context->LongTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLongDouble), + context->LongDoubleTy)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeLongDoubleComplex), + context->LongDoubleComplexTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeLongLong), + context->LongLongTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeNullPtr), + context->NullPtrTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCClass), + context->getObjCClassType())); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCID), + context->getObjCIdType())); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeObjCSel), + context->getObjCSelType())); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeShort), + context->ShortTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeSignedChar), + context->SignedCharTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedChar), + context->UnsignedCharTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedInt), + context->UnsignedIntTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedInt128), + context->UnsignedInt128Ty)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedLong), + context->UnsignedLongTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedLongLong), + context->UnsignedLongLongTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeUnsignedShort), + context->UnsignedShortTy)); + EXPECT_TRUE( + context->hasSameType(GetBasicQualType(eBasicTypeVoid), context->VoidTy)); + EXPECT_TRUE(context->hasSameType(GetBasicQualType(eBasicTypeWChar), + context->WCharTy)); } -TEST_F(TestClangASTContext, TestGetBasicTypeFromName) -{ - EXPECT_EQ(GetBasicQualType(eBasicTypeChar), GetBasicQualType("char")); - EXPECT_EQ(GetBasicQualType(eBasicTypeSignedChar), GetBasicQualType("signed char")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedChar), GetBasicQualType("unsigned char")); - EXPECT_EQ(GetBasicQualType(eBasicTypeWChar), GetBasicQualType("wchar_t")); - EXPECT_EQ(GetBasicQualType(eBasicTypeSignedWChar), GetBasicQualType("signed wchar_t")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedWChar), GetBasicQualType("unsigned wchar_t")); - EXPECT_EQ(GetBasicQualType(eBasicTypeShort), GetBasicQualType("short")); - EXPECT_EQ(GetBasicQualType(eBasicTypeShort), GetBasicQualType("short int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedShort), GetBasicQualType("unsigned short")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedShort), GetBasicQualType("unsigned short int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeInt), GetBasicQualType("int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeInt), GetBasicQualType("signed int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt), GetBasicQualType("unsigned int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt), GetBasicQualType("unsigned")); - EXPECT_EQ(GetBasicQualType(eBasicTypeLong), GetBasicQualType("long")); - EXPECT_EQ(GetBasicQualType(eBasicTypeLong), GetBasicQualType("long int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLong), GetBasicQualType("unsigned long")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLong), GetBasicQualType("unsigned long int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeLongLong), GetBasicQualType("long long")); - EXPECT_EQ(GetBasicQualType(eBasicTypeLongLong), GetBasicQualType("long long int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLongLong), GetBasicQualType("unsigned long long")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLongLong), GetBasicQualType("unsigned long long int")); - EXPECT_EQ(GetBasicQualType(eBasicTypeInt128), GetBasicQualType("__int128_t")); - EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt128), GetBasicQualType("__uint128_t")); - EXPECT_EQ(GetBasicQualType(eBasicTypeVoid), GetBasicQualType("void")); - EXPECT_EQ(GetBasicQualType(eBasicTypeBool), GetBasicQualType("bool")); - EXPECT_EQ(GetBasicQualType(eBasicTypeFloat), GetBasicQualType("float")); - EXPECT_EQ(GetBasicQualType(eBasicTypeDouble), GetBasicQualType("double")); - EXPECT_EQ(GetBasicQualType(eBasicTypeLongDouble), GetBasicQualType("long double")); - EXPECT_EQ(GetBasicQualType(eBasicTypeObjCID), GetBasicQualType("id")); - EXPECT_EQ(GetBasicQualType(eBasicTypeObjCSel), GetBasicQualType("SEL")); - EXPECT_EQ(GetBasicQualType(eBasicTypeNullPtr), GetBasicQualType("nullptr")); +TEST_F(TestClangASTContext, TestGetBasicTypeFromName) { + EXPECT_EQ(GetBasicQualType(eBasicTypeChar), GetBasicQualType("char")); + EXPECT_EQ(GetBasicQualType(eBasicTypeSignedChar), + GetBasicQualType("signed char")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedChar), + GetBasicQualType("unsigned char")); + EXPECT_EQ(GetBasicQualType(eBasicTypeWChar), GetBasicQualType("wchar_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeSignedWChar), + GetBasicQualType("signed wchar_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedWChar), + GetBasicQualType("unsigned wchar_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeShort), GetBasicQualType("short")); + EXPECT_EQ(GetBasicQualType(eBasicTypeShort), GetBasicQualType("short int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedShort), + GetBasicQualType("unsigned short")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedShort), + GetBasicQualType("unsigned short int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeInt), GetBasicQualType("int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeInt), GetBasicQualType("signed int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt), + GetBasicQualType("unsigned int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt), + GetBasicQualType("unsigned")); + EXPECT_EQ(GetBasicQualType(eBasicTypeLong), GetBasicQualType("long")); + EXPECT_EQ(GetBasicQualType(eBasicTypeLong), GetBasicQualType("long int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLong), + GetBasicQualType("unsigned long")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLong), + GetBasicQualType("unsigned long int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeLongLong), + GetBasicQualType("long long")); + EXPECT_EQ(GetBasicQualType(eBasicTypeLongLong), + GetBasicQualType("long long int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLongLong), + GetBasicQualType("unsigned long long")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedLongLong), + GetBasicQualType("unsigned long long int")); + EXPECT_EQ(GetBasicQualType(eBasicTypeInt128), GetBasicQualType("__int128_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeUnsignedInt128), + GetBasicQualType("__uint128_t")); + EXPECT_EQ(GetBasicQualType(eBasicTypeVoid), GetBasicQualType("void")); + EXPECT_EQ(GetBasicQualType(eBasicTypeBool), GetBasicQualType("bool")); + EXPECT_EQ(GetBasicQualType(eBasicTypeFloat), GetBasicQualType("float")); + EXPECT_EQ(GetBasicQualType(eBasicTypeDouble), GetBasicQualType("double")); + EXPECT_EQ(GetBasicQualType(eBasicTypeLongDouble), + GetBasicQualType("long double")); + EXPECT_EQ(GetBasicQualType(eBasicTypeObjCID), GetBasicQualType("id")); + EXPECT_EQ(GetBasicQualType(eBasicTypeObjCSel), GetBasicQualType("SEL")); + EXPECT_EQ(GetBasicQualType(eBasicTypeNullPtr), GetBasicQualType("nullptr")); } -void -VerifyEncodingAndBitSize(clang::ASTContext *context, lldb::Encoding encoding, int bit_size) -{ - CompilerType type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(context, encoding, bit_size); - EXPECT_TRUE(type.IsValid()); - - QualType qtype = ClangUtil::GetQualType(type); - EXPECT_FALSE(qtype.isNull()); - if (qtype.isNull()) - return; - - uint64_t actual_size = context->getTypeSize(qtype); - EXPECT_EQ(bit_size, actual_size); - - const clang::Type *type_ptr = qtype.getTypePtr(); - EXPECT_NE(nullptr, type_ptr); - if (!type_ptr) - return; - - EXPECT_TRUE(type_ptr->isBuiltinType()); - if (encoding == eEncodingSint) - EXPECT_TRUE(type_ptr->isSignedIntegerType()); - else if (encoding == eEncodingUint) - EXPECT_TRUE(type_ptr->isUnsignedIntegerType()); - else if (encoding == eEncodingIEEE754) - EXPECT_TRUE(type_ptr->isFloatingType()); +void VerifyEncodingAndBitSize(clang::ASTContext *context, + lldb::Encoding encoding, int bit_size) { + CompilerType type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize( + context, encoding, bit_size); + EXPECT_TRUE(type.IsValid()); + + QualType qtype = ClangUtil::GetQualType(type); + EXPECT_FALSE(qtype.isNull()); + if (qtype.isNull()) + return; + + uint64_t actual_size = context->getTypeSize(qtype); + EXPECT_EQ(bit_size, actual_size); + + const clang::Type *type_ptr = qtype.getTypePtr(); + EXPECT_NE(nullptr, type_ptr); + if (!type_ptr) + return; + + EXPECT_TRUE(type_ptr->isBuiltinType()); + if (encoding == eEncodingSint) + EXPECT_TRUE(type_ptr->isSignedIntegerType()); + else if (encoding == eEncodingUint) + EXPECT_TRUE(type_ptr->isUnsignedIntegerType()); + else if (encoding == eEncodingIEEE754) + EXPECT_TRUE(type_ptr->isFloatingType()); } -TEST_F(TestClangASTContext, TestBuiltinTypeForEncodingAndBitSize) -{ - clang::ASTContext *context = m_ast->getASTContext(); - - // Make sure we can get types of every possible size in every possible encoding. - // We can't make any guarantee about which specific type we get, because the standard - // isn't that specific. We only need to make sure the compiler hands us some type that - // is both a builtin type and matches the requested bit size. - VerifyEncodingAndBitSize(context, eEncodingSint, 8); - VerifyEncodingAndBitSize(context, eEncodingSint, 16); - VerifyEncodingAndBitSize(context, eEncodingSint, 32); - VerifyEncodingAndBitSize(context, eEncodingSint, 64); - VerifyEncodingAndBitSize(context, eEncodingSint, 128); - - VerifyEncodingAndBitSize(context, eEncodingUint, 8); - VerifyEncodingAndBitSize(context, eEncodingUint, 16); - VerifyEncodingAndBitSize(context, eEncodingUint, 32); - VerifyEncodingAndBitSize(context, eEncodingUint, 64); - VerifyEncodingAndBitSize(context, eEncodingUint, 128); - - VerifyEncodingAndBitSize(context, eEncodingIEEE754, 32); - VerifyEncodingAndBitSize(context, eEncodingIEEE754, 64); +TEST_F(TestClangASTContext, TestBuiltinTypeForEncodingAndBitSize) { + clang::ASTContext *context = m_ast->getASTContext(); + + // Make sure we can get types of every possible size in every possible + // encoding. + // We can't make any guarantee about which specific type we get, because the + // standard + // isn't that specific. We only need to make sure the compiler hands us some + // type that + // is both a builtin type and matches the requested bit size. + VerifyEncodingAndBitSize(context, eEncodingSint, 8); + VerifyEncodingAndBitSize(context, eEncodingSint, 16); + VerifyEncodingAndBitSize(context, eEncodingSint, 32); + VerifyEncodingAndBitSize(context, eEncodingSint, 64); + VerifyEncodingAndBitSize(context, eEncodingSint, 128); + + VerifyEncodingAndBitSize(context, eEncodingUint, 8); + VerifyEncodingAndBitSize(context, eEncodingUint, 16); + VerifyEncodingAndBitSize(context, eEncodingUint, 32); + VerifyEncodingAndBitSize(context, eEncodingUint, 64); + VerifyEncodingAndBitSize(context, eEncodingUint, 128); + + VerifyEncodingAndBitSize(context, eEncodingIEEE754, 32); + VerifyEncodingAndBitSize(context, eEncodingIEEE754, 64); } -TEST_F(TestClangASTContext, TestIsClangType) -{ - clang::ASTContext *context = m_ast->getASTContext(); - lldb::opaque_compiler_type_t bool_ctype = ClangASTContext::GetOpaqueCompilerType(context, lldb::eBasicTypeBool); - CompilerType bool_type(m_ast.get(), bool_ctype); - CompilerType record_type = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "FooRecord", clang::TTK_Struct, - lldb::eLanguageTypeC_plus_plus, nullptr); - // Clang builtin type and record type should pass - EXPECT_TRUE(ClangUtil::IsClangType(bool_type)); - EXPECT_TRUE(ClangUtil::IsClangType(record_type)); - - // Default constructed type should fail - EXPECT_FALSE(ClangUtil::IsClangType(CompilerType())); - - // Go type should fail - GoASTContext go_ast; - CompilerType go_type(&go_ast, bool_ctype); - EXPECT_FALSE(ClangUtil::IsClangType(go_type)); +TEST_F(TestClangASTContext, TestIsClangType) { + clang::ASTContext *context = m_ast->getASTContext(); + lldb::opaque_compiler_type_t bool_ctype = + ClangASTContext::GetOpaqueCompilerType(context, lldb::eBasicTypeBool); + CompilerType bool_type(m_ast.get(), bool_ctype); + CompilerType record_type = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "FooRecord", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + // Clang builtin type and record type should pass + EXPECT_TRUE(ClangUtil::IsClangType(bool_type)); + EXPECT_TRUE(ClangUtil::IsClangType(record_type)); + + // Default constructed type should fail + EXPECT_FALSE(ClangUtil::IsClangType(CompilerType())); + + // Go type should fail + GoASTContext go_ast; + CompilerType go_type(&go_ast, bool_ctype); + EXPECT_FALSE(ClangUtil::IsClangType(go_type)); } -TEST_F(TestClangASTContext, TestRemoveFastQualifiers) -{ - CompilerType record_type = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "FooRecord", clang::TTK_Struct, - lldb::eLanguageTypeC_plus_plus, nullptr); - QualType qt; - - qt = ClangUtil::GetQualType(record_type); - EXPECT_EQ(0, qt.getLocalFastQualifiers()); - record_type = record_type.AddConstModifier(); - record_type = record_type.AddVolatileModifier(); - record_type = record_type.AddRestrictModifier(); - qt = ClangUtil::GetQualType(record_type); - EXPECT_NE(0, qt.getLocalFastQualifiers()); - record_type = ClangUtil::RemoveFastQualifiers(record_type); - qt = ClangUtil::GetQualType(record_type); - EXPECT_EQ(0, qt.getLocalFastQualifiers()); +TEST_F(TestClangASTContext, TestRemoveFastQualifiers) { + CompilerType record_type = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "FooRecord", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + QualType qt; + + qt = ClangUtil::GetQualType(record_type); + EXPECT_EQ(0, qt.getLocalFastQualifiers()); + record_type = record_type.AddConstModifier(); + record_type = record_type.AddVolatileModifier(); + record_type = record_type.AddRestrictModifier(); + qt = ClangUtil::GetQualType(record_type); + EXPECT_NE(0, qt.getLocalFastQualifiers()); + record_type = ClangUtil::RemoveFastQualifiers(record_type); + qt = ClangUtil::GetQualType(record_type); + EXPECT_EQ(0, qt.getLocalFastQualifiers()); } -TEST_F(TestClangASTContext, TestConvertAccessTypeToAccessSpecifier) -{ - EXPECT_EQ(AS_none, ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessNone)); - EXPECT_EQ(AS_none, ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessPackage)); - EXPECT_EQ(AS_public, ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessPublic)); - EXPECT_EQ(AS_private, ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessPrivate)); - EXPECT_EQ(AS_protected, ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessProtected)); +TEST_F(TestClangASTContext, TestConvertAccessTypeToAccessSpecifier) { + EXPECT_EQ(AS_none, + ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessNone)); + EXPECT_EQ(AS_none, ClangASTContext::ConvertAccessTypeToAccessSpecifier( + eAccessPackage)); + EXPECT_EQ(AS_public, + ClangASTContext::ConvertAccessTypeToAccessSpecifier(eAccessPublic)); + EXPECT_EQ(AS_private, ClangASTContext::ConvertAccessTypeToAccessSpecifier( + eAccessPrivate)); + EXPECT_EQ(AS_protected, ClangASTContext::ConvertAccessTypeToAccessSpecifier( + eAccessProtected)); } -TEST_F(TestClangASTContext, TestUnifyAccessSpecifiers) -{ - // Unifying two of the same type should return the same type - EXPECT_EQ(AS_public, ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_public)); - EXPECT_EQ(AS_private, ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_private)); - EXPECT_EQ(AS_protected, ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_protected)); - - // Otherwise the result should be the strictest of the two. - EXPECT_EQ(AS_private, ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_public)); - EXPECT_EQ(AS_private, ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_protected)); - EXPECT_EQ(AS_private, ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_private)); - EXPECT_EQ(AS_private, ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_private)); - EXPECT_EQ(AS_protected, ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_public)); - EXPECT_EQ(AS_protected, ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_protected)); - - // None is stricter than everything (by convention) - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_public)); - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_protected)); - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_private)); - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_none)); - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_none)); - EXPECT_EQ(AS_none, ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_none)); +TEST_F(TestClangASTContext, TestUnifyAccessSpecifiers) { + // Unifying two of the same type should return the same type + EXPECT_EQ(AS_public, + ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_public)); + EXPECT_EQ(AS_private, + ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_private)); + EXPECT_EQ(AS_protected, + ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_protected)); + + // Otherwise the result should be the strictest of the two. + EXPECT_EQ(AS_private, + ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_public)); + EXPECT_EQ(AS_private, + ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_protected)); + EXPECT_EQ(AS_private, + ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_private)); + EXPECT_EQ(AS_private, + ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_private)); + EXPECT_EQ(AS_protected, + ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_public)); + EXPECT_EQ(AS_protected, + ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_protected)); + + // None is stricter than everything (by convention) + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_public)); + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_protected)); + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_none, AS_private)); + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_public, AS_none)); + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_protected, AS_none)); + EXPECT_EQ(AS_none, + ClangASTContext::UnifyAccessSpecifiers(AS_private, AS_none)); } -TEST_F(TestClangASTContext, TestRecordHasFields) -{ - CompilerType int_type = ClangASTContext::GetBasicType(m_ast->getASTContext(), eBasicTypeInt); - - // Test that a record with no fields returns false - CompilerType empty_base = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "EmptyBase", clang::TTK_Struct, - lldb::eLanguageTypeC_plus_plus, nullptr); - ClangASTContext::StartTagDeclarationDefinition(empty_base); - ClangASTContext::CompleteTagDeclarationDefinition(empty_base); - - RecordDecl *empty_base_decl = ClangASTContext::GetAsRecordDecl(empty_base); - EXPECT_NE(nullptr, empty_base_decl); - EXPECT_FALSE(ClangASTContext::RecordHasFields(empty_base_decl)); - - // Test that a record with direct fields returns true - CompilerType non_empty_base = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "NonEmptyBase", - clang::TTK_Struct, lldb::eLanguageTypeC_plus_plus, nullptr); - ClangASTContext::StartTagDeclarationDefinition(non_empty_base); - FieldDecl *non_empty_base_field_decl = - m_ast->AddFieldToRecordType(non_empty_base, "MyField", int_type, eAccessPublic, 0); - ClangASTContext::CompleteTagDeclarationDefinition(non_empty_base); - RecordDecl *non_empty_base_decl = ClangASTContext::GetAsRecordDecl(non_empty_base); - EXPECT_NE(nullptr, non_empty_base_decl); - EXPECT_NE(nullptr, non_empty_base_field_decl); - EXPECT_TRUE(ClangASTContext::RecordHasFields(non_empty_base_decl)); - - // Test that a record with no direct fields, but fields in a base returns true - CompilerType empty_derived = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "EmptyDerived", - clang::TTK_Struct, lldb::eLanguageTypeC_plus_plus, nullptr); - ClangASTContext::StartTagDeclarationDefinition(empty_derived); - CXXBaseSpecifier *non_empty_base_spec = - m_ast->CreateBaseClassSpecifier(non_empty_base.GetOpaqueQualType(), lldb::eAccessPublic, false, false); - bool result = m_ast->SetBaseClassesForClassType(empty_derived.GetOpaqueQualType(), &non_empty_base_spec, 1); - ClangASTContext::CompleteTagDeclarationDefinition(empty_derived); - EXPECT_TRUE(result); - CXXRecordDecl *empty_derived_non_empty_base_cxx_decl = m_ast->GetAsCXXRecordDecl(empty_derived.GetOpaqueQualType()); - RecordDecl *empty_derived_non_empty_base_decl = ClangASTContext::GetAsRecordDecl(empty_derived); - EXPECT_EQ(1, ClangASTContext::GetNumBaseClasses(empty_derived_non_empty_base_cxx_decl, false)); - EXPECT_TRUE(ClangASTContext::RecordHasFields(empty_derived_non_empty_base_decl)); - - // Test that a record with no direct fields, but fields in a virtual base returns true - CompilerType empty_derived2 = m_ast->CreateRecordType(nullptr, lldb::eAccessPublic, "EmptyDerived2", - clang::TTK_Struct, lldb::eLanguageTypeC_plus_plus, nullptr); - ClangASTContext::StartTagDeclarationDefinition(empty_derived2); - CXXBaseSpecifier *non_empty_vbase_spec = - m_ast->CreateBaseClassSpecifier(non_empty_base.GetOpaqueQualType(), lldb::eAccessPublic, true, false); - result = m_ast->SetBaseClassesForClassType(empty_derived2.GetOpaqueQualType(), &non_empty_vbase_spec, 1); - ClangASTContext::CompleteTagDeclarationDefinition(empty_derived2); - EXPECT_TRUE(result); - CXXRecordDecl *empty_derived_non_empty_vbase_cxx_decl = - m_ast->GetAsCXXRecordDecl(empty_derived2.GetOpaqueQualType()); - RecordDecl *empty_derived_non_empty_vbase_decl = ClangASTContext::GetAsRecordDecl(empty_derived2); - EXPECT_EQ(1, ClangASTContext::GetNumBaseClasses(empty_derived_non_empty_vbase_cxx_decl, false)); - EXPECT_TRUE(ClangASTContext::RecordHasFields(empty_derived_non_empty_vbase_decl)); +TEST_F(TestClangASTContext, TestRecordHasFields) { + CompilerType int_type = + ClangASTContext::GetBasicType(m_ast->getASTContext(), eBasicTypeInt); + + // Test that a record with no fields returns false + CompilerType empty_base = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "EmptyBase", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + ClangASTContext::StartTagDeclarationDefinition(empty_base); + ClangASTContext::CompleteTagDeclarationDefinition(empty_base); + + RecordDecl *empty_base_decl = ClangASTContext::GetAsRecordDecl(empty_base); + EXPECT_NE(nullptr, empty_base_decl); + EXPECT_FALSE(ClangASTContext::RecordHasFields(empty_base_decl)); + + // Test that a record with direct fields returns true + CompilerType non_empty_base = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "NonEmptyBase", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + ClangASTContext::StartTagDeclarationDefinition(non_empty_base); + FieldDecl *non_empty_base_field_decl = m_ast->AddFieldToRecordType( + non_empty_base, "MyField", int_type, eAccessPublic, 0); + ClangASTContext::CompleteTagDeclarationDefinition(non_empty_base); + RecordDecl *non_empty_base_decl = + ClangASTContext::GetAsRecordDecl(non_empty_base); + EXPECT_NE(nullptr, non_empty_base_decl); + EXPECT_NE(nullptr, non_empty_base_field_decl); + EXPECT_TRUE(ClangASTContext::RecordHasFields(non_empty_base_decl)); + + // Test that a record with no direct fields, but fields in a base returns true + CompilerType empty_derived = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "EmptyDerived", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + ClangASTContext::StartTagDeclarationDefinition(empty_derived); + CXXBaseSpecifier *non_empty_base_spec = m_ast->CreateBaseClassSpecifier( + non_empty_base.GetOpaqueQualType(), lldb::eAccessPublic, false, false); + bool result = m_ast->SetBaseClassesForClassType( + empty_derived.GetOpaqueQualType(), &non_empty_base_spec, 1); + ClangASTContext::CompleteTagDeclarationDefinition(empty_derived); + EXPECT_TRUE(result); + CXXRecordDecl *empty_derived_non_empty_base_cxx_decl = + m_ast->GetAsCXXRecordDecl(empty_derived.GetOpaqueQualType()); + RecordDecl *empty_derived_non_empty_base_decl = + ClangASTContext::GetAsRecordDecl(empty_derived); + EXPECT_EQ(1, ClangASTContext::GetNumBaseClasses( + empty_derived_non_empty_base_cxx_decl, false)); + EXPECT_TRUE( + ClangASTContext::RecordHasFields(empty_derived_non_empty_base_decl)); + + // Test that a record with no direct fields, but fields in a virtual base + // returns true + CompilerType empty_derived2 = m_ast->CreateRecordType( + nullptr, lldb::eAccessPublic, "EmptyDerived2", clang::TTK_Struct, + lldb::eLanguageTypeC_plus_plus, nullptr); + ClangASTContext::StartTagDeclarationDefinition(empty_derived2); + CXXBaseSpecifier *non_empty_vbase_spec = m_ast->CreateBaseClassSpecifier( + non_empty_base.GetOpaqueQualType(), lldb::eAccessPublic, true, false); + result = m_ast->SetBaseClassesForClassType(empty_derived2.GetOpaqueQualType(), + &non_empty_vbase_spec, 1); + ClangASTContext::CompleteTagDeclarationDefinition(empty_derived2); + EXPECT_TRUE(result); + CXXRecordDecl *empty_derived_non_empty_vbase_cxx_decl = + m_ast->GetAsCXXRecordDecl(empty_derived2.GetOpaqueQualType()); + RecordDecl *empty_derived_non_empty_vbase_decl = + ClangASTContext::GetAsRecordDecl(empty_derived2); + EXPECT_EQ(1, ClangASTContext::GetNumBaseClasses( + empty_derived_non_empty_vbase_cxx_decl, false)); + EXPECT_TRUE( + ClangASTContext::RecordHasFields(empty_derived_non_empty_vbase_decl)); } diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-dwarf.cpp b/lldb/unittests/SymbolFile/PDB/Inputs/test-dwarf.cpp index f86ff3d875b..a987e6a9a36 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-dwarf.cpp +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-dwarf.cpp @@ -1,14 +1,6 @@ // Compile with "cl /c /Zi /GR- test.cpp" // Link with "link test.obj /debug /nodefaultlib /entry:main /out:test.exe" -int __cdecl _purecall(void) -{ - return 0; -} +int __cdecl _purecall(void) { return 0; } -int -main(int argc, char **argv) -{ - - return 0; -} +int main(int argc, char **argv) { return 0; } diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-alt.cpp b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-alt.cpp index d36f15e53fb..33d7df0e4a8 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-alt.cpp +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-alt.cpp @@ -1,9 +1,7 @@ // Compile with "cl /c /Zi /GR- test-pdb-alt.cpp" -// Link with "link test-pdb.obj test-pdb-alt.obj /debug /nodefaultlib /entry:main /out:test-pdb.exe" +// Link with "link test-pdb.obj test-pdb-alt.obj /debug /nodefaultlib +// /entry:main /out:test-pdb.exe" #include "test-pdb.h" -int bar(int n) -{ - return n-1; -} +int bar(int n) { return n - 1; } diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-nested.h b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-nested.h index fc63b50d13c..d0a93d8f39e 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-nested.h +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-nested.h @@ -1,9 +1,6 @@ #ifndef TEST_PDB_NESTED_H #define TEST_PDB_NESTED_H -inline int baz(int n) -{ - return n+1; -} +inline int baz(int n) { return n + 1; } #endif
\ No newline at end of file diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp index 9639a3f4b72..89d69c12963 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp @@ -1,5 +1,6 @@ // Compile with "cl /c /Zi /GR- /EHsc test-pdb-types.cpp"
-// Link with "link test-pdb-types.obj /debug /nodefaultlib /entry:main /out:test-pdb-types.exe"
+// Link with "link test-pdb-types.obj /debug /nodefaultlib /entry:main
+// /out:test-pdb-types.exe"
using namespace std;
@@ -21,42 +22,29 @@ static const int sizeof_double = sizeof(double); static const int sizeof_bool = sizeof(bool);
static const int sizeof_wchar = sizeof(wchar_t);
-enum Enum
-{
- EValue1 = 1,
- EValue2 = 2,
+enum Enum {
+ EValue1 = 1,
+ EValue2 = 2,
};
-enum ShortEnum : short
-{
- ESValue1 = 1,
- ESValue2 = 2
-};
+enum ShortEnum : short { ESValue1 = 1, ESValue2 = 2 };
-namespace NS
-{
-class NSClass
-{
- float f;
- double d;
+namespace NS {
+class NSClass {
+ float f;
+ double d;
};
}
-class Class
-{
+class Class {
public:
- class NestedClass
- {
- Enum e;
- };
- ShortEnum se;
+ class NestedClass {
+ Enum e;
+ };
+ ShortEnum se;
};
-int
-test_func(int a, int b)
-{
- return a + b;
-}
+int test_func(int a, int b) { return a + b; }
typedef Class ClassTypedef;
typedef NS::NSClass NSClassTypedef;
@@ -71,16 +59,14 @@ static const int sizeof_ClassTypedef = sizeof(ClassTypedef); static const int sizeof_NSClassTypedef = sizeof(NSClassTypedef);
static const int sizeof_GlobalArray = sizeof(GlobalArray);
-int
-main(int argc, char **argv)
-{
- ShortEnum e1;
- Enum e2;
- Class c1;
- Class::NestedClass c2;
- NS::NSClass c3;
+int main(int argc, char **argv) {
+ ShortEnum e1;
+ Enum e2;
+ Class c1;
+ Class::NestedClass c2;
+ NS::NSClass c3;
- ClassTypedef t1;
- NSClassTypedef t2;
- return test_func(1, 2);
+ ClassTypedef t1;
+ NSClassTypedef t2;
+ return test_func(1, 2);
}
diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.cpp b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.cpp index c9bf057cfbf..77956acd875 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.cpp +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.cpp @@ -1,15 +1,9 @@ // Compile with "cl /c /Zi /GR- test-pdb.cpp" -// Link with "link test-pdb.obj /debug /nodefaultlib /entry:main /out:test-pdb.exe" +// Link with "link test-pdb.obj /debug /nodefaultlib /entry:main +// /out:test-pdb.exe" #include "test-pdb.h" -int __cdecl _purecall(void) -{ - return 0; -} +int __cdecl _purecall(void) { return 0; } -int -main(int argc, char **argv) -{ - return foo(argc) + bar(argc); -} +int main(int argc, char **argv) { return foo(argc) + bar(argc); } diff --git a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.h b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.h index 273343bb03b..077d9d6b1fa 100644 --- a/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.h +++ b/lldb/unittests/SymbolFile/PDB/Inputs/test-pdb.h @@ -5,9 +5,6 @@ int bar(int n); -inline int foo(int n) -{ - return baz(n)+1; -} +inline int foo(int n) { return baz(n) + 1; } #endif
\ No newline at end of file diff --git a/lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp b/lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp index b303ae7bac4..4d602516b49 100644 --- a/lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp +++ b/lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp @@ -42,126 +42,116 @@ extern const char *TestMainArgv0; using namespace lldb_private; -class SymbolFilePDBTests : public testing::Test -{ +class SymbolFilePDBTests : public testing::Test { public: - void - SetUp() override - { + void SetUp() override { // Initialize and TearDown the plugin every time, so we get a brand new // AST every time so that modifications to the AST from each test don't // leak into the next test. #if defined(_MSC_VER) - ::CoInitializeEx(nullptr, COINIT_MULTITHREADED); + ::CoInitializeEx(nullptr, COINIT_MULTITHREADED); #endif - HostInfo::Initialize(); - ObjectFilePECOFF::Initialize(); - SymbolFileDWARF::Initialize(); - ClangASTContext::Initialize(); - SymbolFilePDB::Initialize(); - - llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); - llvm::SmallString<128> inputs_folder = exe_folder; - llvm::sys::path::append(inputs_folder, "Inputs"); - - m_pdb_test_exe = inputs_folder; - m_dwarf_test_exe = inputs_folder; - m_types_test_exe = inputs_folder; - llvm::sys::path::append(m_pdb_test_exe, "test-pdb.exe"); - llvm::sys::path::append(m_dwarf_test_exe, "test-dwarf.exe"); - llvm::sys::path::append(m_types_test_exe, "test-pdb-types.exe"); - } - - void - TearDown() override - { - SymbolFilePDB::Terminate(); - ClangASTContext::Initialize(); - SymbolFileDWARF::Terminate(); - ObjectFilePECOFF::Terminate(); - HostInfo::Terminate(); + HostInfo::Initialize(); + ObjectFilePECOFF::Initialize(); + SymbolFileDWARF::Initialize(); + ClangASTContext::Initialize(); + SymbolFilePDB::Initialize(); + + llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); + llvm::SmallString<128> inputs_folder = exe_folder; + llvm::sys::path::append(inputs_folder, "Inputs"); + + m_pdb_test_exe = inputs_folder; + m_dwarf_test_exe = inputs_folder; + m_types_test_exe = inputs_folder; + llvm::sys::path::append(m_pdb_test_exe, "test-pdb.exe"); + llvm::sys::path::append(m_dwarf_test_exe, "test-dwarf.exe"); + llvm::sys::path::append(m_types_test_exe, "test-pdb-types.exe"); + } + + void TearDown() override { + SymbolFilePDB::Terminate(); + ClangASTContext::Initialize(); + SymbolFileDWARF::Terminate(); + ObjectFilePECOFF::Terminate(); + HostInfo::Terminate(); #if defined(_MSC_VER) - ::CoUninitialize(); + ::CoUninitialize(); #endif - } + } protected: - llvm::SmallString<128> m_pdb_test_exe; - llvm::SmallString<128> m_dwarf_test_exe; - llvm::SmallString<128> m_types_test_exe; - - bool - FileSpecMatchesAsBaseOrFull(const FileSpec &left, const FileSpec &right) const - { - // If the filenames don't match, the paths can't be equal - if (!left.FileEquals(right)) - return false; - // If BOTH have a directory, also compare the directories. - if (left.GetDirectory() && right.GetDirectory()) - return left.DirectoryEquals(right); - - // If one has a directory but not the other, they match. + llvm::SmallString<128> m_pdb_test_exe; + llvm::SmallString<128> m_dwarf_test_exe; + llvm::SmallString<128> m_types_test_exe; + + bool FileSpecMatchesAsBaseOrFull(const FileSpec &left, + const FileSpec &right) const { + // If the filenames don't match, the paths can't be equal + if (!left.FileEquals(right)) + return false; + // If BOTH have a directory, also compare the directories. + if (left.GetDirectory() && right.GetDirectory()) + return left.DirectoryEquals(right); + + // If one has a directory but not the other, they match. + return true; + } + + void VerifyLineEntry(lldb::ModuleSP module, const SymbolContext &sc, + const FileSpec &spec, LineTable <, uint32_t line, + lldb::addr_t addr) { + LineEntry entry; + Address address; + EXPECT_TRUE(module->ResolveFileAddress(addr, address)); + + EXPECT_TRUE(lt.FindLineEntryByAddress(address, entry)); + EXPECT_EQ(line, entry.line); + EXPECT_EQ(address, entry.range.GetBaseAddress()); + + EXPECT_TRUE(FileSpecMatchesAsBaseOrFull(spec, entry.file)); + } + + bool ContainsCompileUnit(const SymbolContextList &sc_list, + const FileSpec &spec) const { + for (size_t i = 0; i < sc_list.GetSize(); ++i) { + const SymbolContext &sc = sc_list[i]; + if (FileSpecMatchesAsBaseOrFull(*sc.comp_unit, spec)) return true; } - - void - VerifyLineEntry(lldb::ModuleSP module, const SymbolContext &sc, const FileSpec &spec, LineTable <, uint32_t line, - lldb::addr_t addr) - { - LineEntry entry; - Address address; - EXPECT_TRUE(module->ResolveFileAddress(addr, address)); - - EXPECT_TRUE(lt.FindLineEntryByAddress(address, entry)); - EXPECT_EQ(line, entry.line); - EXPECT_EQ(address, entry.range.GetBaseAddress()); - - EXPECT_TRUE(FileSpecMatchesAsBaseOrFull(spec, entry.file)); - } - - bool - ContainsCompileUnit(const SymbolContextList &sc_list, const FileSpec &spec) const - { - for (size_t i = 0; i < sc_list.GetSize(); ++i) - { - const SymbolContext &sc = sc_list[i]; - if (FileSpecMatchesAsBaseOrFull(*sc.comp_unit, spec)) - return true; - } - return false; - } - - int - GetGlobalConstantInteger(const llvm::pdb::IPDBSession &session, llvm::StringRef var) const - { - auto global = session.getGlobalScope(); - auto results = - global->findChildren(llvm::pdb::PDB_SymType::Data, var, llvm::pdb::PDB_NameSearchFlags::NS_Default); - uint32_t count = results->getChildCount(); - if (count == 0) - return -1; - - auto item = results->getChildAtIndex(0); - auto symbol = llvm::dyn_cast<llvm::pdb::PDBSymbolData>(item.get()); - if (!symbol) - return -1; - llvm::pdb::Variant value = symbol->getValue(); - switch (value.Type) - { - case llvm::pdb::PDB_VariantType::Int16: - return value.Value.Int16; - case llvm::pdb::PDB_VariantType::Int32: - return value.Value.Int32; - case llvm::pdb::PDB_VariantType::UInt16: - return value.Value.UInt16; - case llvm::pdb::PDB_VariantType::UInt32: - return value.Value.UInt32; - default: - return 0; - } + return false; + } + + int GetGlobalConstantInteger(const llvm::pdb::IPDBSession &session, + llvm::StringRef var) const { + auto global = session.getGlobalScope(); + auto results = + global->findChildren(llvm::pdb::PDB_SymType::Data, var, + llvm::pdb::PDB_NameSearchFlags::NS_Default); + uint32_t count = results->getChildCount(); + if (count == 0) + return -1; + + auto item = results->getChildAtIndex(0); + auto symbol = llvm::dyn_cast<llvm::pdb::PDBSymbolData>(item.get()); + if (!symbol) + return -1; + llvm::pdb::Variant value = symbol->getValue(); + switch (value.Type) { + case llvm::pdb::PDB_VariantType::Int16: + return value.Value.Int16; + case llvm::pdb::PDB_VariantType::Int32: + return value.Value.Int32; + case llvm::pdb::PDB_VariantType::UInt16: + return value.Value.UInt16; + case llvm::pdb::PDB_VariantType::UInt32: + return value.Value.UInt32; + default: + return 0; } + } }; #if defined(HAVE_DIA_SDK) @@ -170,414 +160,443 @@ protected: #define REQUIRES_DIA_SDK(TestName) DISABLED_##TestName #endif -TEST_F(SymbolFilePDBTests, TestAbilitiesForDWARF) -{ - // Test that when we have Dwarf debug info, SymbolFileDWARF is used. - FileSpec fspec(m_dwarf_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - EXPECT_NE(nullptr, symfile); - EXPECT_EQ(symfile->GetPluginName(), SymbolFileDWARF::GetPluginNameStatic()); - - uint32_t expected_abilities = SymbolFile::kAllAbilities; - EXPECT_EQ(expected_abilities, symfile->CalculateAbilities()); -} +TEST_F(SymbolFilePDBTests, TestAbilitiesForDWARF) { + // Test that when we have Dwarf debug info, SymbolFileDWARF is used. + FileSpec fspec(m_dwarf_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestAbilitiesForPDB)) -{ - // Test that when we have PDB debug info, SymbolFilePDB is used. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - EXPECT_NE(nullptr, symfile); - EXPECT_EQ(symfile->GetPluginName(), SymbolFilePDB::GetPluginNameStatic()); - - uint32_t expected_abilities = SymbolFile::CompileUnits | SymbolFile::LineTables; - EXPECT_EQ(expected_abilities, symfile->CalculateAbilities()); -} + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + EXPECT_NE(nullptr, symfile); + EXPECT_EQ(symfile->GetPluginName(), SymbolFileDWARF::GetPluginNameStatic()); -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestResolveSymbolContextBasename)) -{ - // Test that attempting to call ResolveSymbolContext with only a basename finds all full paths - // with the same basename - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec header_spec("test-pdb.cpp", false); - SymbolContextList sc_list; - uint32_t result_count = symfile->ResolveSymbolContext(header_spec, 0, false, lldb::eSymbolContextCompUnit, sc_list); - EXPECT_EQ(1u, result_count); - EXPECT_TRUE(ContainsCompileUnit(sc_list, header_spec)); + uint32_t expected_abilities = SymbolFile::kAllAbilities; + EXPECT_EQ(expected_abilities, symfile->CalculateAbilities()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestResolveSymbolContextFullPath)) -{ - // Test that attempting to call ResolveSymbolContext with a full path only finds the one source - // file that matches the full path. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec header_spec(R"spec(D:\src\llvm\tools\lldb\unittests\SymbolFile\PDB\Inputs\test-pdb.cpp)spec", false); - SymbolContextList sc_list; - uint32_t result_count = symfile->ResolveSymbolContext(header_spec, 0, false, lldb::eSymbolContextCompUnit, sc_list); - EXPECT_GE(1u, result_count); - EXPECT_TRUE(ContainsCompileUnit(sc_list, header_spec)); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestAbilitiesForPDB)) { + // Test that when we have PDB debug info, SymbolFilePDB is used. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + EXPECT_NE(nullptr, symfile); + EXPECT_EQ(symfile->GetPluginName(), SymbolFilePDB::GetPluginNameStatic()); + + uint32_t expected_abilities = + SymbolFile::CompileUnits | SymbolFile::LineTables; + EXPECT_EQ(expected_abilities, symfile->CalculateAbilities()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLookupOfHeaderFileWithInlines)) -{ - // Test that when looking up a header file via ResolveSymbolContext (i.e. a file that was not by itself - // compiled, but only contributes to the combined code of other source files), a SymbolContext is returned - // for each compiland which has line contributions from the requested header. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec header_specs[] = {FileSpec("test-pdb.h", false), FileSpec("test-pdb-nested.h", false)}; - FileSpec main_cpp_spec("test-pdb.cpp", false); - FileSpec alt_cpp_spec("test-pdb-alt.cpp", false); - for (const auto &hspec : header_specs) - { - SymbolContextList sc_list; - uint32_t result_count = symfile->ResolveSymbolContext(hspec, 0, true, lldb::eSymbolContextCompUnit, sc_list); - EXPECT_EQ(2u, result_count); - EXPECT_TRUE(ContainsCompileUnit(sc_list, main_cpp_spec)); - EXPECT_TRUE(ContainsCompileUnit(sc_list, alt_cpp_spec)); - } +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestResolveSymbolContextBasename)) { + // Test that attempting to call ResolveSymbolContext with only a basename + // finds all full paths + // with the same basename + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec header_spec("test-pdb.cpp", false); + SymbolContextList sc_list; + uint32_t result_count = symfile->ResolveSymbolContext( + header_spec, 0, false, lldb::eSymbolContextCompUnit, sc_list); + EXPECT_EQ(1u, result_count); + EXPECT_TRUE(ContainsCompileUnit(sc_list, header_spec)); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLookupOfHeaderFileWithNoInlines)) -{ - // Test that when looking up a header file via ResolveSymbolContext (i.e. a file that was not by itself - // compiled, but only contributes to the combined code of other source files), that if check_inlines - // is false, no SymbolContexts are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - EXPECT_NE(nullptr, plugin); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec header_specs[] = {FileSpec("test-pdb.h", false), FileSpec("test-pdb-nested.h", false)}; - for (const auto &hspec : header_specs) - { - SymbolContextList sc_list; - uint32_t result_count = symfile->ResolveSymbolContext(hspec, 0, false, lldb::eSymbolContextCompUnit, sc_list); - EXPECT_EQ(0u, result_count); - } +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestResolveSymbolContextFullPath)) { + // Test that attempting to call ResolveSymbolContext with a full path only + // finds the one source + // file that matches the full path. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec header_spec( + R"spec(D:\src\llvm\tools\lldb\unittests\SymbolFile\PDB\Inputs\test-pdb.cpp)spec", + false); + SymbolContextList sc_list; + uint32_t result_count = symfile->ResolveSymbolContext( + header_spec, 0, false, lldb::eSymbolContextCompUnit, sc_list); + EXPECT_GE(1u, result_count); + EXPECT_TRUE(ContainsCompileUnit(sc_list, header_spec)); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLineTablesMatchAll)) -{ - // Test that when calling ResolveSymbolContext with a line number of 0, all line entries from - // the specified files are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec source_file("test-pdb.cpp", false); - FileSpec header1("test-pdb.h", false); - FileSpec header2("test-pdb-nested.h", false); - uint32_t cus = symfile->GetNumCompileUnits(); - EXPECT_EQ(2u, cus); - +TEST_F(SymbolFilePDBTests, + REQUIRES_DIA_SDK(TestLookupOfHeaderFileWithInlines)) { + // Test that when looking up a header file via ResolveSymbolContext (i.e. a + // file that was not by itself + // compiled, but only contributes to the combined code of other source files), + // a SymbolContext is returned + // for each compiland which has line contributions from the requested header. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec header_specs[] = {FileSpec("test-pdb.h", false), + FileSpec("test-pdb-nested.h", false)}; + FileSpec main_cpp_spec("test-pdb.cpp", false); + FileSpec alt_cpp_spec("test-pdb-alt.cpp", false); + for (const auto &hspec : header_specs) { SymbolContextList sc_list; - uint32_t scope = lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry; - - uint32_t count = symfile->ResolveSymbolContext(source_file, 0, true, scope, sc_list); - EXPECT_EQ(1u, count); - SymbolContext sc; - EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); - - LineTable *lt = sc.comp_unit->GetLineTable(); - EXPECT_NE(nullptr, lt); - count = lt->GetSize(); - // We expect one extra entry for termination (per function) - EXPECT_EQ(16u, count); - - VerifyLineEntry(module, sc, source_file, *lt, 7, 0x401040); - VerifyLineEntry(module, sc, source_file, *lt, 8, 0x401043); - VerifyLineEntry(module, sc, source_file, *lt, 9, 0x401045); - - VerifyLineEntry(module, sc, source_file, *lt, 13, 0x401050); - VerifyLineEntry(module, sc, source_file, *lt, 14, 0x401054); - VerifyLineEntry(module, sc, source_file, *lt, 15, 0x401070); - - VerifyLineEntry(module, sc, header1, *lt, 9, 0x401090); - VerifyLineEntry(module, sc, header1, *lt, 10, 0x401093); - VerifyLineEntry(module, sc, header1, *lt, 11, 0x4010a2); - - VerifyLineEntry(module, sc, header2, *lt, 5, 0x401080); - VerifyLineEntry(module, sc, header2, *lt, 6, 0x401083); - VerifyLineEntry(module, sc, header2, *lt, 7, 0x401089); + uint32_t result_count = symfile->ResolveSymbolContext( + hspec, 0, true, lldb::eSymbolContextCompUnit, sc_list); + EXPECT_EQ(2u, result_count); + EXPECT_TRUE(ContainsCompileUnit(sc_list, main_cpp_spec)); + EXPECT_TRUE(ContainsCompileUnit(sc_list, alt_cpp_spec)); + } } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLineTablesMatchSpecific)) -{ - // Test that when calling ResolveSymbolContext with a specific line number, only line entries - // which match the requested line are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFile *symfile = plugin->GetSymbolFile(); - - FileSpec source_file("test-pdb.cpp", false); - FileSpec header1("test-pdb.h", false); - FileSpec header2("test-pdb-nested.h", false); - uint32_t cus = symfile->GetNumCompileUnits(); - EXPECT_EQ(2u, cus); - +TEST_F(SymbolFilePDBTests, + REQUIRES_DIA_SDK(TestLookupOfHeaderFileWithNoInlines)) { + // Test that when looking up a header file via ResolveSymbolContext (i.e. a + // file that was not by itself + // compiled, but only contributes to the combined code of other source files), + // that if check_inlines + // is false, no SymbolContexts are returned. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + EXPECT_NE(nullptr, plugin); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec header_specs[] = {FileSpec("test-pdb.h", false), + FileSpec("test-pdb-nested.h", false)}; + for (const auto &hspec : header_specs) { SymbolContextList sc_list; - uint32_t scope = lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry; - - // First test with line 7, and verify that only line 7 entries are added. - uint32_t count = symfile->ResolveSymbolContext(source_file, 7, true, scope, sc_list); - EXPECT_EQ(1u, count); - SymbolContext sc; - EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); - - LineTable *lt = sc.comp_unit->GetLineTable(); - EXPECT_NE(nullptr, lt); - count = lt->GetSize(); - // We expect one extra entry for termination - EXPECT_EQ(3u, count); - - VerifyLineEntry(module, sc, source_file, *lt, 7, 0x401040); - VerifyLineEntry(module, sc, header2, *lt, 7, 0x401089); - - sc_list.Clear(); - // Then test with line 9, and verify that only line 9 entries are added. - count = symfile->ResolveSymbolContext(source_file, 9, true, scope, sc_list); - EXPECT_EQ(1u, count); - EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); - - lt = sc.comp_unit->GetLineTable(); - EXPECT_NE(nullptr, lt); - count = lt->GetSize(); - // We expect one extra entry for termination - EXPECT_EQ(3u, count); - - VerifyLineEntry(module, sc, source_file, *lt, 9, 0x401045); - VerifyLineEntry(module, sc, header1, *lt, 9, 0x401090); + uint32_t result_count = symfile->ResolveSymbolContext( + hspec, 0, false, lldb::eSymbolContextCompUnit, sc_list); + EXPECT_EQ(0u, result_count); + } } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestSimpleClassTypes)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - TypeMap results; - EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("Class"), nullptr, false, 0, searched_files, results)); - EXPECT_EQ(1u, results.GetSize()); - lldb::TypeSP udt_type = results.GetTypeAtIndex(0); - EXPECT_EQ(ConstString("Class"), udt_type->GetName()); - CompilerType compiler_type = udt_type->GetForwardCompilerType(); - EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); - EXPECT_EQ(uint64_t(GetGlobalConstantInteger(session, "sizeof_Class")), udt_type->GetByteSize()); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLineTablesMatchAll)) { + // Test that when calling ResolveSymbolContext with a line number of 0, all + // line entries from + // the specified files are returned. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec source_file("test-pdb.cpp", false); + FileSpec header1("test-pdb.h", false); + FileSpec header2("test-pdb-nested.h", false); + uint32_t cus = symfile->GetNumCompileUnits(); + EXPECT_EQ(2u, cus); + + SymbolContextList sc_list; + uint32_t scope = lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry; + + uint32_t count = + symfile->ResolveSymbolContext(source_file, 0, true, scope, sc_list); + EXPECT_EQ(1u, count); + SymbolContext sc; + EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); + + LineTable *lt = sc.comp_unit->GetLineTable(); + EXPECT_NE(nullptr, lt); + count = lt->GetSize(); + // We expect one extra entry for termination (per function) + EXPECT_EQ(16u, count); + + VerifyLineEntry(module, sc, source_file, *lt, 7, 0x401040); + VerifyLineEntry(module, sc, source_file, *lt, 8, 0x401043); + VerifyLineEntry(module, sc, source_file, *lt, 9, 0x401045); + + VerifyLineEntry(module, sc, source_file, *lt, 13, 0x401050); + VerifyLineEntry(module, sc, source_file, *lt, 14, 0x401054); + VerifyLineEntry(module, sc, source_file, *lt, 15, 0x401070); + + VerifyLineEntry(module, sc, header1, *lt, 9, 0x401090); + VerifyLineEntry(module, sc, header1, *lt, 10, 0x401093); + VerifyLineEntry(module, sc, header1, *lt, 11, 0x4010a2); + + VerifyLineEntry(module, sc, header2, *lt, 5, 0x401080); + VerifyLineEntry(module, sc, header2, *lt, 6, 0x401083); + VerifyLineEntry(module, sc, header2, *lt, 7, 0x401089); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNestedClassTypes)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - TypeMap results; - EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("Class::NestedClass"), nullptr, false, 0, searched_files, results)); - EXPECT_EQ(1u, results.GetSize()); - lldb::TypeSP udt_type = results.GetTypeAtIndex(0); - EXPECT_EQ(ConstString("Class::NestedClass"), udt_type->GetName()); - CompilerType compiler_type = udt_type->GetForwardCompilerType(); - EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); - EXPECT_EQ(uint64_t(GetGlobalConstantInteger(session, "sizeof_NestedClass")), udt_type->GetByteSize()); -} - -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestClassInNamespace)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - TypeMap results; - EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("NS::NSClass"), nullptr, false, 0, searched_files, results)); - EXPECT_EQ(1u, results.GetSize()); - lldb::TypeSP udt_type = results.GetTypeAtIndex(0); - EXPECT_EQ(ConstString("NS::NSClass"), udt_type->GetName()); - CompilerType compiler_type = udt_type->GetForwardCompilerType(); - EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); - EXPECT_EQ(GetGlobalConstantInteger(session, "sizeof_NSClass"), udt_type->GetByteSize()); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestLineTablesMatchSpecific)) { + // Test that when calling ResolveSymbolContext with a specific line number, + // only line entries + // which match the requested line are returned. + FileSpec fspec(m_pdb_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFile *symfile = plugin->GetSymbolFile(); + + FileSpec source_file("test-pdb.cpp", false); + FileSpec header1("test-pdb.h", false); + FileSpec header2("test-pdb-nested.h", false); + uint32_t cus = symfile->GetNumCompileUnits(); + EXPECT_EQ(2u, cus); + + SymbolContextList sc_list; + uint32_t scope = lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry; + + // First test with line 7, and verify that only line 7 entries are added. + uint32_t count = + symfile->ResolveSymbolContext(source_file, 7, true, scope, sc_list); + EXPECT_EQ(1u, count); + SymbolContext sc; + EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); + + LineTable *lt = sc.comp_unit->GetLineTable(); + EXPECT_NE(nullptr, lt); + count = lt->GetSize(); + // We expect one extra entry for termination + EXPECT_EQ(3u, count); + + VerifyLineEntry(module, sc, source_file, *lt, 7, 0x401040); + VerifyLineEntry(module, sc, header2, *lt, 7, 0x401089); + + sc_list.Clear(); + // Then test with line 9, and verify that only line 9 entries are added. + count = symfile->ResolveSymbolContext(source_file, 9, true, scope, sc_list); + EXPECT_EQ(1u, count); + EXPECT_TRUE(sc_list.GetContextAtIndex(0, sc)); + + lt = sc.comp_unit->GetLineTable(); + EXPECT_NE(nullptr, lt); + count = lt->GetSize(); + // We expect one extra entry for termination + EXPECT_EQ(3u, count); + + VerifyLineEntry(module, sc, source_file, *lt, 9, 0x401045); + VerifyLineEntry(module, sc, header1, *lt, 9, 0x401090); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestEnumTypes)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - const char *EnumsToCheck[] = {"Enum", "ShortEnum"}; - for (auto Enum : EnumsToCheck) - { - TypeMap results; - EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString(Enum), nullptr, false, 0, searched_files, results)); - EXPECT_EQ(1u, results.GetSize()); - lldb::TypeSP enum_type = results.GetTypeAtIndex(0); - EXPECT_EQ(ConstString(Enum), enum_type->GetName()); - CompilerType compiler_type = enum_type->GetFullCompilerType(); - EXPECT_TRUE(ClangASTContext::IsEnumType(compiler_type.GetOpaqueQualType())); - clang::EnumDecl *enum_decl = ClangASTContext::GetAsEnumDecl(compiler_type); - EXPECT_NE(nullptr, enum_decl); - EXPECT_EQ(2, std::distance(enum_decl->enumerator_begin(), enum_decl->enumerator_end())); - - std::string sizeof_var = "sizeof_"; - sizeof_var.append(Enum); - EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), enum_type->GetByteSize()); - } +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestSimpleClassTypes)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("Class"), nullptr, false, 0, + searched_files, results)); + EXPECT_EQ(1u, results.GetSize()); + lldb::TypeSP udt_type = results.GetTypeAtIndex(0); + EXPECT_EQ(ConstString("Class"), udt_type->GetName()); + CompilerType compiler_type = udt_type->GetForwardCompilerType(); + EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); + EXPECT_EQ(uint64_t(GetGlobalConstantInteger(session, "sizeof_Class")), + udt_type->GetByteSize()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestArrayTypes)) -{ - // In order to get this test working, we need to support lookup by symbol name. Because array - // types themselves do not have names, only the symbols have names (i.e. the name of the array). +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNestedClassTypes)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("Class::NestedClass"), + nullptr, false, 0, searched_files, results)); + EXPECT_EQ(1u, results.GetSize()); + lldb::TypeSP udt_type = results.GetTypeAtIndex(0); + EXPECT_EQ(ConstString("Class::NestedClass"), udt_type->GetName()); + CompilerType compiler_type = udt_type->GetForwardCompilerType(); + EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); + EXPECT_EQ(uint64_t(GetGlobalConstantInteger(session, "sizeof_NestedClass")), + udt_type->GetByteSize()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestFunctionTypes)) -{ - // In order to get this test working, we need to support lookup by symbol name. Because array - // types themselves do not have names, only the symbols have names (i.e. the name of the array). +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestClassInNamespace)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString("NS::NSClass"), nullptr, + false, 0, searched_files, results)); + EXPECT_EQ(1u, results.GetSize()); + lldb::TypeSP udt_type = results.GetTypeAtIndex(0); + EXPECT_EQ(ConstString("NS::NSClass"), udt_type->GetName()); + CompilerType compiler_type = udt_type->GetForwardCompilerType(); + EXPECT_TRUE(ClangASTContext::IsClassType(compiler_type.GetOpaqueQualType())); + EXPECT_EQ(GetGlobalConstantInteger(session, "sizeof_NSClass"), + udt_type->GetByteSize()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestTypedefs)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestEnumTypes)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + const char *EnumsToCheck[] = {"Enum", "ShortEnum"}; + for (auto Enum : EnumsToCheck) { TypeMap results; + EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString(Enum), nullptr, false, 0, + searched_files, results)); + EXPECT_EQ(1u, results.GetSize()); + lldb::TypeSP enum_type = results.GetTypeAtIndex(0); + EXPECT_EQ(ConstString(Enum), enum_type->GetName()); + CompilerType compiler_type = enum_type->GetFullCompilerType(); + EXPECT_TRUE(ClangASTContext::IsEnumType(compiler_type.GetOpaqueQualType())); + clang::EnumDecl *enum_decl = ClangASTContext::GetAsEnumDecl(compiler_type); + EXPECT_NE(nullptr, enum_decl); + EXPECT_EQ(2, std::distance(enum_decl->enumerator_begin(), + enum_decl->enumerator_end())); + + std::string sizeof_var = "sizeof_"; + sizeof_var.append(Enum); + EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), + enum_type->GetByteSize()); + } +} - const char *TypedefsToCheck[] = {"ClassTypedef", "NSClassTypedef"}; - for (auto Typedef : TypedefsToCheck) - { - TypeMap results; - EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString(Typedef), nullptr, false, 0, searched_files, results)); - EXPECT_EQ(1u, results.GetSize()); - lldb::TypeSP typedef_type = results.GetTypeAtIndex(0); - EXPECT_EQ(ConstString(Typedef), typedef_type->GetName()); - CompilerType compiler_type = typedef_type->GetFullCompilerType(); - ClangASTContext *clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem()); - EXPECT_TRUE(clang_type_system->IsTypedefType(compiler_type.GetOpaqueQualType())); - - std::string sizeof_var = "sizeof_"; - sizeof_var.append(Typedef); - EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), typedef_type->GetByteSize()); - } +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestArrayTypes)) { + // In order to get this test working, we need to support lookup by symbol + // name. Because array + // types themselves do not have names, only the symbols have names (i.e. the + // name of the array). } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestRegexNameMatch)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestFunctionTypes)) { + // In order to get this test working, we need to support lookup by symbol + // name. Because array + // types themselves do not have names, only the symbols have names (i.e. the + // name of the array). +} - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestTypedefs)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + const llvm::pdb::IPDBSession &session = symfile->GetPDBSession(); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + + const char *TypedefsToCheck[] = {"ClassTypedef", "NSClassTypedef"}; + for (auto Typedef : TypedefsToCheck) { TypeMap results; - uint32_t num_results = symfile->FindTypes(sc, ConstString(".*"), nullptr, false, 0, searched_files, results); - EXPECT_GT(num_results, 1u); - EXPECT_EQ(num_results, results.GetSize()); + EXPECT_EQ(1u, symfile->FindTypes(sc, ConstString(Typedef), nullptr, false, + 0, searched_files, results)); + EXPECT_EQ(1u, results.GetSize()); + lldb::TypeSP typedef_type = results.GetTypeAtIndex(0); + EXPECT_EQ(ConstString(Typedef), typedef_type->GetName()); + CompilerType compiler_type = typedef_type->GetFullCompilerType(); + ClangASTContext *clang_type_system = + llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem()); + EXPECT_TRUE( + clang_type_system->IsTypedefType(compiler_type.GetOpaqueQualType())); + + std::string sizeof_var = "sizeof_"; + sizeof_var.append(Typedef); + EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), + typedef_type->GetByteSize()); + } } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestMaxMatches)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); - - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - TypeMap results; - uint32_t num_results = symfile->FindTypes(sc, ConstString(".*"), nullptr, false, 0, searched_files, results); - // Try to limit ourselves from 1 to 10 results, otherwise we could be doing this thousands of times. - // The idea is just to make sure that for a variety of values, the number of limited results always - // comes out to the number we are expecting. - uint32_t iterations = std::min(num_results, 10u); - for (uint32_t i = 1; i <= iterations; ++i) - { - uint32_t num_limited_results = symfile->FindTypes(sc, ConstString(".*"), nullptr, false, i, searched_files, results); - EXPECT_EQ(i, num_limited_results); - EXPECT_EQ(num_limited_results, results.GetSize()); - } +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestRegexNameMatch)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + uint32_t num_results = symfile->FindTypes(sc, ConstString(".*"), nullptr, + false, 0, searched_files, results); + EXPECT_GT(num_results, 1u); + EXPECT_EQ(num_results, results.GetSize()); } -TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNullName)) -{ - FileSpec fspec(m_types_test_exe.c_str(), false); - ArchSpec aspec("i686-pc-windows"); - lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestMaxMatches)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + uint32_t num_results = symfile->FindTypes(sc, ConstString(".*"), nullptr, + false, 0, searched_files, results); + // Try to limit ourselves from 1 to 10 results, otherwise we could be doing + // this thousands of times. + // The idea is just to make sure that for a variety of values, the number of + // limited results always + // comes out to the number we are expecting. + uint32_t iterations = std::min(num_results, 10u); + for (uint32_t i = 1; i <= iterations; ++i) { + uint32_t num_limited_results = symfile->FindTypes( + sc, ConstString(".*"), nullptr, false, i, searched_files, results); + EXPECT_EQ(i, num_limited_results); + EXPECT_EQ(num_limited_results, results.GetSize()); + } +} - SymbolVendor *plugin = module->GetSymbolVendor(); - SymbolFilePDB *symfile = static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); - SymbolContext sc; - llvm::DenseSet<SymbolFile *> searched_files; - TypeMap results; - uint32_t num_results = symfile->FindTypes(sc, ConstString(), nullptr, false, 0, searched_files, results); - EXPECT_EQ(0u, num_results); - EXPECT_EQ(0u, results.GetSize()); +TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNullName)) { + FileSpec fspec(m_types_test_exe.c_str(), false); + ArchSpec aspec("i686-pc-windows"); + lldb::ModuleSP module = std::make_shared<Module>(fspec, aspec); + + SymbolVendor *plugin = module->GetSymbolVendor(); + SymbolFilePDB *symfile = + static_cast<SymbolFilePDB *>(plugin->GetSymbolFile()); + SymbolContext sc; + llvm::DenseSet<SymbolFile *> searched_files; + TypeMap results; + uint32_t num_results = symfile->FindTypes(sc, ConstString(), nullptr, false, + 0, searched_files, results); + EXPECT_EQ(0u, num_results); + EXPECT_EQ(0u, results.GetSize()); } diff --git a/lldb/unittests/Utility/Inputs/TestModule.c b/lldb/unittests/Utility/Inputs/TestModule.c index 12374e1f7c6..6347f726494 100644 --- a/lldb/unittests/Utility/Inputs/TestModule.c +++ b/lldb/unittests/Utility/Inputs/TestModule.c @@ -1,10 +1,9 @@ // Compile with $CC -nostdlib -shared TestModule.c -o TestModule.so -// The actual contents of the test module is not important here. I am using this because it +// The actual contents of the test module is not important here. I am using this +// because it // produces an extremely tiny (but still perfectly valid) module. -void -boom(void) -{ - char *BOOM; - *BOOM = 47; +void boom(void) { + char *BOOM; + *BOOM = 47; } diff --git a/lldb/unittests/Utility/ModuleCacheTest.cpp b/lldb/unittests/Utility/ModuleCacheTest.cpp index 53bfc882f23..911c278c162 100644 --- a/lldb/unittests/Utility/ModuleCacheTest.cpp +++ b/lldb/unittests/Utility/ModuleCacheTest.cpp @@ -16,24 +16,20 @@ extern const char *TestMainArgv0; using namespace lldb_private; using namespace lldb; -namespace -{ +namespace { -class ModuleCacheTest : public testing::Test -{ +class ModuleCacheTest : public testing::Test { public: - static void - SetUpTestCase(); + static void SetUpTestCase(); - static void - TearDownTestCase(); + static void TearDownTestCase(); protected: - static FileSpec s_cache_dir; - static llvm::SmallString<128> s_test_executable; + static FileSpec s_cache_dir; + static llvm::SmallString<128> s_test_executable; - void - TryGetAndPut(const FileSpec &cache_dir, const char *hostname, bool expect_download); + void TryGetAndPut(const FileSpec &cache_dir, const char *hostname, + bool expect_download); }; } @@ -43,137 +39,131 @@ llvm::SmallString<128> ModuleCacheTest::s_test_executable; static const char dummy_hostname[] = "dummy_hostname"; static const char dummy_remote_dir[] = "bin"; static const char module_name[] = "TestModule.so"; -static const char module_uuid[] = "F4E7E991-9B61-6AD4-0073-561AC3D9FA10-C043A476"; +static const char module_uuid[] = + "F4E7E991-9B61-6AD4-0073-561AC3D9FA10-C043A476"; static const uint32_t uuid_bytes = 20; static const size_t module_size = 5602; -static FileSpec -GetDummyRemotePath() -{ - FileSpec fs("/", false, FileSpec::ePathSyntaxPosix); - fs.AppendPathComponent(dummy_remote_dir); - fs.AppendPathComponent(module_name); - return fs; +static FileSpec GetDummyRemotePath() { + FileSpec fs("/", false, FileSpec::ePathSyntaxPosix); + fs.AppendPathComponent(dummy_remote_dir); + fs.AppendPathComponent(module_name); + return fs; } -static FileSpec -GetUuidView(FileSpec spec) -{ - spec.AppendPathComponent(".cache"); - spec.AppendPathComponent(module_uuid); - spec.AppendPathComponent(module_name); - return spec; +static FileSpec GetUuidView(FileSpec spec) { + spec.AppendPathComponent(".cache"); + spec.AppendPathComponent(module_uuid); + spec.AppendPathComponent(module_name); + return spec; } -static FileSpec -GetSysrootView(FileSpec spec, const char *hostname) -{ - spec.AppendPathComponent(hostname); - spec.AppendPathComponent(dummy_remote_dir); - spec.AppendPathComponent(module_name); - return spec; +static FileSpec GetSysrootView(FileSpec spec, const char *hostname) { + spec.AppendPathComponent(hostname); + spec.AppendPathComponent(dummy_remote_dir); + spec.AppendPathComponent(module_name); + return spec; } -void -ModuleCacheTest::SetUpTestCase() -{ - HostInfo::Initialize(); - ObjectFileELF::Initialize(); +void ModuleCacheTest::SetUpTestCase() { + HostInfo::Initialize(); + ObjectFileELF::Initialize(); - FileSpec tmpdir_spec; - HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, s_cache_dir); + FileSpec tmpdir_spec; + HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, s_cache_dir); - llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); - s_test_executable = exe_folder; - llvm::sys::path::append(s_test_executable, "Inputs", module_name); + llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); + s_test_executable = exe_folder; + llvm::sys::path::append(s_test_executable, "Inputs", module_name); } -void -ModuleCacheTest::TearDownTestCase() -{ - ObjectFileELF::Terminate(); - HostInfo::Terminate(); +void ModuleCacheTest::TearDownTestCase() { + ObjectFileELF::Terminate(); + HostInfo::Terminate(); } -static void -VerifyDiskState(const FileSpec &cache_dir, const char *hostname) -{ - FileSpec uuid_view = GetUuidView(cache_dir); - EXPECT_TRUE(uuid_view.Exists()) << "uuid_view is: " << uuid_view.GetCString(); - EXPECT_EQ(module_size, uuid_view.GetByteSize()); +static void VerifyDiskState(const FileSpec &cache_dir, const char *hostname) { + FileSpec uuid_view = GetUuidView(cache_dir); + EXPECT_TRUE(uuid_view.Exists()) << "uuid_view is: " << uuid_view.GetCString(); + EXPECT_EQ(module_size, uuid_view.GetByteSize()); - FileSpec sysroot_view = GetSysrootView(cache_dir, hostname); - EXPECT_TRUE(sysroot_view.Exists()) << "sysroot_view is: " << sysroot_view.GetCString(); - EXPECT_EQ(module_size, sysroot_view.GetByteSize()); + FileSpec sysroot_view = GetSysrootView(cache_dir, hostname); + EXPECT_TRUE(sysroot_view.Exists()) << "sysroot_view is: " + << sysroot_view.GetCString(); + EXPECT_EQ(module_size, sysroot_view.GetByteSize()); } -void -ModuleCacheTest::TryGetAndPut(const FileSpec &cache_dir, const char *hostname, bool expect_download) -{ - ModuleCache mc; - ModuleSpec module_spec; - module_spec.GetFileSpec() = GetDummyRemotePath(); - module_spec.GetUUID().SetFromCString(module_uuid, uuid_bytes); - module_spec.SetObjectSize(module_size); - ModuleSP module_sp; - bool did_create; - bool download_called = false; - - Error error = mc.GetAndPut( - cache_dir, hostname, module_spec, - [this, &download_called](const ModuleSpec &module_spec, const FileSpec &tmp_download_file_spec) { - download_called = true; - EXPECT_STREQ(GetDummyRemotePath().GetCString(), module_spec.GetFileSpec().GetCString()); - std::error_code ec = llvm::sys::fs::copy_file(s_test_executable, tmp_download_file_spec.GetCString()); - EXPECT_FALSE(ec); - return Error(); - }, - [](const ModuleSP &module_sp, const FileSpec &tmp_download_file_spec) { return Error("Not supported."); }, - module_sp, &did_create); - EXPECT_EQ(expect_download, download_called); - - EXPECT_TRUE(error.Success()) << "Error was: " << error.AsCString(); - EXPECT_TRUE(did_create); - ASSERT_TRUE(bool(module_sp)); - - SymbolContextList sc_list; - EXPECT_EQ(1u, module_sp->FindFunctionSymbols(ConstString("boom"), eFunctionNameTypeFull, sc_list)); - EXPECT_STREQ(GetDummyRemotePath().GetCString(), module_sp->GetPlatformFileSpec().GetCString()); - EXPECT_STREQ(module_uuid, module_sp->GetUUID().GetAsString().c_str()); +void ModuleCacheTest::TryGetAndPut(const FileSpec &cache_dir, + const char *hostname, bool expect_download) { + ModuleCache mc; + ModuleSpec module_spec; + module_spec.GetFileSpec() = GetDummyRemotePath(); + module_spec.GetUUID().SetFromCString(module_uuid, uuid_bytes); + module_spec.SetObjectSize(module_size); + ModuleSP module_sp; + bool did_create; + bool download_called = false; + + Error error = mc.GetAndPut( + cache_dir, hostname, module_spec, + [this, &download_called](const ModuleSpec &module_spec, + const FileSpec &tmp_download_file_spec) { + download_called = true; + EXPECT_STREQ(GetDummyRemotePath().GetCString(), + module_spec.GetFileSpec().GetCString()); + std::error_code ec = llvm::sys::fs::copy_file( + s_test_executable, tmp_download_file_spec.GetCString()); + EXPECT_FALSE(ec); + return Error(); + }, + [](const ModuleSP &module_sp, const FileSpec &tmp_download_file_spec) { + return Error("Not supported."); + }, + module_sp, &did_create); + EXPECT_EQ(expect_download, download_called); + + EXPECT_TRUE(error.Success()) << "Error was: " << error.AsCString(); + EXPECT_TRUE(did_create); + ASSERT_TRUE(bool(module_sp)); + + SymbolContextList sc_list; + EXPECT_EQ(1u, module_sp->FindFunctionSymbols(ConstString("boom"), + eFunctionNameTypeFull, sc_list)); + EXPECT_STREQ(GetDummyRemotePath().GetCString(), + module_sp->GetPlatformFileSpec().GetCString()); + EXPECT_STREQ(module_uuid, module_sp->GetUUID().GetAsString().c_str()); } -TEST_F(ModuleCacheTest, GetAndPut) -{ - FileSpec test_cache_dir = s_cache_dir; - test_cache_dir.AppendPathComponent("GetAndPut"); +TEST_F(ModuleCacheTest, GetAndPut) { + FileSpec test_cache_dir = s_cache_dir; + test_cache_dir.AppendPathComponent("GetAndPut"); - const bool expect_download = true; - TryGetAndPut(test_cache_dir, dummy_hostname, expect_download); - VerifyDiskState(test_cache_dir, dummy_hostname); + const bool expect_download = true; + TryGetAndPut(test_cache_dir, dummy_hostname, expect_download); + VerifyDiskState(test_cache_dir, dummy_hostname); } -TEST_F(ModuleCacheTest, GetAndPutUuidExists) -{ - FileSpec test_cache_dir = s_cache_dir; - test_cache_dir.AppendPathComponent("GetAndPutUuidExists"); +TEST_F(ModuleCacheTest, GetAndPutUuidExists) { + FileSpec test_cache_dir = s_cache_dir; + test_cache_dir.AppendPathComponent("GetAndPutUuidExists"); - FileSpec uuid_view = GetUuidView(test_cache_dir); - std::error_code ec = llvm::sys::fs::create_directories(uuid_view.GetDirectory().GetCString()); - ASSERT_FALSE(ec); - ec = llvm::sys::fs::copy_file(s_test_executable, uuid_view.GetCString()); - ASSERT_FALSE(ec); + FileSpec uuid_view = GetUuidView(test_cache_dir); + std::error_code ec = + llvm::sys::fs::create_directories(uuid_view.GetDirectory().GetCString()); + ASSERT_FALSE(ec); + ec = llvm::sys::fs::copy_file(s_test_executable, uuid_view.GetCString()); + ASSERT_FALSE(ec); - const bool expect_download = false; - TryGetAndPut(test_cache_dir, dummy_hostname, expect_download); - VerifyDiskState(test_cache_dir, dummy_hostname); + const bool expect_download = false; + TryGetAndPut(test_cache_dir, dummy_hostname, expect_download); + VerifyDiskState(test_cache_dir, dummy_hostname); } -TEST_F(ModuleCacheTest, GetAndPutStrangeHostname) -{ - FileSpec test_cache_dir = s_cache_dir; - test_cache_dir.AppendPathComponent("GetAndPutStrangeHostname"); +TEST_F(ModuleCacheTest, GetAndPutStrangeHostname) { + FileSpec test_cache_dir = s_cache_dir; + test_cache_dir.AppendPathComponent("GetAndPutStrangeHostname"); - const bool expect_download = true; - TryGetAndPut(test_cache_dir, "tab\tcolon:asterisk*", expect_download); - VerifyDiskState(test_cache_dir, "tab_colon_asterisk_"); + const bool expect_download = true; + TryGetAndPut(test_cache_dir, "tab\tcolon:asterisk*", expect_download); + VerifyDiskState(test_cache_dir, "tab_colon_asterisk_"); } diff --git a/lldb/unittests/Utility/StringExtractorTest.cpp b/lldb/unittests/Utility/StringExtractorTest.cpp index 94cb4e58d07..42f7fb7d014 100644 --- a/lldb/unittests/Utility/StringExtractorTest.cpp +++ b/lldb/unittests/Utility/StringExtractorTest.cpp @@ -1,738 +1,698 @@ -#include <limits.h> #include "gtest/gtest.h" +#include <limits.h> #include "lldb/Utility/StringExtractor.h" -namespace -{ - class StringExtractorTest: public ::testing::Test - { - }; +namespace { +class StringExtractorTest : public ::testing::Test {}; +} + +TEST_F(StringExtractorTest, InitEmpty) { + const char kEmptyString[] = ""; + StringExtractor ex(kEmptyString); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_STREQ(kEmptyString, ex.GetStringRef().c_str()); + ASSERT_EQ(true, ex.Empty()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, InitMisc) { + const char kInitMiscString[] = "Hello, StringExtractor!"; + StringExtractor ex(kInitMiscString); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_STREQ(kInitMiscString, ex.GetStringRef().c_str()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(sizeof(kInitMiscString) - 1, ex.GetBytesLeft()); + ASSERT_EQ(kInitMiscString[0], *ex.Peek()); } -TEST_F (StringExtractorTest, InitEmpty) -{ - const char kEmptyString[] = ""; - StringExtractor ex (kEmptyString); +TEST_F(StringExtractorTest, DecodeHexU8_Underflow) { + const char kEmptyString[] = ""; + StringExtractor ex(kEmptyString); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_STREQ (kEmptyString, ex.GetStringRef().c_str()); - ASSERT_EQ (true, ex.Empty()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); + ASSERT_EQ(-1, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(true, ex.Empty()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); } -TEST_F (StringExtractorTest, InitMisc) -{ - const char kInitMiscString[] = "Hello, StringExtractor!"; - StringExtractor ex (kInitMiscString); +TEST_F(StringExtractorTest, DecodeHexU8_Underflow2) { + const char kEmptyString[] = "1"; + StringExtractor ex(kEmptyString); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_STREQ (kInitMiscString, ex.GetStringRef().c_str()); - ASSERT_EQ (false, ex.Empty()); - ASSERT_EQ (sizeof(kInitMiscString)-1, ex.GetBytesLeft()); - ASSERT_EQ (kInitMiscString[0], *ex.Peek()); + ASSERT_EQ(-1, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(1u, ex.GetBytesLeft()); + ASSERT_EQ('1', *ex.Peek()); } -TEST_F (StringExtractorTest, DecodeHexU8_Underflow) -{ - const char kEmptyString[] = ""; - StringExtractor ex (kEmptyString); +TEST_F(StringExtractorTest, DecodeHexU8_InvalidHex) { + const char kInvalidHex[] = "xa"; + StringExtractor ex(kInvalidHex); - ASSERT_EQ (-1, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (true, ex.Empty()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); + ASSERT_EQ(-1, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('x', *ex.Peek()); } -TEST_F (StringExtractorTest, DecodeHexU8_Underflow2) -{ - const char kEmptyString[] = "1"; - StringExtractor ex (kEmptyString); - - ASSERT_EQ (-1, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (1u, ex.GetBytesLeft()); - ASSERT_EQ ('1', *ex.Peek()); +TEST_F(StringExtractorTest, DecodeHexU8_InvalidHex2) { + const char kInvalidHex[] = "ax"; + StringExtractor ex(kInvalidHex); + + ASSERT_EQ(-1, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('a', *ex.Peek()); } -TEST_F (StringExtractorTest, DecodeHexU8_InvalidHex) -{ - const char kInvalidHex[] = "xa"; - StringExtractor ex (kInvalidHex); - - ASSERT_EQ (-1, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('x', *ex.Peek()); +TEST_F(StringExtractorTest, DecodeHexU8_Exact) { + const char kValidHexPair[] = "12"; + StringExtractor ex(kValidHexPair); + + ASSERT_EQ(0x12, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); } -TEST_F (StringExtractorTest, DecodeHexU8_InvalidHex2) -{ - const char kInvalidHex[] = "ax"; - StringExtractor ex (kInvalidHex); - - ASSERT_EQ (-1, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('a', *ex.Peek()); +TEST_F(StringExtractorTest, DecodeHexU8_Extra) { + const char kValidHexPair[] = "1234"; + StringExtractor ex(kValidHexPair); + + ASSERT_EQ(0x12, ex.DecodeHexU8()); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('3', *ex.Peek()); } -TEST_F (StringExtractorTest, DecodeHexU8_Exact) -{ - const char kValidHexPair[] = "12"; - StringExtractor ex (kValidHexPair); - - ASSERT_EQ (0x12, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} +TEST_F(StringExtractorTest, GetHexU8_Underflow) { + const char kEmptyString[] = ""; + StringExtractor ex(kEmptyString); -TEST_F (StringExtractorTest, DecodeHexU8_Extra) -{ - const char kValidHexPair[] = "1234"; - StringExtractor ex (kValidHexPair); - - ASSERT_EQ (0x12, ex.DecodeHexU8()); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('3', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Underflow) -{ - const char kEmptyString[] = ""; - StringExtractor ex (kEmptyString); - - ASSERT_EQ (0xab, ex.GetHexU8(0xab)); - ASSERT_EQ (false, ex.IsGood()); - ASSERT_EQ (UINT64_MAX, ex.GetFilePos()); - ASSERT_EQ (true, ex.Empty()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Underflow2) -{ - const char kOneNibble[] = "1"; - StringExtractor ex (kOneNibble); - - ASSERT_EQ (0xbc, ex.GetHexU8(0xbc)); - ASSERT_EQ (false, ex.IsGood()); - ASSERT_EQ (UINT64_MAX, ex.GetFilePos()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_InvalidHex) -{ - const char kInvalidHex[] = "xx"; - StringExtractor ex (kInvalidHex); - - ASSERT_EQ (0xcd, ex.GetHexU8(0xcd)); - ASSERT_EQ (false, ex.IsGood()); - ASSERT_EQ (UINT64_MAX, ex.GetFilePos()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Exact) -{ - const char kValidHexPair[] = "12"; - StringExtractor ex (kValidHexPair); - - ASSERT_EQ (0x12, ex.GetHexU8(0x12)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Extra) -{ - const char kValidHexPair[] = "1234"; - StringExtractor ex (kValidHexPair); - - ASSERT_EQ (0x12, ex.GetHexU8(0x12)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('3', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Underflow_NoEof) -{ - const char kEmptyString[] = ""; - StringExtractor ex (kEmptyString); - const bool kSetEofOnFail = false; - - ASSERT_EQ (0xab, ex.GetHexU8(0xab, kSetEofOnFail)); - ASSERT_EQ (false, ex.IsGood()); // this result seems inconsistent with kSetEofOnFail == false - ASSERT_EQ (UINT64_MAX, ex.GetFilePos()); - ASSERT_EQ (true, ex.Empty()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Underflow2_NoEof) -{ - const char kOneNibble[] = "1"; - StringExtractor ex (kOneNibble); - const bool kSetEofOnFail = false; - - ASSERT_EQ (0xbc, ex.GetHexU8(0xbc, kSetEofOnFail)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (1u, ex.GetBytesLeft()); - ASSERT_EQ ('1', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_InvalidHex_NoEof) -{ - const char kInvalidHex[] = "xx"; - StringExtractor ex (kInvalidHex); - const bool kSetEofOnFail = false; - - ASSERT_EQ (0xcd, ex.GetHexU8(0xcd, kSetEofOnFail)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (0u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('x', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Exact_NoEof) -{ - const char kValidHexPair[] = "12"; - StringExtractor ex (kValidHexPair); - const bool kSetEofOnFail = false; - - ASSERT_EQ (0x12, ex.GetHexU8(0x12, kSetEofOnFail)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (0u, ex.GetBytesLeft()); - ASSERT_EQ (nullptr, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexU8_Extra_NoEof) -{ - const char kValidHexPair[] = "1234"; - StringExtractor ex (kValidHexPair); - const bool kSetEofOnFail = false; - - ASSERT_EQ (0x12, ex.GetHexU8(0x12, kSetEofOnFail)); - ASSERT_EQ (true, ex.IsGood()); - ASSERT_EQ (2u, ex.GetFilePos()); - ASSERT_EQ (2u, ex.GetBytesLeft()); - ASSERT_EQ ('3', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexBytes) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[kValidHexPairs]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytes (dst, 0xde)); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - EXPECT_EQ(0x23,dst[4]); - EXPECT_EQ(0x45,dst[5]); - EXPECT_EQ(0x67,dst[6]); - EXPECT_EQ(0x89,dst[7]); - - ASSERT_EQ(true, ex.IsGood()); - ASSERT_EQ(2*kValidHexPairs, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(4u, ex.GetBytesLeft()); - ASSERT_EQ('x', *ex.Peek()); -} - -TEST_F(StringExtractorTest, GetHexBytes_FullString) -{ - const char kHexEncodedBytes[] = "abcdef0123456789"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[kValidHexPairs]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); - EXPECT_EQ(0x89, dst[7]); -} - -TEST_F(StringExtractorTest, GetHexBytes_OddPair) -{ - const char kHexEncodedBytes[] = "abcdef012345678w"; - const size_t kValidHexPairs = 7; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[8]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); - - // This one should be invalid - EXPECT_EQ(0xde, dst[7]); -} - - -TEST_F(StringExtractorTest, GetHexBytes_OddPair2) -{ - const char kHexEncodedBytes[] = "abcdef012345678"; - const size_t kValidHexPairs = 7; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[8]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); - - EXPECT_EQ(0xde, dst[7]); -} - -TEST_F (StringExtractorTest, GetHexBytes_Underflow) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[12]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytes (dst, 0xde)); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - EXPECT_EQ(0x23,dst[4]); - EXPECT_EQ(0x45,dst[5]); - EXPECT_EQ(0x67,dst[6]); - EXPECT_EQ(0x89,dst[7]); - // these bytes should be filled with fail_fill_value 0xde - EXPECT_EQ(0xde,dst[8]); - EXPECT_EQ(0xde,dst[9]); - EXPECT_EQ(0xde,dst[10]); - EXPECT_EQ(0xde,dst[11]); - - ASSERT_EQ(false, ex.IsGood()); - ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(0u, ex.GetBytesLeft()); - ASSERT_EQ(0, ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexBytes_Partial) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kReadBytes = 4; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[12]; - memset(dst, 0xab, sizeof(dst)); - ASSERT_EQ(kReadBytes, ex.GetHexBytes (llvm::MutableArrayRef<uint8_t>(dst, kReadBytes), 0xde)); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - // these bytes should be unchanged - EXPECT_EQ(0xab,dst[4]); - EXPECT_EQ(0xab,dst[5]); - EXPECT_EQ(0xab,dst[6]); - EXPECT_EQ(0xab,dst[7]); - EXPECT_EQ(0xab,dst[8]); - EXPECT_EQ(0xab,dst[9]); - EXPECT_EQ(0xab,dst[10]); - EXPECT_EQ(0xab,dst[11]); - - ASSERT_EQ(true, ex.IsGood()); - ASSERT_EQ(kReadBytes*2, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(12u, ex.GetBytesLeft()); - ASSERT_EQ('2', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexBytesAvail) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[kValidHexPairs]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail (dst)); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - EXPECT_EQ(0x23,dst[4]); - EXPECT_EQ(0x45,dst[5]); - EXPECT_EQ(0x67,dst[6]); - EXPECT_EQ(0x89,dst[7]); - - ASSERT_EQ(true, ex.IsGood()); - ASSERT_EQ(2*kValidHexPairs, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(4u, ex.GetBytesLeft()); - ASSERT_EQ('x', *ex.Peek()); -} - -TEST_F(StringExtractorTest, GetHexBytesAvail_FullString) -{ - const char kHexEncodedBytes[] = "abcdef0123456789"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[kValidHexPairs]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); - EXPECT_EQ(0x89, dst[7]); -} - -TEST_F(StringExtractorTest, GetHexBytesAvail_OddPair) -{ - const char kHexEncodedBytes[] = "abcdef012345678w"; - const size_t kValidHexPairs = 7; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[8]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); -} - - -TEST_F(StringExtractorTest, GetHexBytesAvail_OddPair2) -{ - const char kHexEncodedBytes[] = "abcdef012345678"; - const size_t kValidHexPairs = 7; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[8]; - ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); - EXPECT_EQ(0xab, dst[0]); - EXPECT_EQ(0xcd, dst[1]); - EXPECT_EQ(0xef, dst[2]); - EXPECT_EQ(0x01, dst[3]); - EXPECT_EQ(0x23, dst[4]); - EXPECT_EQ(0x45, dst[5]); - EXPECT_EQ(0x67, dst[6]); -} - -TEST_F (StringExtractorTest, GetHexBytesAvail_Underflow) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kValidHexPairs = 8; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[12]; - memset(dst, 0xef, sizeof(dst)); - ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail (dst)); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - EXPECT_EQ(0x23,dst[4]); - EXPECT_EQ(0x45,dst[5]); - EXPECT_EQ(0x67,dst[6]); - EXPECT_EQ(0x89,dst[7]); - // these bytes should be unchanged - EXPECT_EQ(0xef,dst[8]); - EXPECT_EQ(0xef,dst[9]); - EXPECT_EQ(0xef,dst[10]); - EXPECT_EQ(0xef,dst[11]); - - ASSERT_EQ(true, ex.IsGood()); - ASSERT_EQ(kValidHexPairs*2, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(4u, ex.GetBytesLeft()); - ASSERT_EQ('x', *ex.Peek()); -} - -TEST_F (StringExtractorTest, GetHexBytesAvail_Partial) -{ - const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; - const size_t kReadBytes = 4; - StringExtractor ex(kHexEncodedBytes); - - uint8_t dst[12]; - memset(dst, 0xab, sizeof(dst)); - ASSERT_EQ(kReadBytes, ex.GetHexBytesAvail (llvm::MutableArrayRef<uint8_t>(dst, kReadBytes))); - EXPECT_EQ(0xab,dst[0]); - EXPECT_EQ(0xcd,dst[1]); - EXPECT_EQ(0xef,dst[2]); - EXPECT_EQ(0x01,dst[3]); - // these bytes should be unchanged - EXPECT_EQ(0xab,dst[4]); - EXPECT_EQ(0xab,dst[5]); - EXPECT_EQ(0xab,dst[6]); - EXPECT_EQ(0xab,dst[7]); - EXPECT_EQ(0xab,dst[8]); - EXPECT_EQ(0xab,dst[9]); - EXPECT_EQ(0xab,dst[10]); - EXPECT_EQ(0xab,dst[11]); - - ASSERT_EQ(true, ex.IsGood()); - ASSERT_EQ(kReadBytes*2, ex.GetFilePos()); - ASSERT_EQ(false, ex.Empty()); - ASSERT_EQ(12u, ex.GetBytesLeft()); - ASSERT_EQ('2', *ex.Peek()); -} - -TEST_F(StringExtractorTest, GetNameColonValueSuccess) -{ - const char kNameColonPairs[] = "key1:value1;key2:value2;"; - StringExtractor ex(kNameColonPairs); - - llvm::StringRef name; - llvm::StringRef value; - EXPECT_TRUE(ex.GetNameColonValue(name, value)); - EXPECT_EQ("key1", name); - EXPECT_EQ("value1", value); - EXPECT_TRUE(ex.GetNameColonValue(name, value)); - EXPECT_EQ("key2", name); - EXPECT_EQ("value2", value); - EXPECT_EQ(0, ex.GetBytesLeft()); -} - - -TEST_F(StringExtractorTest, GetNameColonValueContainsColon) -{ - const char kNameColonPairs[] = "key1:value1:value2;key2:value3;"; - StringExtractor ex(kNameColonPairs); - - llvm::StringRef name; - llvm::StringRef value; - EXPECT_TRUE(ex.GetNameColonValue(name, value)); - EXPECT_EQ("key1", name); - EXPECT_EQ("value1:value2", value); - EXPECT_TRUE(ex.GetNameColonValue(name, value)); - EXPECT_EQ("key2", name); - EXPECT_EQ("value3", value); - EXPECT_EQ(0, ex.GetBytesLeft()); -} - -TEST_F(StringExtractorTest, GetNameColonValueNoSemicolon) -{ - const char kNameColonPairs[] = "key1:value1"; - StringExtractor ex(kNameColonPairs); + ASSERT_EQ(0xab, ex.GetHexU8(0xab)); + ASSERT_EQ(false, ex.IsGood()); + ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); + ASSERT_EQ(true, ex.Empty()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} - llvm::StringRef name; - llvm::StringRef value; - EXPECT_FALSE(ex.GetNameColonValue(name, value)); - EXPECT_EQ(0, ex.GetBytesLeft()); -} +TEST_F(StringExtractorTest, GetHexU8_Underflow2) { + const char kOneNibble[] = "1"; + StringExtractor ex(kOneNibble); + + ASSERT_EQ(0xbc, ex.GetHexU8(0xbc)); + ASSERT_EQ(false, ex.IsGood()); + ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_InvalidHex) { + const char kInvalidHex[] = "xx"; + StringExtractor ex(kInvalidHex); + + ASSERT_EQ(0xcd, ex.GetHexU8(0xcd)); + ASSERT_EQ(false, ex.IsGood()); + ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Exact) { + const char kValidHexPair[] = "12"; + StringExtractor ex(kValidHexPair); + + ASSERT_EQ(0x12, ex.GetHexU8(0x12)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Extra) { + const char kValidHexPair[] = "1234"; + StringExtractor ex(kValidHexPair); + + ASSERT_EQ(0x12, ex.GetHexU8(0x12)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('3', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Underflow_NoEof) { + const char kEmptyString[] = ""; + StringExtractor ex(kEmptyString); + const bool kSetEofOnFail = false; + + ASSERT_EQ(0xab, ex.GetHexU8(0xab, kSetEofOnFail)); + ASSERT_EQ(false, ex.IsGood()); // this result seems inconsistent with + // kSetEofOnFail == false + ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); + ASSERT_EQ(true, ex.Empty()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Underflow2_NoEof) { + const char kOneNibble[] = "1"; + StringExtractor ex(kOneNibble); + const bool kSetEofOnFail = false; + + ASSERT_EQ(0xbc, ex.GetHexU8(0xbc, kSetEofOnFail)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(1u, ex.GetBytesLeft()); + ASSERT_EQ('1', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_InvalidHex_NoEof) { + const char kInvalidHex[] = "xx"; + StringExtractor ex(kInvalidHex); + const bool kSetEofOnFail = false; + + ASSERT_EQ(0xcd, ex.GetHexU8(0xcd, kSetEofOnFail)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(0u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('x', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Exact_NoEof) { + const char kValidHexPair[] = "12"; + StringExtractor ex(kValidHexPair); + const bool kSetEofOnFail = false; + + ASSERT_EQ(0x12, ex.GetHexU8(0x12, kSetEofOnFail)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(nullptr, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexU8_Extra_NoEof) { + const char kValidHexPair[] = "1234"; + StringExtractor ex(kValidHexPair); + const bool kSetEofOnFail = false; + + ASSERT_EQ(0x12, ex.GetHexU8(0x12, kSetEofOnFail)); + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2u, ex.GetFilePos()); + ASSERT_EQ(2u, ex.GetBytesLeft()); + ASSERT_EQ('3', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytes) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[kValidHexPairs]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2 * kValidHexPairs, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(4u, ex.GetBytesLeft()); + ASSERT_EQ('x', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytes_FullString) { + const char kHexEncodedBytes[] = "abcdef0123456789"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[kValidHexPairs]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); +} + +TEST_F(StringExtractorTest, GetHexBytes_OddPair) { + const char kHexEncodedBytes[] = "abcdef012345678w"; + const size_t kValidHexPairs = 7; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[8]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + + // This one should be invalid + EXPECT_EQ(0xde, dst[7]); +} + +TEST_F(StringExtractorTest, GetHexBytes_OddPair2) { + const char kHexEncodedBytes[] = "abcdef012345678"; + const size_t kValidHexPairs = 7; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[8]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + + EXPECT_EQ(0xde, dst[7]); +} + +TEST_F(StringExtractorTest, GetHexBytes_Underflow) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[12]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytes(dst, 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); + // these bytes should be filled with fail_fill_value 0xde + EXPECT_EQ(0xde, dst[8]); + EXPECT_EQ(0xde, dst[9]); + EXPECT_EQ(0xde, dst[10]); + EXPECT_EQ(0xde, dst[11]); + + ASSERT_EQ(false, ex.IsGood()); + ASSERT_EQ(UINT64_MAX, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(0u, ex.GetBytesLeft()); + ASSERT_EQ(0, ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytes_Partial) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kReadBytes = 4; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[12]; + memset(dst, 0xab, sizeof(dst)); + ASSERT_EQ( + kReadBytes, + ex.GetHexBytes(llvm::MutableArrayRef<uint8_t>(dst, kReadBytes), 0xde)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + // these bytes should be unchanged + EXPECT_EQ(0xab, dst[4]); + EXPECT_EQ(0xab, dst[5]); + EXPECT_EQ(0xab, dst[6]); + EXPECT_EQ(0xab, dst[7]); + EXPECT_EQ(0xab, dst[8]); + EXPECT_EQ(0xab, dst[9]); + EXPECT_EQ(0xab, dst[10]); + EXPECT_EQ(0xab, dst[11]); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(kReadBytes * 2, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(12u, ex.GetBytesLeft()); + ASSERT_EQ('2', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[kValidHexPairs]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(2 * kValidHexPairs, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(4u, ex.GetBytesLeft()); + ASSERT_EQ('x', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail_FullString) { + const char kHexEncodedBytes[] = "abcdef0123456789"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[kValidHexPairs]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail_OddPair) { + const char kHexEncodedBytes[] = "abcdef012345678w"; + const size_t kValidHexPairs = 7; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[8]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail_OddPair2) { + const char kHexEncodedBytes[] = "abcdef012345678"; + const size_t kValidHexPairs = 7; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[8]; + ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail_Underflow) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kValidHexPairs = 8; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[12]; + memset(dst, 0xef, sizeof(dst)); + ASSERT_EQ(kValidHexPairs, ex.GetHexBytesAvail(dst)); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + EXPECT_EQ(0x23, dst[4]); + EXPECT_EQ(0x45, dst[5]); + EXPECT_EQ(0x67, dst[6]); + EXPECT_EQ(0x89, dst[7]); + // these bytes should be unchanged + EXPECT_EQ(0xef, dst[8]); + EXPECT_EQ(0xef, dst[9]); + EXPECT_EQ(0xef, dst[10]); + EXPECT_EQ(0xef, dst[11]); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(kValidHexPairs * 2, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(4u, ex.GetBytesLeft()); + ASSERT_EQ('x', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetHexBytesAvail_Partial) { + const char kHexEncodedBytes[] = "abcdef0123456789xyzw"; + const size_t kReadBytes = 4; + StringExtractor ex(kHexEncodedBytes); + + uint8_t dst[12]; + memset(dst, 0xab, sizeof(dst)); + ASSERT_EQ(kReadBytes, ex.GetHexBytesAvail( + llvm::MutableArrayRef<uint8_t>(dst, kReadBytes))); + EXPECT_EQ(0xab, dst[0]); + EXPECT_EQ(0xcd, dst[1]); + EXPECT_EQ(0xef, dst[2]); + EXPECT_EQ(0x01, dst[3]); + // these bytes should be unchanged + EXPECT_EQ(0xab, dst[4]); + EXPECT_EQ(0xab, dst[5]); + EXPECT_EQ(0xab, dst[6]); + EXPECT_EQ(0xab, dst[7]); + EXPECT_EQ(0xab, dst[8]); + EXPECT_EQ(0xab, dst[9]); + EXPECT_EQ(0xab, dst[10]); + EXPECT_EQ(0xab, dst[11]); + + ASSERT_EQ(true, ex.IsGood()); + ASSERT_EQ(kReadBytes * 2, ex.GetFilePos()); + ASSERT_EQ(false, ex.Empty()); + ASSERT_EQ(12u, ex.GetBytesLeft()); + ASSERT_EQ('2', *ex.Peek()); +} + +TEST_F(StringExtractorTest, GetNameColonValueSuccess) { + const char kNameColonPairs[] = "key1:value1;key2:value2;"; + StringExtractor ex(kNameColonPairs); + + llvm::StringRef name; + llvm::StringRef value; + EXPECT_TRUE(ex.GetNameColonValue(name, value)); + EXPECT_EQ("key1", name); + EXPECT_EQ("value1", value); + EXPECT_TRUE(ex.GetNameColonValue(name, value)); + EXPECT_EQ("key2", name); + EXPECT_EQ("value2", value); + EXPECT_EQ(0, ex.GetBytesLeft()); +} + +TEST_F(StringExtractorTest, GetNameColonValueContainsColon) { + const char kNameColonPairs[] = "key1:value1:value2;key2:value3;"; + StringExtractor ex(kNameColonPairs); + + llvm::StringRef name; + llvm::StringRef value; + EXPECT_TRUE(ex.GetNameColonValue(name, value)); + EXPECT_EQ("key1", name); + EXPECT_EQ("value1:value2", value); + EXPECT_TRUE(ex.GetNameColonValue(name, value)); + EXPECT_EQ("key2", name); + EXPECT_EQ("value3", value); + EXPECT_EQ(0, ex.GetBytesLeft()); +} + +TEST_F(StringExtractorTest, GetNameColonValueNoSemicolon) { + const char kNameColonPairs[] = "key1:value1"; + StringExtractor ex(kNameColonPairs); + + llvm::StringRef name; + llvm::StringRef value; + EXPECT_FALSE(ex.GetNameColonValue(name, value)); + EXPECT_EQ(0, ex.GetBytesLeft()); +} -TEST_F(StringExtractorTest, GetNameColonValueNoColon) -{ - const char kNameColonPairs[] = "key1value1;"; - StringExtractor ex(kNameColonPairs); +TEST_F(StringExtractorTest, GetNameColonValueNoColon) { + const char kNameColonPairs[] = "key1value1;"; + StringExtractor ex(kNameColonPairs); - llvm::StringRef name; - llvm::StringRef value; - EXPECT_FALSE(ex.GetNameColonValue(name, value)); - EXPECT_EQ(0, ex.GetBytesLeft()); + llvm::StringRef name; + llvm::StringRef value; + EXPECT_FALSE(ex.GetNameColonValue(name, value)); + EXPECT_EQ(0, ex.GetBytesLeft()); } -TEST_F(StringExtractorTest, GetU32LittleEndian) -{ - StringExtractor ex(""); - EXPECT_EQ(0x0, ex.GetHexMaxU32(true, 0)); +TEST_F(StringExtractorTest, GetU32LittleEndian) { + StringExtractor ex(""); + EXPECT_EQ(0x0, ex.GetHexMaxU32(true, 0)); - ex.Reset("0"); - EXPECT_EQ(0x0, ex.GetHexMaxU32(true, 1)); + ex.Reset("0"); + EXPECT_EQ(0x0, ex.GetHexMaxU32(true, 1)); - ex.Reset("1"); - EXPECT_EQ(0x1, ex.GetHexMaxU32(true, 0)); + ex.Reset("1"); + EXPECT_EQ(0x1, ex.GetHexMaxU32(true, 0)); - ex.Reset("01"); - EXPECT_EQ(0x1, ex.GetHexMaxU32(true, 0)); + ex.Reset("01"); + EXPECT_EQ(0x1, ex.GetHexMaxU32(true, 0)); - ex.Reset("001"); - EXPECT_EQ(0x100, ex.GetHexMaxU32(true, 0)); + ex.Reset("001"); + EXPECT_EQ(0x100, ex.GetHexMaxU32(true, 0)); - ex.Reset("12"); - EXPECT_EQ(0x12, ex.GetHexMaxU32(true, 0)); + ex.Reset("12"); + EXPECT_EQ(0x12, ex.GetHexMaxU32(true, 0)); - ex.Reset("123"); - EXPECT_EQ(0x312, ex.GetHexMaxU32(true, 0)); + ex.Reset("123"); + EXPECT_EQ(0x312, ex.GetHexMaxU32(true, 0)); - ex.Reset("1203"); - EXPECT_EQ(0x312, ex.GetHexMaxU32(true, 0)); + ex.Reset("1203"); + EXPECT_EQ(0x312, ex.GetHexMaxU32(true, 0)); - ex.Reset("1234"); - EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); + ex.Reset("1234"); + EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); - ex.Reset("12340"); - EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); + ex.Reset("12340"); + EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); - ex.Reset("123400"); - EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); + ex.Reset("123400"); + EXPECT_EQ(0x3412, ex.GetHexMaxU32(true, 0)); - ex.Reset("12345670"); - EXPECT_EQ(0x70563412, ex.GetHexMaxU32(true, 0)); + ex.Reset("12345670"); + EXPECT_EQ(0x70563412, ex.GetHexMaxU32(true, 0)); - ex.Reset("123456701"); - EXPECT_EQ(0, ex.GetHexMaxU32(true, 0)); + ex.Reset("123456701"); + EXPECT_EQ(0, ex.GetHexMaxU32(true, 0)); } -TEST_F(StringExtractorTest, GetU32BigEndian) -{ - StringExtractor ex(""); - EXPECT_EQ(0x0, ex.GetHexMaxU32(false, 0)); +TEST_F(StringExtractorTest, GetU32BigEndian) { + StringExtractor ex(""); + EXPECT_EQ(0x0, ex.GetHexMaxU32(false, 0)); - ex.Reset("0"); - EXPECT_EQ(0x0, ex.GetHexMaxU32(false, 1)); + ex.Reset("0"); + EXPECT_EQ(0x0, ex.GetHexMaxU32(false, 1)); - ex.Reset("1"); - EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); + ex.Reset("1"); + EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); - ex.Reset("01"); - EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); + ex.Reset("01"); + EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); - ex.Reset("001"); - EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); + ex.Reset("001"); + EXPECT_EQ(0x1, ex.GetHexMaxU32(false, 0)); - ex.Reset("12"); - EXPECT_EQ(0x12, ex.GetHexMaxU32(false, 0)); + ex.Reset("12"); + EXPECT_EQ(0x12, ex.GetHexMaxU32(false, 0)); - ex.Reset("123"); - EXPECT_EQ(0x123, ex.GetHexMaxU32(false, 0)); + ex.Reset("123"); + EXPECT_EQ(0x123, ex.GetHexMaxU32(false, 0)); - ex.Reset("1203"); - EXPECT_EQ(0x1203, ex.GetHexMaxU32(false, 0)); + ex.Reset("1203"); + EXPECT_EQ(0x1203, ex.GetHexMaxU32(false, 0)); - ex.Reset("1234"); - EXPECT_EQ(0x1234, ex.GetHexMaxU32(false, 0)); + ex.Reset("1234"); + EXPECT_EQ(0x1234, ex.GetHexMaxU32(false, 0)); - ex.Reset("12340"); - EXPECT_EQ(0x12340, ex.GetHexMaxU32(false, 0)); + ex.Reset("12340"); + EXPECT_EQ(0x12340, ex.GetHexMaxU32(false, 0)); - ex.Reset("123400"); - EXPECT_EQ(0x123400, ex.GetHexMaxU32(false, 0)); + ex.Reset("123400"); + EXPECT_EQ(0x123400, ex.GetHexMaxU32(false, 0)); - ex.Reset("12345670"); - EXPECT_EQ(0x12345670, ex.GetHexMaxU32(false, 0)); + ex.Reset("12345670"); + EXPECT_EQ(0x12345670, ex.GetHexMaxU32(false, 0)); - ex.Reset("123456700"); - EXPECT_EQ(0, ex.GetHexMaxU32(false, 0)); + ex.Reset("123456700"); + EXPECT_EQ(0, ex.GetHexMaxU32(false, 0)); } -TEST_F(StringExtractorTest, GetU64LittleEndian) -{ - StringExtractor ex(""); - EXPECT_EQ(0x0, ex.GetHexMaxU64(true, 0)); +TEST_F(StringExtractorTest, GetU64LittleEndian) { + StringExtractor ex(""); + EXPECT_EQ(0x0, ex.GetHexMaxU64(true, 0)); - ex.Reset("0"); - EXPECT_EQ(0x0, ex.GetHexMaxU64(true, 1)); + ex.Reset("0"); + EXPECT_EQ(0x0, ex.GetHexMaxU64(true, 1)); - ex.Reset("1"); - EXPECT_EQ(0x1, ex.GetHexMaxU64(true, 0)); + ex.Reset("1"); + EXPECT_EQ(0x1, ex.GetHexMaxU64(true, 0)); - ex.Reset("01"); - EXPECT_EQ(0x1, ex.GetHexMaxU64(true, 0)); + ex.Reset("01"); + EXPECT_EQ(0x1, ex.GetHexMaxU64(true, 0)); - ex.Reset("001"); - EXPECT_EQ(0x100, ex.GetHexMaxU64(true, 0)); + ex.Reset("001"); + EXPECT_EQ(0x100, ex.GetHexMaxU64(true, 0)); - ex.Reset("12"); - EXPECT_EQ(0x12, ex.GetHexMaxU64(true, 0)); + ex.Reset("12"); + EXPECT_EQ(0x12, ex.GetHexMaxU64(true, 0)); - ex.Reset("123"); - EXPECT_EQ(0x312, ex.GetHexMaxU64(true, 0)); + ex.Reset("123"); + EXPECT_EQ(0x312, ex.GetHexMaxU64(true, 0)); - ex.Reset("1203"); - EXPECT_EQ(0x312, ex.GetHexMaxU64(true, 0)); + ex.Reset("1203"); + EXPECT_EQ(0x312, ex.GetHexMaxU64(true, 0)); - ex.Reset("1234"); - EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); + ex.Reset("1234"); + EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); - ex.Reset("12340"); - EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); + ex.Reset("12340"); + EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); - ex.Reset("123400"); - EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); + ex.Reset("123400"); + EXPECT_EQ(0x3412, ex.GetHexMaxU64(true, 0)); - ex.Reset("123456789ABCDEF0"); - EXPECT_EQ(0xF0DEBC9A78563412ULL, ex.GetHexMaxU64(true, 0)); + ex.Reset("123456789ABCDEF0"); + EXPECT_EQ(0xF0DEBC9A78563412ULL, ex.GetHexMaxU64(true, 0)); - ex.Reset("123456789ABCDEF01"); - EXPECT_EQ(0, ex.GetHexMaxU64(true, 0)); + ex.Reset("123456789ABCDEF01"); + EXPECT_EQ(0, ex.GetHexMaxU64(true, 0)); } -TEST_F(StringExtractorTest, GetU64BigEndian) -{ - StringExtractor ex(""); - EXPECT_EQ(0x0, ex.GetHexMaxU64(false, 0)); +TEST_F(StringExtractorTest, GetU64BigEndian) { + StringExtractor ex(""); + EXPECT_EQ(0x0, ex.GetHexMaxU64(false, 0)); - ex.Reset("0"); - EXPECT_EQ(0x0, ex.GetHexMaxU64(false, 1)); + ex.Reset("0"); + EXPECT_EQ(0x0, ex.GetHexMaxU64(false, 1)); - ex.Reset("1"); - EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); + ex.Reset("1"); + EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); - ex.Reset("01"); - EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); + ex.Reset("01"); + EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); - ex.Reset("001"); - EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); + ex.Reset("001"); + EXPECT_EQ(0x1, ex.GetHexMaxU64(false, 0)); - ex.Reset("12"); - EXPECT_EQ(0x12, ex.GetHexMaxU64(false, 0)); + ex.Reset("12"); + EXPECT_EQ(0x12, ex.GetHexMaxU64(false, 0)); - ex.Reset("123"); - EXPECT_EQ(0x123, ex.GetHexMaxU64(false, 0)); + ex.Reset("123"); + EXPECT_EQ(0x123, ex.GetHexMaxU64(false, 0)); - ex.Reset("1203"); - EXPECT_EQ(0x1203, ex.GetHexMaxU64(false, 0)); + ex.Reset("1203"); + EXPECT_EQ(0x1203, ex.GetHexMaxU64(false, 0)); - ex.Reset("1234"); - EXPECT_EQ(0x1234, ex.GetHexMaxU64(false, 0)); + ex.Reset("1234"); + EXPECT_EQ(0x1234, ex.GetHexMaxU64(false, 0)); - ex.Reset("12340"); - EXPECT_EQ(0x12340, ex.GetHexMaxU64(false, 0)); + ex.Reset("12340"); + EXPECT_EQ(0x12340, ex.GetHexMaxU64(false, 0)); - ex.Reset("123400"); - EXPECT_EQ(0x123400, ex.GetHexMaxU64(false, 0)); + ex.Reset("123400"); + EXPECT_EQ(0x123400, ex.GetHexMaxU64(false, 0)); - ex.Reset("123456789ABCDEF0"); - EXPECT_EQ(0x123456789ABCDEF0ULL, ex.GetHexMaxU64(false, 0)); + ex.Reset("123456789ABCDEF0"); + EXPECT_EQ(0x123456789ABCDEF0ULL, ex.GetHexMaxU64(false, 0)); - ex.Reset("123456789ABCDEF000"); - EXPECT_EQ(0, ex.GetHexMaxU64(false, 0)); + ex.Reset("123456789ABCDEF000"); + EXPECT_EQ(0, ex.GetHexMaxU64(false, 0)); } diff --git a/lldb/unittests/Utility/TaskPoolTest.cpp b/lldb/unittests/Utility/TaskPoolTest.cpp index 24431e2c789..172e32a9c6c 100644 --- a/lldb/unittests/Utility/TaskPoolTest.cpp +++ b/lldb/unittests/Utility/TaskPoolTest.cpp @@ -2,61 +2,53 @@ #include "lldb/Utility/TaskPool.h" -TEST (TaskPoolTest, AddTask) -{ - auto fn = [](int x) { return x * x + 1; }; - - auto f1 = TaskPool::AddTask(fn, 1); - auto f2 = TaskPool::AddTask(fn, 2); - auto f3 = TaskPool::AddTask(fn, 3); - auto f4 = TaskPool::AddTask(fn, 4); - - ASSERT_EQ (10, f3.get()); - ASSERT_EQ ( 2, f1.get()); - ASSERT_EQ (17, f4.get()); - ASSERT_EQ ( 5, f2.get()); +TEST(TaskPoolTest, AddTask) { + auto fn = [](int x) { return x * x + 1; }; + + auto f1 = TaskPool::AddTask(fn, 1); + auto f2 = TaskPool::AddTask(fn, 2); + auto f3 = TaskPool::AddTask(fn, 3); + auto f4 = TaskPool::AddTask(fn, 4); + + ASSERT_EQ(10, f3.get()); + ASSERT_EQ(2, f1.get()); + ASSERT_EQ(17, f4.get()); + ASSERT_EQ(5, f2.get()); } -TEST (TaskPoolTest, RunTasks) -{ - std::vector<int> r(4); - - auto fn = [](int x, int& y) { y = x * x + 1; }; - - TaskPool::RunTasks( - [fn, &r]() { fn(1, r[0]); }, - [fn, &r]() { fn(2, r[1]); }, - [fn, &r]() { fn(3, r[2]); }, - [fn, &r]() { fn(4, r[3]); } - ); - - ASSERT_EQ ( 2, r[0]); - ASSERT_EQ ( 5, r[1]); - ASSERT_EQ (10, r[2]); - ASSERT_EQ (17, r[3]); +TEST(TaskPoolTest, RunTasks) { + std::vector<int> r(4); + + auto fn = [](int x, int &y) { y = x * x + 1; }; + + TaskPool::RunTasks([fn, &r]() { fn(1, r[0]); }, [fn, &r]() { fn(2, r[1]); }, + [fn, &r]() { fn(3, r[2]); }, [fn, &r]() { fn(4, r[3]); }); + + ASSERT_EQ(2, r[0]); + ASSERT_EQ(5, r[1]); + ASSERT_EQ(10, r[2]); + ASSERT_EQ(17, r[3]); } -TEST (TaskPoolTest, TaskRunner) -{ - auto fn = [](int x) { return std::make_pair(x, x * x); }; - - TaskRunner<std::pair<int, int>> tr; - tr.AddTask(fn, 1); - tr.AddTask(fn, 2); - tr.AddTask(fn, 3); - tr.AddTask(fn, 4); - - int count = 0; - while (true) - { - auto f = tr.WaitForNextCompletedTask(); - if (!f.valid()) - break; - - ++count; - std::pair<int, int> v = f.get(); - ASSERT_EQ (v.first * v.first, v.second); - } - - ASSERT_EQ(4, count); +TEST(TaskPoolTest, TaskRunner) { + auto fn = [](int x) { return std::make_pair(x, x * x); }; + + TaskRunner<std::pair<int, int>> tr; + tr.AddTask(fn, 1); + tr.AddTask(fn, 2); + tr.AddTask(fn, 3); + tr.AddTask(fn, 4); + + int count = 0; + while (true) { + auto f = tr.WaitForNextCompletedTask(); + if (!f.valid()) + break; + + ++count; + std::pair<int, int> v = f.get(); + ASSERT_EQ(v.first * v.first, v.second); + } + + ASSERT_EQ(4, count); } diff --git a/lldb/unittests/Utility/UriParserTest.cpp b/lldb/unittests/Utility/UriParserTest.cpp index fe0a6a70f21..2fd1960c0f0 100644 --- a/lldb/unittests/Utility/UriParserTest.cpp +++ b/lldb/unittests/Utility/UriParserTest.cpp @@ -1,159 +1,135 @@ -#include "gtest/gtest.h" #include "Utility/UriParser.h" +#include "gtest/gtest.h" -namespace -{ - class UriParserTest: public ::testing::Test - { - }; +namespace { +class UriParserTest : public ::testing::Test {}; } // result strings (scheme/hostname/port/path) passed into UriParser::Parse -// are initialized to kAsdf so we can verify that they are unmodified if the +// are initialized to kAsdf so we can verify that they are unmodified if the // URI is invalid -static const char* kAsdf = "asdf"; +static const char *kAsdf = "asdf"; -class UriTestCase -{ +class UriTestCase { public: - UriTestCase(const char* uri, const char* scheme, const char* hostname, int port, const char* path) : - m_uri(uri), - m_result(true), - m_scheme(scheme), - m_hostname(hostname), - m_port(port), - m_path(path) - { - } - - UriTestCase(const char* uri) : - m_uri(uri), - m_result(false), - m_scheme(kAsdf), - m_hostname(kAsdf), - m_port(1138), - m_path(kAsdf) - { - } - - const char* m_uri; - bool m_result; - const char* m_scheme; - const char* m_hostname; - int m_port; - const char* m_path; + UriTestCase(const char *uri, const char *scheme, const char *hostname, + int port, const char *path) + : m_uri(uri), m_result(true), m_scheme(scheme), m_hostname(hostname), + m_port(port), m_path(path) {} + + UriTestCase(const char *uri) + : m_uri(uri), m_result(false), m_scheme(kAsdf), m_hostname(kAsdf), + m_port(1138), m_path(kAsdf) {} + + const char *m_uri; + bool m_result; + const char *m_scheme; + const char *m_hostname; + int m_port; + const char *m_path; }; -#define VALIDATE \ - std::string scheme(kAsdf); \ - std::string hostname(kAsdf); \ - int port(1138); \ - std::string path(kAsdf); \ - EXPECT_EQ (testCase.m_result, UriParser::Parse(testCase.m_uri, scheme, hostname, port, path)); \ - EXPECT_STREQ (testCase.m_scheme, scheme.c_str()); \ - EXPECT_STREQ (testCase.m_hostname, hostname.c_str()); \ - EXPECT_EQ (testCase.m_port, port); \ - EXPECT_STREQ (testCase.m_path, path.c_str()); +#define VALIDATE \ + std::string scheme(kAsdf); \ + std::string hostname(kAsdf); \ + int port(1138); \ + std::string path(kAsdf); \ + EXPECT_EQ(testCase.m_result, \ + UriParser::Parse(testCase.m_uri, scheme, hostname, port, path)); \ + EXPECT_STREQ(testCase.m_scheme, scheme.c_str()); \ + EXPECT_STREQ(testCase.m_hostname, hostname.c_str()); \ + EXPECT_EQ(testCase.m_port, port); \ + EXPECT_STREQ(testCase.m_path, path.c_str()); -TEST_F (UriParserTest, Minimal) -{ - const UriTestCase testCase("x://y", "x", "y", -1, "/"); - VALIDATE +TEST_F(UriParserTest, Minimal) { + const UriTestCase testCase("x://y", "x", "y", -1, "/"); + VALIDATE } -TEST_F (UriParserTest, MinimalPort) -{ - const UriTestCase testCase("x://y:1", "x", "y", 1, "/"); - VALIDATE +TEST_F(UriParserTest, MinimalPort) { + const UriTestCase testCase("x://y:1", "x", "y", 1, "/"); + VALIDATE } -TEST_F (UriParserTest, MinimalPath) -{ - const UriTestCase testCase("x://y/", "x", "y", -1, "/"); - VALIDATE +TEST_F(UriParserTest, MinimalPath) { + const UriTestCase testCase("x://y/", "x", "y", -1, "/"); + VALIDATE } -TEST_F (UriParserTest, MinimalPortPath) -{ - const UriTestCase testCase("x://y:1/", "x", "y", 1, "/"); - VALIDATE +TEST_F(UriParserTest, MinimalPortPath) { + const UriTestCase testCase("x://y:1/", "x", "y", 1, "/"); + VALIDATE } -TEST_F (UriParserTest, LongPath) -{ - const UriTestCase testCase("x://y/abc/def/xyz", "x", "y", -1, "/abc/def/xyz"); - VALIDATE +TEST_F(UriParserTest, LongPath) { + const UriTestCase testCase("x://y/abc/def/xyz", "x", "y", -1, "/abc/def/xyz"); + VALIDATE } -TEST_F (UriParserTest, TypicalPortPath) -{ - const UriTestCase testCase("connect://192.168.100.132:5432/", "connect", "192.168.100.132", 5432, "/"); - VALIDATE +TEST_F(UriParserTest, TypicalPortPath) { + const UriTestCase testCase("connect://192.168.100.132:5432/", "connect", + "192.168.100.132", 5432, "/"); + VALIDATE } -TEST_F (UriParserTest, BracketedHostnamePort) -{ - const UriTestCase testCase("connect://[192.168.100.132]:5432/", "connect", "192.168.100.132", 5432, "/"); - VALIDATE +TEST_F(UriParserTest, BracketedHostnamePort) { + const UriTestCase testCase("connect://[192.168.100.132]:5432/", "connect", + "192.168.100.132", 5432, "/"); + VALIDATE } -TEST_F (UriParserTest, BracketedHostname) -{ - const UriTestCase testCase("connect://[192.168.100.132]", "connect", "192.168.100.132", -1, "/"); - VALIDATE +TEST_F(UriParserTest, BracketedHostname) { + const UriTestCase testCase("connect://[192.168.100.132]", "connect", + "192.168.100.132", -1, "/"); + VALIDATE } -TEST_F (UriParserTest, BracketedHostnameWithColon) -{ - const UriTestCase testCase("connect://[192.168.100.132:5555]:1234", "connect", "192.168.100.132:5555", 1234, "/"); - VALIDATE +TEST_F(UriParserTest, BracketedHostnameWithColon) { + const UriTestCase testCase("connect://[192.168.100.132:5555]:1234", "connect", + "192.168.100.132:5555", 1234, "/"); + VALIDATE } -TEST_F (UriParserTest, SchemeHostSeparator) -{ - const UriTestCase testCase("x:/y"); - VALIDATE +TEST_F(UriParserTest, SchemeHostSeparator) { + const UriTestCase testCase("x:/y"); + VALIDATE } -TEST_F (UriParserTest, SchemeHostSeparator2) -{ - const UriTestCase testCase("x:y"); - VALIDATE +TEST_F(UriParserTest, SchemeHostSeparator2) { + const UriTestCase testCase("x:y"); + VALIDATE } -TEST_F (UriParserTest, SchemeHostSeparator3) -{ - const UriTestCase testCase("x//y"); - VALIDATE +TEST_F(UriParserTest, SchemeHostSeparator3) { + const UriTestCase testCase("x//y"); + VALIDATE } -TEST_F (UriParserTest, SchemeHostSeparator4) -{ - const UriTestCase testCase("x/y"); - VALIDATE +TEST_F(UriParserTest, SchemeHostSeparator4) { + const UriTestCase testCase("x/y"); + VALIDATE } -TEST_F (UriParserTest, BadPort) -{ - const UriTestCase testCase("x://y:a/"); - VALIDATE +TEST_F(UriParserTest, BadPort) { + const UriTestCase testCase("x://y:a/"); + VALIDATE } -TEST_F (UriParserTest, BadPort2) -{ - const UriTestCase testCase("x://y:5432a/"); - VALIDATE +TEST_F(UriParserTest, BadPort2) { + const UriTestCase testCase("x://y:5432a/"); + VALIDATE } -TEST_F (UriParserTest, Empty) -{ - const UriTestCase testCase(""); - VALIDATE +TEST_F(UriParserTest, Empty) { + const UriTestCase testCase(""); + VALIDATE } -TEST_F (UriParserTest, PortOverflow) -{ - const UriTestCase testCase("x://y:0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789/"); - VALIDATE +TEST_F(UriParserTest, PortOverflow) { + const UriTestCase testCase("x://" + "y:" + "0123456789012345678901234567890123456789012345678" + "9012345678901234567890123456789012345678901234567" + "89/"); + VALIDATE } - diff --git a/lldb/unittests/gtest_common.h b/lldb/unittests/gtest_common.h index 006c9596ca4..c8fe9257594 100644 --- a/lldb/unittests/gtest_common.h +++ b/lldb/unittests/gtest_common.h @@ -17,8 +17,10 @@ // units. Be very leary about putting anything in this file. #if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0) -// Due to a bug in <thread>, when _HAS_EXCEPTIONS == 0 the header will try to call -// uncaught_exception() without having a declaration for it. The fix for this is +// Due to a bug in <thread>, when _HAS_EXCEPTIONS == 0 the header will try to +// call +// uncaught_exception() without having a declaration for it. The fix for this +// is // to manually #include <eh.h>, which contains this declaration. #include <eh.h> #endif |