[Lldb-commits] [lldb] 7208cb1 - [lldb] Remove XFAIL from now passing TestPtrRefs/TestPtreRefsObjC

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Raphael Isemann
Date: 2020-08-15T08:14:44+02:00
New Revision: 7208cb1ac43e4be806bcb91c622fc1f8641e010b

URL: 
https://github.com/llvm/llvm-project/commit/7208cb1ac43e4be806bcb91c622fc1f8641e010b
DIFF: 
https://github.com/llvm/llvm-project/commit/7208cb1ac43e4be806bcb91c622fc1f8641e010b.diff

LOG: [lldb] Remove XFAIL from now passing TestPtrRefs/TestPtreRefsObjC

8fcfe2862fd4fde4793e232cfeebe6c5540c80a5 and
0cceb54366b406649fdfe7bb11b133ab96f3cd70 fixed those tests.

Added: 


Modified: 
lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py

Removed: 




diff  --git a/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py 
b/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
index 6a392a0a756e..96073ea7fa6b 100644
--- a/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
+++ b/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
@@ -15,7 +15,6 @@ class TestPtrRefs(TestBase):
 
 @skipIfAsan # The output looks 
diff erent under ASAN.
 @skipUnlessDarwin
-@expectedFailureAll(oslist=["macosx"], debug_info=["dwarf", "gmodules"], 
bugnumber="llvm.org/pr45112")
 def test_ptr_refs(self):
 """Test format string functionality."""
 self.build()

diff  --git a/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py 
b/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
index ca543eb91967..7767f7b45720 100644
--- a/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
+++ b/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
@@ -15,7 +15,6 @@ class TestPtrRefsObjC(TestBase):
 
 @skipIfAsan # The output looks 
diff erent under ASAN.
 @skipUnlessDarwin
-@expectedFailureAll(oslist=["macosx"], debug_info=["dwarf", "gmodules"], 
bugnumber="llvm.org/pr45112")
 def test_ptr_refs(self):
 """Test the ptr_refs tool on Darwin with Objective-C"""
 self.build()



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D84974: [WIP] Enable Launching the Debugee in VSCode Terminal

2020-08-14 Thread Greg Clayton via Phabricator via lldb-commits
clayborg requested changes to this revision.
clayborg added a comment.
This revision now requires changes to proceed.

So there is a lot of noise in this patch that is just reformatting on code that 
hasn't changed. It would be nice to get rid of any changes that are 
whitespace/indentation/formatting only. Also see inlined comments for needed 
changes.




Comment at: lldb/tools/lldb-vscode/VSCode.cpp:410
+
+VSCode::PacketStatus VSCode::SendReverseRequest(llvm::json::Object &request,
+llvm::json::Object &response) {

add "const" to before "llvm::json::Object &request"



Comment at: lldb/tools/lldb-vscode/VSCode.h:166-173
+  const std::map &GetRequestHandlers();
+
+  PacketStatus GetObject(llvm::json::Object &object);
+  bool HandleObject(const llvm::json::Object &object);
+  PacketStatus SendReverseRequest(llvm::json::Object &request,
+  llvm::json::Object &response);
+

Revert all changes to this function. Seems like there are some forward 
declarations to functions in here for some reason that aren't needed.



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1441
+   llvm::json::Object &launch_response) {
+  // Fill out attach info
+  g_vsc.is_attach = true;

Add more comment here to explain how we are attaching. Maybe something like:
```
// We have already created a target that has a valid "program" path to the 
executable.
// We will attach to the next process whose basename matches that of the 
target's 
// executable by waiting for the next process to launch that matches. This help 
LLDB
// ignore any existing processes that are already running that match this 
executable
// name and wait for the next one to launch.
```



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1448-1449
+  g_vsc.stop_at_entry = true;
+  auto attach_func = [&]() { g_vsc.target.Attach(attach_info, error); };
+  std::thread attacher(attach_func);
+

Inline the lambda, add a comment, and enable async mode to ensure we don't have 
a race condition:

```
// Here we launch a thread to do the attach. We disable async events so
// that when we call g_vsc.target.Attach(...) it will not return unless the 
attach
// succeeds. In the event the attach never happens, the user will be able to hit
// the square stop button in the debug session and it will kill lldb-vscode. If
// this ever changes in the IDE we will need to do more work to ensure we can
// nicely timeout from the attach after a set period of time.
std::thread attacher([&]() { 
   g_vsc.debugger.SetAsync(false);
   g_vsc.target.Attach(attach_info, error); 
   g_vsc.debugger.SetAsync(true);
});
```



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1486-1506
+  if (error.Success()) {
+// IDE doesn't respond back the pid of the target, so lldb can only attach
+// by process name, which is already set up in request_launch().
+auto attached_pid = g_vsc.target.GetProcess().GetProcessID();
+if (attached_pid == LLDB_INVALID_PROCESS_ID) {
+  error.SetErrorString("Failed to attach to a process");
+}

Need to clean up this logic a bit. We have two "if (error.Success())" 
statements and the flow of the code is hard to follow.

```
if (error.Success()) {
  // IDE doesn't respond back the pid of the target from the runInTerminal 
  // response, so we have lldb attach by name and wait, so grab the process
  // ID from the target.
  auto attached_pid = g_vsc.target.GetProcess().GetProcessID();
  if (attached_pid == LLDB_INVALID_PROCESS_ID)
error.SetErrorString("Failed to attach to a process");
  else
SendProcessEvent(Attach);
}

// Check error again as it might have been modified with a new error above.
if (error.Fail()) {
  launch_response["success"] = llvm::json::Value(false);
  EmplaceSafeString(launch_response, "message", 
std::string(error.GetCString()));
} else {
  launch_response["success"] = llvm::json::Value(true);
}

```



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1582-1585
+  if (GetBoolean(arguments, "launchInTerminal", false)) {
+request_runInTerminal(request, response);
+g_vsc.SendJSON(llvm::json::Value(std::move(response)));
   } else {

Remove all new indentation that was added for the else scope and use early 
return:

```
if (GetBoolean(arguments, "launchInTerminal", false)) {
  request_runInTerminal(request, response);
  g_vsc.SendJSON(llvm::json::Value(std::move(response)));
  return;
}
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84974/new/

https://reviews.llvm.org/D84974

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] 0cceb54 - [TestPtrRefsObjC] Prefer `command script import`.

2020-08-14 Thread Davide Italiano via lldb-commits

Author: Davide Italiano
Date: 2020-08-14T15:31:02-07:00
New Revision: 0cceb54366b406649fdfe7bb11b133ab96f3cd70

URL: 
https://github.com/llvm/llvm-project/commit/0cceb54366b406649fdfe7bb11b133ab96f3cd70
DIFF: 
https://github.com/llvm/llvm-project/commit/0cceb54366b406649fdfe7bb11b133ab96f3cd70.diff

LOG: [TestPtrRefsObjC] Prefer `command script import`.

Added: 


Modified: 
lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py

Removed: 




diff  --git a/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py 
b/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
index 390a07c4718a..ca543eb91967 100644
--- a/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
+++ b/lldb/test/API/lang/objc/ptr_refs/TestPtrRefsObjC.py
@@ -44,6 +44,6 @@ def test_ptr_refs(self):
 
 frame = thread.GetFrameAtIndex(0)
 
-self.runCmd("script import lldb.macosx.heap")
+self.runCmd("command script import lldb.macosx.heap")
 self.expect("ptr_refs self", substrs=["malloc", "stack"])
 



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] 8fcfe28 - [TestPtrRefs] Prefer `command script import`.

2020-08-14 Thread Davide Italiano via lldb-commits

Author: Davide Italiano
Date: 2020-08-14T15:30:31-07:00
New Revision: 8fcfe2862fd4fde4793e232cfeebe6c5540c80a5

URL: 
https://github.com/llvm/llvm-project/commit/8fcfe2862fd4fde4793e232cfeebe6c5540c80a5
DIFF: 
https://github.com/llvm/llvm-project/commit/8fcfe2862fd4fde4793e232cfeebe6c5540c80a5.diff

LOG: [TestPtrRefs] Prefer `command script import`.

Added: 


Modified: 
lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py

Removed: 




diff  --git a/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py 
b/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
index 41216bbce2e5..6a392a0a756e 100644
--- a/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
+++ b/lldb/test/API/functionalities/ptr_refs/TestPtrRefs.py
@@ -44,5 +44,5 @@ def test_ptr_refs(self):
 
 frame = thread.GetFrameAtIndex(0)
 
-self.runCmd("script import lldb.macosx.heap")
+self.runCmd("command script import lldb.macosx.heap")
 self.expect("ptr_refs my_ptr", substrs=["malloc", "stack"])



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85993: [lldb] Set the access property on member function decls

2020-08-14 Thread Alexandre Ganea via Phabricator via lldb-commits
aganea added a comment.

LGTM.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85993/new/

https://reviews.llvm.org/D85993

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85993: [lldb] Set the access property on member function decls

2020-08-14 Thread Adrian McCarthy via Phabricator via lldb-commits
amccarth created this revision.
amccarth added reviewers: clayborg, aganea.
amccarth requested review of this revision.

This fixes two failures in the PDB tests.  LLVM has a "sanity" check on 
function decls.  One of the requirements of member functions is that they have 
the access property (public, protected, private) set if the function is a 
member function.  The check is an assert, so you'll see the failure only if 
you're running with assertions enabled.

This sets the access property to public to match how the existing code handles 
member function templates.


https://reviews.llvm.org/D85993

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp


Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2017,6 +2017,12 @@
   func_decl->setHasWrittenPrototype(hasWrittenPrototype);
   func_decl->setConstexprKind(isConstexprSpecified ? CSK_constexpr
: CSK_unspecified);
+  // Functions inside a record need to have an access specifier.  It doesn't
+  // matter what access specifier we give the function as LLDB allows
+  // accessing everything inside a record.
+  if (decl_ctx->isRecord())
+func_decl->setAccess(clang::AccessSpecifier::AS_public);
+
   SetOwningModule(func_decl, owning_module);
   if (func_decl)
 decl_ctx->addDecl(func_decl);


Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2017,6 +2017,12 @@
   func_decl->setHasWrittenPrototype(hasWrittenPrototype);
   func_decl->setConstexprKind(isConstexprSpecified ? CSK_constexpr
: CSK_unspecified);
+  // Functions inside a record need to have an access specifier.  It doesn't
+  // matter what access specifier we give the function as LLDB allows
+  // accessing everything inside a record.
+  if (decl_ctx->isRecord())
+func_decl->setAccess(clang::AccessSpecifier::AS_public);
+
   SetOwningModule(func_decl, owning_module);
   if (func_decl)
 decl_ctx->addDecl(func_decl);
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85988: Fix the ability to list iOS simulator processes.

2020-08-14 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere added a comment.

We should have a few tests that launch a simulator. @aprantl revived them 
recently:

- TestAppleSimulatorOSType.py
- TestSimulatorPlatform.py
- TestIOSSimulator.py


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85988/new/

https://reviews.llvm.org/D85988

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D84974: [WIP] Enable Launching the Debugee in VSCode Terminal

2020-08-14 Thread Yifan Shen via Phabricator via lldb-commits
aelitashen updated this revision to Diff 285727.
aelitashen added a comment.

Remove uncomplete tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84974/new/

https://reviews.llvm.org/D84974

Files:
  lldb/tools/lldb-vscode/VSCode.cpp
  lldb/tools/lldb-vscode/VSCode.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -343,7 +343,7 @@
   char buffer[1024];
   size_t count;
   while ((count = process.GetSTDOUT(buffer, sizeof(buffer))) > 0)
-  g_vsc.SendOutput(OutputType::Stdout, llvm::StringRef(buffer, count));
+g_vsc.SendOutput(OutputType::Stdout, llvm::StringRef(buffer, count));
   while ((count = process.GetSTDERR(buffer, sizeof(buffer))) > 0)
 g_vsc.SendOutput(OutputType::Stderr, llvm::StringRef(buffer, count));
 }
@@ -448,10 +448,10 @@
 if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded) {
   body.try_emplace("reason", "new");
 } else if (event_mask &
-lldb::SBTarget::eBroadcastBitModulesUnloaded) {
+   lldb::SBTarget::eBroadcastBitModulesUnloaded) {
   body.try_emplace("reason", "removed");
 } else if (event_mask &
-lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
+   lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
   body.try_emplace("reason", "changed");
 }
 body.try_emplace("module", module_value);
@@ -873,7 +873,9 @@
 // "CompletionsRequest": {
 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
 // "type": "object",
-// "description": "Returns a list of possible completions for a given caret position and text.\nThe CompletionsRequest may only be called if the 'supportsCompletionsRequest' capability exists and is true.",
+// "description": "Returns a list of possible completions for a given caret
+// position and text.\nThe CompletionsRequest may only be called if the
+// 'supportsCompletionsRequest' capability exists and is true.",
 // "properties": {
 //   "command": {
 // "type": "string",
@@ -892,19 +894,23 @@
 //   "properties": {
 // "frameId": {
 //   "type": "integer",
-//   "description": "Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope."
+//   "description": "Returns completions in the scope of this stack frame.
+//   If not specified, the completions are returned for the global scope."
 // },
 // "text": {
 //   "type": "string",
-//   "description": "One or more source lines. Typically this is the text a user has typed into the debug console before he asked for completion."
+//   "description": "One or more source lines. Typically this is the text a
+//   user has typed into the debug console before he asked for completion."
 // },
 // "column": {
 //   "type": "integer",
-//   "description": "The character position for which to determine the completion proposals."
+//   "description": "The character position for which to determine the
+//   completion proposals."
 // },
 // "line": {
 //   "type": "integer",
-//   "description": "An optional line for which to determine the completion proposals. If missing the first line of the text is assumed."
+//   "description": "An optional line for which to determine the completion
+//   proposals. If missing the first line of the text is assumed."
 // }
 //   },
 //   "required": [ "text", "column" ]
@@ -933,39 +939,51 @@
 // },
 // "CompletionItem": {
 //   "type": "object",
-//   "description": "CompletionItems are the suggestions returned from the CompletionsRequest.",
-//   "properties": {
+//   "description": "CompletionItems are the suggestions returned from the
+//   CompletionsRequest.", "properties": {
 // "label": {
 //   "type": "string",
-//   "description": "The label of this completion item. By default this is also the text that is inserted when selecting this completion."
+//   "description": "The label of this completion item. By default this is
+//   also the text that is inserted when selecting this completion."
 // },
 // "text": {
 //   "type": "string",
-//   "description": "If text is not falsy then it is inserted instead of the label."
+//   "description": "If text is not falsy then it is inserted instead of the
+//   label."
 // },
 // "sortText": {
 //   "type": "string",
-//   "description": "A string that should be used when comparing this item with other items. When `falsy` the label is used."
+//   "description": "A string that should be used when comparing this item
+//   with other items. When `falsy` the label

[Lldb-commits] [PATCH] D84974: [WIP] Enable Launching the Debugee in VSCode Terminal

2020-08-14 Thread Yifan Shen via Phabricator via lldb-commits
aelitashen updated this revision to Diff 285725.
aelitashen added a comment.

Add a attacher thread to avoid race condition


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84974/new/

https://reviews.llvm.org/D84974

Files:
  lldb/test/API/tools/lldb-vscode/runInTerminal/Makefile
  lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
  lldb/test/API/tools/lldb-vscode/runInTerminal/main.cpp
  lldb/tools/lldb-vscode/VSCode.cpp
  lldb/tools/lldb-vscode/VSCode.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -343,7 +343,7 @@
   char buffer[1024];
   size_t count;
   while ((count = process.GetSTDOUT(buffer, sizeof(buffer))) > 0)
-  g_vsc.SendOutput(OutputType::Stdout, llvm::StringRef(buffer, count));
+g_vsc.SendOutput(OutputType::Stdout, llvm::StringRef(buffer, count));
   while ((count = process.GetSTDERR(buffer, sizeof(buffer))) > 0)
 g_vsc.SendOutput(OutputType::Stderr, llvm::StringRef(buffer, count));
 }
@@ -448,10 +448,10 @@
 if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded) {
   body.try_emplace("reason", "new");
 } else if (event_mask &
-lldb::SBTarget::eBroadcastBitModulesUnloaded) {
+   lldb::SBTarget::eBroadcastBitModulesUnloaded) {
   body.try_emplace("reason", "removed");
 } else if (event_mask &
-lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
+   lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
   body.try_emplace("reason", "changed");
 }
 body.try_emplace("module", module_value);
@@ -873,7 +873,9 @@
 // "CompletionsRequest": {
 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
 // "type": "object",
-// "description": "Returns a list of possible completions for a given caret position and text.\nThe CompletionsRequest may only be called if the 'supportsCompletionsRequest' capability exists and is true.",
+// "description": "Returns a list of possible completions for a given caret
+// position and text.\nThe CompletionsRequest may only be called if the
+// 'supportsCompletionsRequest' capability exists and is true.",
 // "properties": {
 //   "command": {
 // "type": "string",
@@ -892,19 +894,23 @@
 //   "properties": {
 // "frameId": {
 //   "type": "integer",
-//   "description": "Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope."
+//   "description": "Returns completions in the scope of this stack frame.
+//   If not specified, the completions are returned for the global scope."
 // },
 // "text": {
 //   "type": "string",
-//   "description": "One or more source lines. Typically this is the text a user has typed into the debug console before he asked for completion."
+//   "description": "One or more source lines. Typically this is the text a
+//   user has typed into the debug console before he asked for completion."
 // },
 // "column": {
 //   "type": "integer",
-//   "description": "The character position for which to determine the completion proposals."
+//   "description": "The character position for which to determine the
+//   completion proposals."
 // },
 // "line": {
 //   "type": "integer",
-//   "description": "An optional line for which to determine the completion proposals. If missing the first line of the text is assumed."
+//   "description": "An optional line for which to determine the completion
+//   proposals. If missing the first line of the text is assumed."
 // }
 //   },
 //   "required": [ "text", "column" ]
@@ -933,39 +939,51 @@
 // },
 // "CompletionItem": {
 //   "type": "object",
-//   "description": "CompletionItems are the suggestions returned from the CompletionsRequest.",
-//   "properties": {
+//   "description": "CompletionItems are the suggestions returned from the
+//   CompletionsRequest.", "properties": {
 // "label": {
 //   "type": "string",
-//   "description": "The label of this completion item. By default this is also the text that is inserted when selecting this completion."
+//   "description": "The label of this completion item. By default this is
+//   also the text that is inserted when selecting this completion."
 // },
 // "text": {
 //   "type": "string",
-//   "description": "If text is not falsy then it is inserted instead of the label."
+//   "description": "If text is not falsy then it is inserted instead of the
+//   label."
 // },
 // "sortText": {
 //   "type": "string",
-//   "description": "A string that should be

[Lldb-commits] [PATCH] D85988: Fix the ability to list iOS simulator processes.

2020-08-14 Thread Greg Clayton via Phabricator via lldb-commits
clayborg created this revision.
clayborg added reviewers: labath, aprantl, JDevlieghere, jingham, jasonmolenda.
Herald added a project: LLDB.
clayborg requested review of this revision.

This can be done by doing:
(lldb) platform select ios-simulator
(lldb) platform process list

There was code that was trying to detect simulator processes but it had an 
error in the loop where each time it would check for a env var that starts with 
"SIMULATOR_UDID=" it would change the architecture to iOS if it found it and 
MacOSX if it didn't. This meant unless "SIMULATOR_UDID=" was the last 
environment variable, this loop would never set the OS correctly. We also 
weren't setting the environment to Simulator which means 
PlatformAppleSimulator::FindProcesses(...) would never return any valid 
processes even when there were many.

I don't know how I can test this as we don't want a test suite having to launch 
an iOS simulator, so there are no tests at the moment. If anyone has any ideas 
on how to test this, please let me know.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D85988

Files:
  lldb/source/Host/macosx/objcxx/Host.mm


Index: lldb/source/Host/macosx/objcxx/Host.mm
===
--- lldb/source/Host/macosx/objcxx/Host.mm
+++ lldb/source/Host/macosx/objcxx/Host.mm
@@ -503,12 +503,12 @@
   uint32_t argc = data.GetU32(&offset);
   llvm::Triple &triple = process_info.GetArchitecture().GetTriple();
   const llvm::Triple::ArchType triple_arch = triple.getArch();
-  const bool check_for_ios_simulator =
+  bool check_for_ios_simulator =
   (triple_arch == llvm::Triple::x86 ||
triple_arch == llvm::Triple::x86_64);
-  const char *cstr = data.GetCStr(&offset);
-  if (cstr) {
-process_info.GetExecutableFile().SetFile(cstr, 
FileSpec::Style::native);
+  llvm::StringRef str(data.GetCStr(&offset));
+  if (!str.empty()) {
+process_info.GetExecutableFile().SetFile(str, FileSpec::Style::native);
 
 if (match_info_ptr == NULL ||
 NameMatches(
@@ -525,27 +525,29 @@
   // Now extract all arguments
   Args &proc_args = process_info.GetArguments();
   for (int i = 0; i < static_cast(argc); ++i) {
-cstr = data.GetCStr(&offset);
-if (cstr)
-  proc_args.AppendArgument(llvm::StringRef(cstr));
+str = data.GetCStr(&offset);
+if (!str.empty())
+  proc_args.AppendArgument(str);
   }
 
   Environment &proc_env = process_info.GetEnvironment();
-  while ((cstr = data.GetCStr(&offset))) {
-if (cstr[0] == '\0')
+  process_info.GetArchitecture().GetTriple().setOS(
+  llvm::Triple::MacOSX);
+  while (true) {
+str = data.GetCStr(&offset);
+if (str.empty())
   break;
 
 if (check_for_ios_simulator) {
-  if (strncmp(cstr, "SIMULATOR_UDID=", strlen("SIMULATOR_UDID=")) 
==
-  0)
+  if (str.startswith("SIMULATOR_UDID=")) {
 process_info.GetArchitecture().GetTriple().setOS(
 llvm::Triple::IOS);
-  else
-process_info.GetArchitecture().GetTriple().setOS(
-llvm::Triple::MacOSX);
+process_info.GetArchitecture().GetTriple().setEnvironment(
+llvm::Triple::Simulator);
+check_for_ios_simulator = false;
+  }
 }
-
-proc_env.insert(cstr);
+proc_env.insert(str);
   }
   return true;
 }


Index: lldb/source/Host/macosx/objcxx/Host.mm
===
--- lldb/source/Host/macosx/objcxx/Host.mm
+++ lldb/source/Host/macosx/objcxx/Host.mm
@@ -503,12 +503,12 @@
   uint32_t argc = data.GetU32(&offset);
   llvm::Triple &triple = process_info.GetArchitecture().GetTriple();
   const llvm::Triple::ArchType triple_arch = triple.getArch();
-  const bool check_for_ios_simulator =
+  bool check_for_ios_simulator =
   (triple_arch == llvm::Triple::x86 ||
triple_arch == llvm::Triple::x86_64);
-  const char *cstr = data.GetCStr(&offset);
-  if (cstr) {
-process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native);
+  llvm::StringRef str(data.GetCStr(&offset));
+  if (!str.empty()) {
+process_info.GetExecutableFile().SetFile(str, FileSpec::Style::native);
 
 if (match_info_ptr == NULL ||
 NameMatches(
@@ -525,27 +525,29 @@
   // Now extract all arguments
   Args &proc_args = process_info.GetArguments();
   for (int i = 0; i < static_cast(argc); ++i) {
-cstr = data.GetCStr(&offset);
-if (cstr)
-  proc_args.AppendArgument(llvm::StringRef(cstr));
+str =

[Lldb-commits] [lldb] b6db0a5 - Add python enumerators for SBTypeEnumMemberList, and some tests for this API.

2020-08-14 Thread Jim Ingham via lldb-commits

Author: Jim Ingham
Date: 2020-08-14T09:57:46-07:00
New Revision: b6db0a544df1f28e7fa53b74e19839e55e63c8c9

URL: 
https://github.com/llvm/llvm-project/commit/b6db0a544df1f28e7fa53b74e19839e55e63c8c9
DIFF: 
https://github.com/llvm/llvm-project/commit/b6db0a544df1f28e7fa53b74e19839e55e63c8c9.diff

LOG: Add python enumerators for SBTypeEnumMemberList, and some tests for this 
API.

Differential Revision: https://reviews.llvm.org/D85951

Added: 


Modified: 
lldb/bindings/interface/SBTypeEnumMember.i
lldb/test/API/lang/c/enum_types/TestEnumTypes.py
lldb/test/API/lang/c/enum_types/main.c

Removed: 




diff  --git a/lldb/bindings/interface/SBTypeEnumMember.i 
b/lldb/bindings/interface/SBTypeEnumMember.i
index 006bdeaa8cee..518e2bf90115 100644
--- a/lldb/bindings/interface/SBTypeEnumMember.i
+++ b/lldb/bindings/interface/SBTypeEnumMember.i
@@ -71,10 +71,18 @@ protected:
 SBTypeEnumMember (const lldb::TypeEnumMemberImplSP &);
 };
 
-%feature(
-"docstring",
-"Represents a list of SBTypeEnumMembers."
-) SBTypeEnumMemberList;
+%feature("docstring",
+"Represents a list of SBTypeEnumMembers.
+SBTypeEnumMemberList supports SBTypeEnumMember iteration.
+It also supports [] access either by index, or by enum
+element name by doing:
+
+  myType = target.FindFirstType('MyEnumWithElementA')
+  members = myType.GetEnumMembers()
+  first_elem = members[0]
+  elem_A = members['A']
+
+") SBTypeEnumMemberList;
 
 class SBTypeEnumMemberList
 {
@@ -99,6 +107,29 @@ public:
 uint32_t
 GetSize();
 
+#ifdef SWIGPYTHON
+%pythoncode %{
+def __iter__(self):
+'''Iterate over all members in a lldb.SBTypeEnumMemberList 
object.'''
+return lldb_iter(self, 'GetSize', 'GetTypeEnumMemberAtIndex')
+
+def __len__(self):
+'''Return the number of members in a lldb.SBTypeEnumMemberList 
object.'''
+return self.GetSize()
+
+def __getitem__(self, key):
+  num_elements = self.GetSize()
+  if type(key) is int:
+  if key < num_elements:
+  return self.GetTypeEnumMemberAtIndex(key)
+  elif type(key) is str:
+  for idx in range(num_elements):
+  item = self.GetTypeEnumMemberAtIndex(idx)
+  if item.name == key:
+  return item
+  return None
+%} 
+#endif
 
 private:
 std::unique_ptr m_opaque_ap;

diff  --git a/lldb/test/API/lang/c/enum_types/TestEnumTypes.py 
b/lldb/test/API/lang/c/enum_types/TestEnumTypes.py
index cb5bb8eccaa2..0442dd34196a 100644
--- a/lldb/test/API/lang/c/enum_types/TestEnumTypes.py
+++ b/lldb/test/API/lang/c/enum_types/TestEnumTypes.py
@@ -18,11 +18,9 @@ def setUp(self):
 # Find the line number to break inside main().
 self.line = line_number('main.c', '// Set break point at this line.')
 
-def test(self):
-"""Test 'image lookup -t days' and check for correct display and enum 
value printing."""
+def test_command_line(self):
+"""Test 'image lookup -t enum_test_days' and check for correct display 
and enum value printing."""
 self.build()
-exe = self.getBuildArtifact("a.out")
-self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
 
 lldbutil.run_to_source_breakpoint(
 self, '// Breakpoint for bitfield', lldb.SBFileSpec("main.c"))
@@ -63,10 +61,10 @@ def test(self):
 self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
 substrs=[' resolved, hit count = 1'])
 
-# Look up information about the 'days' enum type.
+# Look up information about the 'enum_test_days' enum type.
 # Check for correct display.
-self.expect("image lookup -t days", DATA_TYPES_DISPLAYED_CORRECTLY,
-substrs=['enum days {',
+self.expect("image lookup -t enum_test_days", 
DATA_TYPES_DISPLAYED_CORRECTLY,
+substrs=['enum enum_test_days {',
  'Monday',
  'Tuesday',
  'Wednesday',
@@ -124,3 +122,41 @@ def test(self):
 'check for valid enumeration value',
 substrs=[enum_value])
 lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+def check_enum_members(self, members):
+name_matches = ["Monday", "Tuesday", "Wednesday", "Thursday", 
"Friday", "Saturday", "Sunday", "kNumDays"]
+value_matches = [-3, -2, -1, 0, 1, 2, 3, 4]
+
+# First test that the list of members from the type works
+num_matches = len(name_matches)
+self.assertEqual(len(members), num_matches, "enum_members returns the 
right number of elements")
+for idx in range(0, num_matches):
+member = members[idx]
+self.assertTrue(member.IsValid(), "Got a valid member for idx: 
%d"%(idx))
+se

[Lldb-commits] [PATCH] D85951: Add Python iterator & getitem for SBTypeEnumMemberList

2020-08-14 Thread Jim Ingham via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb6db0a544df1: Add python enumerators for 
SBTypeEnumMemberList, and some tests for this API. (authored by jingham).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85951/new/

https://reviews.llvm.org/D85951

Files:
  lldb/bindings/interface/SBTypeEnumMember.i
  lldb/test/API/lang/c/enum_types/TestEnumTypes.py
  lldb/test/API/lang/c/enum_types/main.c

Index: lldb/test/API/lang/c/enum_types/main.c
===
--- lldb/test/API/lang/c/enum_types/main.c
+++ lldb/test/API/lang/c/enum_types/main.c
@@ -25,7 +25,7 @@
 Beta = 4
 };
 
-enum days {
+enum enum_test_days {
 Monday = -3,
 Tuesday,
 Wednesday,
@@ -40,7 +40,7 @@
 int nonsense = a + b + c + ab + ac + all;
 enum non_bitfield omega = Alpha | Beta;
 
-enum days day;
+enum enum_test_days day;
 struct foo f;
 f.op = NULL; // Breakpoint for bitfield
 for (day = Monday - 1; day <= kNumDays + 1; day++)
Index: lldb/test/API/lang/c/enum_types/TestEnumTypes.py
===
--- lldb/test/API/lang/c/enum_types/TestEnumTypes.py
+++ lldb/test/API/lang/c/enum_types/TestEnumTypes.py
@@ -18,11 +18,9 @@
 # Find the line number to break inside main().
 self.line = line_number('main.c', '// Set break point at this line.')
 
-def test(self):
-"""Test 'image lookup -t days' and check for correct display and enum value printing."""
+def test_command_line(self):
+"""Test 'image lookup -t enum_test_days' and check for correct display and enum value printing."""
 self.build()
-exe = self.getBuildArtifact("a.out")
-self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
 
 lldbutil.run_to_source_breakpoint(
 self, '// Breakpoint for bitfield', lldb.SBFileSpec("main.c"))
@@ -63,10 +61,10 @@
 self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
 substrs=[' resolved, hit count = 1'])
 
-# Look up information about the 'days' enum type.
+# Look up information about the 'enum_test_days' enum type.
 # Check for correct display.
-self.expect("image lookup -t days", DATA_TYPES_DISPLAYED_CORRECTLY,
-substrs=['enum days {',
+self.expect("image lookup -t enum_test_days", DATA_TYPES_DISPLAYED_CORRECTLY,
+substrs=['enum enum_test_days {',
  'Monday',
  'Tuesday',
  'Wednesday',
@@ -124,3 +122,41 @@
 'check for valid enumeration value',
 substrs=[enum_value])
 lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+def check_enum_members(self, members):
+name_matches = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "kNumDays"]
+value_matches = [-3, -2, -1, 0, 1, 2, 3, 4]
+
+# First test that the list of members from the type works
+num_matches = len(name_matches)
+self.assertEqual(len(members), num_matches, "enum_members returns the right number of elements")
+for idx in range(0, num_matches):
+member = members[idx]
+self.assertTrue(member.IsValid(), "Got a valid member for idx: %d"%(idx))
+self.assertEqual(member.name, name_matches[idx], "Name matches for %d"%(idx))
+self.assertEqual(member.signed, value_matches[idx], "Value matches for %d"%(idx))
+
+def test_api(self):
+"""Test the the SBTypeEnumMember API's work correctly for enum_test_days"""
+self.build()
+target = lldbutil.run_to_breakpoint_make_target(self)
+
+types = target.FindTypes("enum_test_days")
+self.assertEqual(len(types), 1, "Found more than one enum_test_days type...")
+type = types.GetTypeAtIndex(0)
+
+# First check using the Python list returned by the type:
+self.check_enum_members(type.enum_members)
+
+# Now use the SBTypeEnumMemberList.
+member_list = type.GetEnumMembers()
+self.check_enum_members(member_list)
+
+# Now check that the by name accessor works:
+for member in member_list:
+name = member.name
+check_member = member_list[name]
+self.assertTrue(check_member.IsValid(), "Got a valid member for %s."%(name))
+self.assertEqual(name, check_member.name, "Got back the right name")
+self.assertEqual(member.unsigned, check_member.unsigned)
+
Index: lldb/bindings/interface/SBTypeEnumMember.i
===
--- lldb/bindings/interface/SBTypeEnumMember.i
+++ lldb/bindings/interface/SBTypeEnumMember.i
@@ -71,10 +71,18 @@
 SBTypeEnumMe

[Lldb-commits] [PATCH] D85976: [lldb] Get rid of helper CMake variables for Python

2020-08-14 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere created this revision.
JDevlieghere added reviewers: mgorny, labath, LLDB.
JDevlieghere requested review of this revision.
Herald added a subscriber: aheejin.

This patch is basically just a big sed to update the variables:

  s/PYTHON_LIBRARIES/Python3_LIBRARIES/g 
  s/PYTHON_INCLUDE_DIRS/Python3_INCLUDE_DIRS/g
  s/PYTHON_EXECUTABLE/Python3_EXECUTABLE/g 
  s/PYTHON_RPATH/Python3_RPATH/g 

I've also renamed the CMake module to better express its purpose and for 
consistency with `FindLuaAndSwig`.


https://reviews.llvm.org/D85976

Files:
  lldb/CMakeLists.txt
  lldb/bindings/python/CMakeLists.txt
  lldb/cmake/modules/FindPythonAndSwig.cmake
  lldb/cmake/modules/FindPythonInterpAndLibs.cmake
  lldb/cmake/modules/LLDBConfig.cmake
  lldb/source/API/CMakeLists.txt
  lldb/source/Plugins/ObjectFile/CMakeLists.txt
  lldb/source/Plugins/ScriptInterpreter/None/CMakeLists.txt
  lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
  lldb/test/API/CMakeLists.txt
  lldb/test/API/lit.site.cfg.py.in
  lldb/test/CMakeLists.txt
  lldb/test/Shell/lit.site.cfg.py.in
  lldb/test/Unit/lit.site.cfg.py.in
  lldb/test/lit.site.cfg.py.in
  lldb/tools/intel-features/CMakeLists.txt
  lldb/tools/lldb-test/CMakeLists.txt
  lldb/unittests/API/CMakeLists.txt
  lldb/unittests/Process/Linux/CMakeLists.txt
  lldb/unittests/ScriptInterpreter/Lua/CMakeLists.txt
  lldb/unittests/ScriptInterpreter/Python/CMakeLists.txt
  lldb/utils/lldb-dotest/lldb-dotest.in

Index: lldb/utils/lldb-dotest/lldb-dotest.in
===
--- lldb/utils/lldb-dotest/lldb-dotest.in
+++ lldb/utils/lldb-dotest/lldb-dotest.in
@@ -1,4 +1,4 @@
-#!@PYTHON_EXECUTABLE@
+#!@Python3_EXECUTABLE@
 import subprocess
 import sys
 
Index: lldb/unittests/ScriptInterpreter/Python/CMakeLists.txt
===
--- lldb/unittests/ScriptInterpreter/Python/CMakeLists.txt
+++ lldb/unittests/ScriptInterpreter/Python/CMakeLists.txt
@@ -10,6 +10,6 @@
 Support
   )
 
-if(PYTHON_RPATH)
-  set_property(TARGET ScriptInterpreterPythonTests APPEND PROPERTY BUILD_RPATH "${PYTHON_RPATH}")
-endif()
\ No newline at end of file
+if(Python3_RPATH)
+  set_property(TARGET ScriptInterpreterPythonTests APPEND PROPERTY BUILD_RPATH "${Python3_RPATH}")
+endif()
Index: lldb/unittests/ScriptInterpreter/Lua/CMakeLists.txt
===
--- lldb/unittests/ScriptInterpreter/Lua/CMakeLists.txt
+++ lldb/unittests/ScriptInterpreter/Lua/CMakeLists.txt
@@ -9,4 +9,4 @@
 LLVMTestingSupport
   LINK_COMPONENTS
 Support
-  )
\ No newline at end of file
+  )
Index: lldb/unittests/Process/Linux/CMakeLists.txt
===
--- lldb/unittests/Process/Linux/CMakeLists.txt
+++ lldb/unittests/Process/Linux/CMakeLists.txt
@@ -6,4 +6,4 @@
   )
 
 target_include_directories(ProcessorTraceTests PRIVATE
-  ${LLDB_SOURCE_DIR}/source/Plugins/Process/Linux)
\ No newline at end of file
+  ${LLDB_SOURCE_DIR}/source/Plugins/Process/Linux)
Index: lldb/unittests/API/CMakeLists.txt
===
--- lldb/unittests/API/CMakeLists.txt
+++ lldb/unittests/API/CMakeLists.txt
@@ -5,6 +5,6 @@
 liblldb
   )
 
-if(PYTHON_RPATH)
-  set_property(TARGET APITests APPEND PROPERTY BUILD_RPATH "${PYTHON_RPATH}")
+if(Python3_RPATH)
+  set_property(TARGET APITests APPEND PROPERTY BUILD_RPATH "${Python3_RPATH}")
 endif()
Index: lldb/tools/lldb-test/CMakeLists.txt
===
--- lldb/tools/lldb-test/CMakeLists.txt
+++ lldb/tools/lldb-test/CMakeLists.txt
@@ -24,9 +24,9 @@
 Support
   )
 
-if(PYTHON_RPATH)
-  set_property(TARGET lldb-test APPEND PROPERTY INSTALL_RPATH "${PYTHON_RPATH}")
-  set_property(TARGET lldb-test APPEND PROPERTY BUILD_RPATH   "${PYTHON_RPATH}")
+if(Python3_RPATH)
+  set_property(TARGET lldb-test APPEND PROPERTY INSTALL_RPATH "${Python3_RPATH}")
+  set_property(TARGET lldb-test APPEND PROPERTY BUILD_RPATH   "${Python3_RPATH}")
 endif()
 
 target_include_directories(lldb-test PRIVATE ${LLDB_SOURCE_DIR}/source)
Index: lldb/tools/intel-features/CMakeLists.txt
===
--- lldb/tools/intel-features/CMakeLists.txt
+++ lldb/tools/intel-features/CMakeLists.txt
@@ -56,7 +56,7 @@
 
   LINK_LIBS
 ${FEATURE_LIBS}
-${PYTHON_LIBRARIES}
+${Python3_LIBRARIES}
   )
 
 # Add link dependencies for python wrapper
Index: lldb/test/lit.site.cfg.py.in
===
--- lldb/test/lit.site.cfg.py.in
+++ lldb/test/lit.site.cfg.py.in
@@ -10,7 +10,7 @@
 config.lldb_obj_root = "@LLDB_BINARY_DIR@"
 config.lldb_src_root = "@LLDB_SOURCE_DIR@"
 config.target_triple = "@TARGET_TRIPLE@"
-config.python_executable = "@PYTHON_EXECUTABLE@"
+config.python_executable = "@Python3_EXECUTABLE@"
 
 # Suppo

[Lldb-commits] [PATCH] D85942: [lldb] Remove Python 2 fallback and make Python 3 the only supported configuration.

2020-08-14 Thread Jonas Devlieghere via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce439cb1c962: [lldb] Remove Python 2 fallback and only 
support Python 3 (authored by JDevlieghere).
Herald added a project: LLDB.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85942/new/

https://reviews.llvm.org/D85942

Files:
  lldb/cmake/modules/FindPythonInterpAndLibs.cmake


Index: lldb/cmake/modules/FindPythonInterpAndLibs.cmake
===
--- lldb/cmake/modules/FindPythonInterpAndLibs.cmake
+++ lldb/cmake/modules/FindPythonInterpAndLibs.cmake
@@ -38,41 +38,12 @@
   endif()
 endmacro()
 
-macro(FindPython2)
-  # Use PYTHON_HOME as a hint to find Python 2.
-  set(Python2_ROOT_DIR "${PYTHON_HOME}")
-  find_package(Python2 COMPONENTS Interpreter Development)
-  if(Python2_FOUND AND Python2_Interpreter_FOUND)
-set(PYTHON_LIBRARIES ${Python2_LIBRARIES})
-set(PYTHON_INCLUDE_DIRS ${Python2_INCLUDE_DIRS})
-set(PYTHON_EXECUTABLE ${Python2_EXECUTABLE})
-
-set(PYTHON2_FOUND TRUE)
-mark_as_advanced(
-  PYTHON_LIBRARIES
-  PYTHON_INCLUDE_DIRS
-  PYTHON_EXECUTABLE
-  SWIG_EXECUTABLE)
-  endif()
-endmacro()
-
 if(PYTHON_LIBRARIES AND PYTHON_INCLUDE_DIRS AND PYTHON_EXECUTABLE AND 
SWIG_EXECUTABLE)
   set(PYTHONINTERPANDLIBS_FOUND TRUE)
 else()
   find_package(SWIG 2.0)
   if (SWIG_FOUND)
-if (LLDB_PYTHON_VERSION)
-  if (LLDB_PYTHON_VERSION VERSION_EQUAL "2")
-FindPython2()
-  elseif(LLDB_PYTHON_VERSION VERSION_EQUAL "3")
-FindPython3()
-  endif()
-else()
   FindPython3()
-  if (NOT PYTHON3_FOUND AND NOT CMAKE_SYSTEM_NAME STREQUAL Windows)
-FindPython2()
-  endif()
-endif()
   else()
 message(STATUS "SWIG 2 or later is required for Python support in LLDB but 
could not be found")
   endif()


Index: lldb/cmake/modules/FindPythonInterpAndLibs.cmake
===
--- lldb/cmake/modules/FindPythonInterpAndLibs.cmake
+++ lldb/cmake/modules/FindPythonInterpAndLibs.cmake
@@ -38,41 +38,12 @@
   endif()
 endmacro()
 
-macro(FindPython2)
-  # Use PYTHON_HOME as a hint to find Python 2.
-  set(Python2_ROOT_DIR "${PYTHON_HOME}")
-  find_package(Python2 COMPONENTS Interpreter Development)
-  if(Python2_FOUND AND Python2_Interpreter_FOUND)
-set(PYTHON_LIBRARIES ${Python2_LIBRARIES})
-set(PYTHON_INCLUDE_DIRS ${Python2_INCLUDE_DIRS})
-set(PYTHON_EXECUTABLE ${Python2_EXECUTABLE})
-
-set(PYTHON2_FOUND TRUE)
-mark_as_advanced(
-  PYTHON_LIBRARIES
-  PYTHON_INCLUDE_DIRS
-  PYTHON_EXECUTABLE
-  SWIG_EXECUTABLE)
-  endif()
-endmacro()
-
 if(PYTHON_LIBRARIES AND PYTHON_INCLUDE_DIRS AND PYTHON_EXECUTABLE AND SWIG_EXECUTABLE)
   set(PYTHONINTERPANDLIBS_FOUND TRUE)
 else()
   find_package(SWIG 2.0)
   if (SWIG_FOUND)
-if (LLDB_PYTHON_VERSION)
-  if (LLDB_PYTHON_VERSION VERSION_EQUAL "2")
-FindPython2()
-  elseif(LLDB_PYTHON_VERSION VERSION_EQUAL "3")
-FindPython3()
-  endif()
-else()
   FindPython3()
-  if (NOT PYTHON3_FOUND AND NOT CMAKE_SYSTEM_NAME STREQUAL Windows)
-FindPython2()
-  endif()
-endif()
   else()
 message(STATUS "SWIG 2 or later is required for Python support in LLDB but could not be found")
   endif()
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] ce439cb - [lldb] Remove Python 2 fallback and only support Python 3

2020-08-14 Thread Jonas Devlieghere via lldb-commits

Author: Jonas Devlieghere
Date: 2020-08-14T08:50:11-07:00
New Revision: ce439cb1c962360267fb7a94d44ad57053787607

URL: 
https://github.com/llvm/llvm-project/commit/ce439cb1c962360267fb7a94d44ad57053787607
DIFF: 
https://github.com/llvm/llvm-project/commit/ce439cb1c962360267fb7a94d44ad57053787607.diff

LOG: [lldb] Remove Python 2 fallback and only support Python 3

This removes the fallback to Python 2 and makes Python 3 the only
supported configuration. This is the first step to fully migrate to
Python 3 over the coming releases as discussed on the mailing list.

http://lists.llvm.org/pipermail/lldb-dev/2020-August/016388.html

As a reminder, for the current release the test suite and the generated
bindings should remain compatible with Python 2.

Differential revision: https://reviews.llvm.org/D85942

Added: 


Modified: 
lldb/cmake/modules/FindPythonInterpAndLibs.cmake

Removed: 




diff  --git a/lldb/cmake/modules/FindPythonInterpAndLibs.cmake 
b/lldb/cmake/modules/FindPythonInterpAndLibs.cmake
index 3a64ebbcf972..5ac472b036d7 100644
--- a/lldb/cmake/modules/FindPythonInterpAndLibs.cmake
+++ b/lldb/cmake/modules/FindPythonInterpAndLibs.cmake
@@ -38,41 +38,12 @@ macro(FindPython3)
   endif()
 endmacro()
 
-macro(FindPython2)
-  # Use PYTHON_HOME as a hint to find Python 2.
-  set(Python2_ROOT_DIR "${PYTHON_HOME}")
-  find_package(Python2 COMPONENTS Interpreter Development)
-  if(Python2_FOUND AND Python2_Interpreter_FOUND)
-set(PYTHON_LIBRARIES ${Python2_LIBRARIES})
-set(PYTHON_INCLUDE_DIRS ${Python2_INCLUDE_DIRS})
-set(PYTHON_EXECUTABLE ${Python2_EXECUTABLE})
-
-set(PYTHON2_FOUND TRUE)
-mark_as_advanced(
-  PYTHON_LIBRARIES
-  PYTHON_INCLUDE_DIRS
-  PYTHON_EXECUTABLE
-  SWIG_EXECUTABLE)
-  endif()
-endmacro()
-
 if(PYTHON_LIBRARIES AND PYTHON_INCLUDE_DIRS AND PYTHON_EXECUTABLE AND 
SWIG_EXECUTABLE)
   set(PYTHONINTERPANDLIBS_FOUND TRUE)
 else()
   find_package(SWIG 2.0)
   if (SWIG_FOUND)
-if (LLDB_PYTHON_VERSION)
-  if (LLDB_PYTHON_VERSION VERSION_EQUAL "2")
-FindPython2()
-  elseif(LLDB_PYTHON_VERSION VERSION_EQUAL "3")
-FindPython3()
-  endif()
-else()
   FindPython3()
-  if (NOT PYTHON3_FOUND AND NOT CMAKE_SYSTEM_NAME STREQUAL Windows)
-FindPython2()
-  endif()
-endif()
   else()
 message(STATUS "SWIG 2 or later is required for Python support in LLDB but 
could not be found")
   endif()



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85915: [lldb] Use file to synchronize TestDeepBundle and TestBundleWithDotInFilename

2020-08-14 Thread Jonas Devlieghere via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG37ec83fcfc6c: [lldb] Use file to synchronize TestDeepBundle 
and TestBundleWithDotInFilename (authored by JDevlieghere).
Herald added a project: LLDB.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85915/new/

https://reviews.llvm.org/D85915

Files:
  
lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
  lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
  lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
  lldb/test/API/macosx/find-dsym/deep-bundle/main.c

Index: lldb/test/API/macosx/find-dsym/deep-bundle/main.c
===
--- lldb/test/API/macosx/find-dsym/deep-bundle/main.c
+++ lldb/test/API/macosx/find-dsym/deep-bundle/main.c
@@ -13,6 +13,8 @@
  argv[1], argv[1], argv[1]);
 system (command);
 
+FILE *fp = fopen (argv[2], "w");
+fclose (fp);
 setup_is_complete = 1;
 
 // At this point we want lldb to attach to the process.  If lldb attaches
Index: lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
===
--- lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
+++ lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
@@ -31,14 +31,24 @@
 @skipUnlessDarwin
 # This test is explicitly a dSYM test, it doesn't need to run for any other config.
 @skipIf(debug_info=no_match(["dsym"]))
+@skipIfReproducer # File synchronization is not supported during replay.
 def test_attach_and_check_dsyms(self):
 """Test attach to binary, see if the framework dSYM is found"""
 exe = self.getBuildArtifact(exe_name)
 self.build()
-popen = self.spawnSubprocess(exe, [self.getBuildDir()])
 
-# Give the inferior time to start up, dlopen a bundle, remove the bundle it linked in
-sleep(5)
+# Use a file as a synchronization point between test and inferior.
+pid_file_path = lldbutil.append_to_process_working_directory(self,
+"token_pid_%d" % (int(os.getpid(
+self.addTearDownHook(
+lambda: self.run_platform_command(
+"rm %s" %
+(pid_file_path)))
+
+popen = self.spawnSubprocess(exe, [self.getBuildDir(),  pid_file_path])
+
+# Wait for the inferior to start up, dlopen a bundle, remove the bundle it linked in
+pid = lldbutil.wait_for_file_on_target(self, pid_file_path)
 
 # Since the library that was dlopen()'ed is now removed, lldb will need to find the
 # binary & dSYM via target.exec-search-paths
Index: lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
===
--- lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
+++ lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
@@ -1,10 +1,11 @@
 #include 
 #include 
 #include 
+#include 
 
 int setup_is_complete = 0;
 
-int main()
+int main(int argc, const char** argv)
 {
 
 void *handle = dlopen ("com.apple.sbd.xpc/com.apple.sbd", RTLD_NOW);
@@ -13,6 +14,9 @@
 if (dlsym(handle, "foo"))
 {
 system ("/bin/rm -rf com.apple.sbd.xpc com.apple.sbd.xpc.dSYM");
+
+FILE *fp = fopen (argv[1], "w");
+fclose (fp);
 setup_is_complete = 1;
 
 // At this point we want lldb to attach to the process.  If lldb attaches
Index: lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
===
--- lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
+++ lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
@@ -32,15 +32,25 @@
 @skipUnlessDarwin
 # This test is explicitly a dSYM test, it doesn't need to run for any other config.
 @skipIf(debug_info=no_match(["dsym"]))
+@skipIfReproducer # File synchronization is not supported during replay.
 def test_attach_and_check_dsyms(self):
 """Test attach to binary, see if the bundle dSYM is found"""
 exe = self.getBuildArtifact(exe_name)
 self.build()
 os.chdir(self.getBuildDir());
-popen = self.spawnSubprocess(exe)
 
-# Give the inferior time to start up, dlopen a bundle, remove the bundle it linked in
-sleep(5)
+# Use a file as a synchronization point between test and inferior.
+pid_file_path = lldbutil.append_to_process_working_directory(self,
+"token_pid_%d" % (int(os.getpid(
+self.addTearDownHook(
+lambda: self.run_platform_command(
+"rm %s" %
+(pid_file_path)))
+
+popen = self.spawnSubprocess(exe, [p

[Lldb-commits] [lldb] 37ec83f - [lldb] Use file to synchronize TestDeepBundle and TestBundleWithDotInFilename

2020-08-14 Thread Jonas Devlieghere via lldb-commits

Author: Jonas Devlieghere
Date: 2020-08-14T08:32:21-07:00
New Revision: 37ec83fcfc6c7915c51268f578b8e0dadb54c1cf

URL: 
https://github.com/llvm/llvm-project/commit/37ec83fcfc6c7915c51268f578b8e0dadb54c1cf
DIFF: 
https://github.com/llvm/llvm-project/commit/37ec83fcfc6c7915c51268f578b8e0dadb54c1cf.diff

LOG: [lldb] Use file to synchronize TestDeepBundle and 
TestBundleWithDotInFilename

Currently these two tests use an arbitrary wait of 5 seconds for the
inferior to finish setting up. When the test machine is under heavy load
this sometimes is insufficient leading to spurious test failures. This
patch adds synchronization trough a token on the file system. In
addition to making the test more reliable it also makes it much faster
because we no longer have to wait the full 5 seconds if the setup was
completed faster than that.

Differential revision: https://reviews.llvm.org/D85915

Added: 


Modified: 

lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
lldb/test/API/macosx/find-dsym/deep-bundle/main.c

Removed: 




diff  --git 
a/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
 
b/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
index 2572600a1829..e12a638f9c03 100644
--- 
a/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
+++ 
b/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py
@@ -32,15 +32,25 @@ def tearDown(self):
 @skipUnlessDarwin
 # This test is explicitly a dSYM test, it doesn't need to run for any 
other config.
 @skipIf(debug_info=no_match(["dsym"]))
+@skipIfReproducer # File synchronization is not supported during replay.
 def test_attach_and_check_dsyms(self):
 """Test attach to binary, see if the bundle dSYM is found"""
 exe = self.getBuildArtifact(exe_name)
 self.build()
 os.chdir(self.getBuildDir());
-popen = self.spawnSubprocess(exe)
 
-# Give the inferior time to start up, dlopen a bundle, remove the 
bundle it linked in
-sleep(5)
+# Use a file as a synchronization point between test and inferior.
+pid_file_path = lldbutil.append_to_process_working_directory(self,
+"token_pid_%d" % (int(os.getpid(
+self.addTearDownHook(
+lambda: self.run_platform_command(
+"rm %s" %
+(pid_file_path)))
+
+popen = self.spawnSubprocess(exe, [pid_file_path])
+
+# Wait for the inferior to start up, dlopen a bundle, remove the 
bundle it linked in
+pid = lldbutil.wait_for_file_on_target(self, pid_file_path)
 
 # Since the library that was dlopen()'ed is now removed, lldb will 
need to find the
 # binary & dSYM via target.exec-search-paths
@@ -64,6 +74,3 @@ def test_attach_and_check_dsyms(self):
 self.assertTrue (dsym_name == 'com.apple.sbd', "Check that we 
found the dSYM for the bundle that was loaded")
 i=i+1
 os.chdir(self.getSourceDir());
-
-if __name__ == '__main__':
-unittest.main()

diff  --git a/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c 
b/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
index 30761eb1b409..a4cffc840731 100644
--- a/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
+++ b/lldb/test/API/macosx/find-dsym/bundle-with-dot-in-filename/main.c
@@ -1,10 +1,11 @@
 #include 
 #include 
 #include 
+#include 
 
 int setup_is_complete = 0;
 
-int main()
+int main(int argc, const char** argv)
 {
 
 void *handle = dlopen ("com.apple.sbd.xpc/com.apple.sbd", RTLD_NOW);
@@ -13,6 +14,9 @@ int main()
 if (dlsym(handle, "foo"))
 {
 system ("/bin/rm -rf com.apple.sbd.xpc com.apple.sbd.xpc.dSYM");
+
+FILE *fp = fopen (argv[1], "w");
+fclose (fp);
 setup_is_complete = 1;
 
 // At this point we want lldb to attach to the process.  If lldb 
attaches

diff  --git a/lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py 
b/lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
index a486c5159f01..358a4b70d2f5 100644
--- a/lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
+++ b/lldb/test/API/macosx/find-dsym/deep-bundle/TestDeepBundle.py
@@ -31,14 +31,24 @@ def tearDown(self):
 @skipUnlessDarwin
 # This test is explicitly a dSYM test, it doesn't need to run for any 
other config.
 @skipIf(debug_info=no_match(["dsym"]))
+@skipIfReproducer # File synchronization is not supported during replay.
 def test_attach_and_check_dsyms(self):
 """Test attach to binary, see if the fra

[Lldb-commits] [lldb] 46ed27f - [lldb] Make packetlog_get_dylib_info returns the last full response

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Raphael Isemann
Date: 2020-08-14T14:51:13+02:00
New Revision: 46ed27ff1b1cd74742511d73a4a43afa97455fe2

URL: 
https://github.com/llvm/llvm-project/commit/46ed27ff1b1cd74742511d73a4a43afa97455fe2
DIFF: 
https://github.com/llvm/llvm-project/commit/46ed27ff1b1cd74742511d73a4a43afa97455fe2.diff

LOG: [lldb] Make packetlog_get_dylib_info returns the last full response

In sanitized builds the last packet this function finds for the
TestMacCatalyst and TestPlatformSimulator tests is for the asan runtime.

```
 <  69> send packet: 
$jGetLoadedDynamicLibrariesInfos:{"solib_addresses":[4296048640]}]#3a <
 715> read packet: 
${"images":[{"load_address":4296048640,"mod_date":0,"pathname":
 
"/Users/buildslave/jenkins/workspace/lldb-cmake-sanitized/host-compiler/lib/clang/12.0.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib",
 "uuid":"8E38A2CD-753F-3E0F-8EB0-F4BD5788A5CA",
 "min_version_os_name":"macosx","min_version_os_sdk":"10.9",
 
"mach_header":{"magic":4277009103,"cputype":16777223,"cpusubtype":3,"filetype":6,
 
"flags":43090053}],"segments":[{"name":"__TEXT","vmaddr":0,"vmsize":565248,"fileoff":0,
 
"filesize":565248,"maxprot":5}],{"name":"__DATA","vmaddr":565248,"vmsize":13152256,"fileoff":565248,
 
"filesize":20480,"maxprot":3}],{"name":"__LINKEDIT","vmaddr":13717504,"vmsize":438272,"fileoff":585728,
 "filesize":435008,"maxprot":1}]]}]]}]#00
```

This just fetches the last package which has fetch_all_solibs and we know
it will contain the image of our test executable to get the tests running again.

Added: 


Modified: 
lldb/packages/Python/lldbsuite/test/lldbutil.py

Removed: 




diff  --git a/lldb/packages/Python/lldbsuite/test/lldbutil.py 
b/lldb/packages/Python/lldbsuite/test/lldbutil.py
index 4eb407638903..d0ba25e185cd 100644
--- a/lldb/packages/Python/lldbsuite/test/lldbutil.py
+++ b/lldb/packages/Python/lldbsuite/test/lldbutil.py
@@ -1490,7 +1490,8 @@ def packetlog_get_process_info(log):
 return process_info
 
 def packetlog_get_dylib_info(log):
-"""parse a gdb-remote packet log file and extract the *last* response to 
jGetLoadedDynamicLibrariesInfos"""
+"""parse a gdb-remote packet log file and extract the *last* complete
+(=> fetch_all_solibs=true) response to jGetLoadedDynamicLibrariesInfos"""
 import json
 dylib_info = None
 with open(log, "r") as logfile:
@@ -1504,7 +1505,7 @@ def packetlog_get_dylib_info(log):
 # Unescape '}'.
 dylib_info = json.loads(line.replace('}]','}')[:-4])
 expect_dylib_info_response = False
-if 'send packet: $jGetLoadedDynamicLibrariesInfos:{' in line:
+if 'send packet: 
$jGetLoadedDynamicLibrariesInfos:{"fetch_all_solibs":true}' in line:
 expect_dylib_info_response = True
 
 return dylib_info



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85968: [lldb] Forcefully complete a type when adding nested classes

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
labath created this revision.
labath added reviewers: teemperor, shafik.
Herald added a project: LLDB.
labath requested review of this revision.
Herald added a subscriber: JDevlieghere.

With -flimit-debug-info, we can run into cases when we only have a class
as a declaration, but we do have a definition of a nested class. In this
case, clang will hit an assertion when adding a member to an incomplete
type (but only if it's adding a c++ class, and not C struct).

It turns out we already had code to handle a similar situation arising
in the -gmodules scenario. This extends the code to handle
-flimit-debug-info as well, and reorganizes bits of other code handling
completion of types to move functions doing similar things closer
together.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D85968

Files:
  lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.h
  lldb/test/Shell/SymbolFile/DWARF/DW_AT_declaration-with-children.s

Index: lldb/test/Shell/SymbolFile/DWARF/DW_AT_declaration-with-children.s
===
--- lldb/test/Shell/SymbolFile/DWARF/DW_AT_declaration-with-children.s
+++ lldb/test/Shell/SymbolFile/DWARF/DW_AT_declaration-with-children.s
@@ -1,27 +1,48 @@
-# Test that a forward-declared (DW_AT_declaration) structure is treated as a
-# forward-declaration even if it has children. These types can be produced due
-# to vtable-based type homing, or other -flimit-debug-info optimizations.
+# Test handling of forward-declared (DW_AT_declaration) structures. These types
+# can be produced due to vtable-based type homing, or other -flimit-debug-info
+# optimizations.
 
 # REQUIRES: x86
 
-# RUN: llvm-mc --triple x86_64-pc-linux %s --filetype=obj > %t
-# RUN: %lldb %t -o "expr a" -o exit 2>&1 | FileCheck %s --check-prefix=EXPR
-# RUN: %lldb %t -o "target var a" -o exit 2>&1 | FileCheck %s --check-prefix=VAR
-
-# EXPR: incomplete type 'A' where a complete type is required
+# RUN: rm -rf %t
+# RUN: split-file %s %t
+# RUN: llvm-mc --triple x86_64-pc-linux %t/asm --filetype=obj > %t.o
+# RUN: %lldb -o "settings set interpreter.stop-command-source-on-error false" \
+# RUN:   -s %t/commands -o exit %t.o 2>&1 | FileCheck %s
 
+#--- commands
+# Type A should be treated as a forward-declaration even though it has a child.
+target var a
+# CHECK-LABEL: target var a
 # FIXME: This should also produce some kind of an error.
-# VAR: (A) a = {}
+# CHECK: (A) a = {}
+expr a
+# CHECK-LABEL: expr a
+# CHECK: incomplete type 'A' where a complete type is required
+
+# Parsing B::B1 should not crash even though B is incomplete. Note that in this
+# case B must be forcefully completed.
+target var b1
+# CHECK-LABEL: target var b1
+# CHECK: (B::B1) b1 = (ptr = 0xbaadf00d)
+expr b1
+# CHECK-LABEL: expr b1
+# CHECK: (B::B1) $0 = (ptr = 0xbaadf00d)
 
+#--- asm
 .text
 _ZN1AC2Ev:
 retq
 .LZN1AC2Ev_end:
 
 .data
+.p2align 4
 a:
-.quad   $_ZTV1A+16
-.quad   $0xdeadbeef
+.quad   _ZTV1A+16
+.quad   0xdeadbeef
+
+b1:
+.quad   0xbaadf00d
 
 .section.debug_abbrev,"",@progbits
 .byte   1   # Abbreviation Code
@@ -73,6 +94,24 @@
 .byte   25  # DW_FORM_flag_present
 .byte   0   # EOM(1)
 .byte   0   # EOM(2)
+.byte   6   # Abbreviation Code
+.byte   2   # DW_TAG_class_type
+.byte   1   # DW_CHILDREN_yes
+.byte   3   # DW_AT_name
+.byte   8   # DW_FORM_string
+.byte   0   # EOM(1)
+.byte   0   # EOM(2)
+.byte   7   # Abbreviation Code
+.byte   13  # DW_TAG_member
+.byte   0   # DW_CHILDREN_no
+.byte   3   # DW_AT_name
+.byte   8   # DW_FORM_string
+.byte   73  # DW_AT_type
+.byte   19  # DW_FORM_ref4
+.byte   56  # DW_AT_data_member_location
+.byte   11  # DW_FORM_data1
+.byte   0   # EOM(1)
+.byte   0   # EOM(2)
 .byte   8   # Abbreviation Code
 .byte   15  # DW_TAG_pointer_type
 .byte   0   # DW_CHILDREN_no
@@ -120,6 +159,15 @@
 .asciz  "Hand-written DWARF"# DW_AT_producer
 .quad   _ZN1AC2E

[Lldb-commits] [lldb] bb4efab - [lldb] Use SBProcess::Continue instead of 'run' command in TestTargetAPI.py

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Raphael Isemann
Date: 2020-08-14T13:12:52+02:00
New Revision: bb4efab9a4d9431dbedb27f04249effd0a73812e

URL: 
https://github.com/llvm/llvm-project/commit/bb4efab9a4d9431dbedb27f04249effd0a73812e
DIFF: 
https://github.com/llvm/llvm-project/commit/bb4efab9a4d9431dbedb27f04249effd0a73812e.diff

LOG: [lldb] Use SBProcess::Continue instead of 'run' command in TestTargetAPI.py

This test is flaky on Green Dragon as it often fails when the process state
is "Invalid" in the assert:
self.assertEqual(process.GetState(), lldb.eStateExited)
It seems this is related to just doing "run" which apparently invalidates
the Target's process in case it's still running and needs to be restarted.
Just doing 'continue' on the process (and ignoring the error in case it already
finished) prevents that and makes this consistently pass for me.

Just pushing this out to get Green Dragon back online.

Added: 


Modified: 
lldb/test/API/python_api/target/TestTargetAPI.py

Removed: 




diff  --git a/lldb/test/API/python_api/target/TestTargetAPI.py 
b/lldb/test/API/python_api/target/TestTargetAPI.py
index de8bed08f5fa..85a6d78bdf5a 100644
--- a/lldb/test/API/python_api/target/TestTargetAPI.py
+++ b/lldb/test/API/python_api/target/TestTargetAPI.py
@@ -168,7 +168,7 @@ def test_launch_simple(self):
 
 process = target.LaunchSimple(
 ['foo', 'bar'], ['baz'], self.get_process_working_directory())
-self.runCmd("run")
+process.Continue()
 self.assertEqual(process.GetState(), lldb.eStateExited)
 output = process.GetSTDOUT()
 self.assertIn('arg: foo', output)
@@ -179,7 +179,7 @@ def test_launch_simple(self):
 self.runCmd("setting set target.env-vars bar=baz")
 process = target.LaunchSimple(None, None,
   self.get_process_working_directory())
-self.runCmd("run")
+process.Continue()
 self.assertEqual(process.GetState(), lldb.eStateExited)
 output = process.GetSTDOUT()
 self.assertIn('arg: foo', output)
@@ -188,7 +188,7 @@ def test_launch_simple(self):
 self.runCmd("settings set target.disable-stdio true")
 process = target.LaunchSimple(
 None, None, self.get_process_working_directory())
-self.runCmd("run")
+process.Continue()
 self.assertEqual(process.GetState(), lldb.eStateExited)
 output = process.GetSTDOUT()
 self.assertEqual(output, "")



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85904: [lldb] Check Decl kind when completing -flimit-debug-info types

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfdc6aea3fd82: [lldb] Check Decl kind when completing 
-flimit-debug-info types (authored by labath).

Changed prior to commit:
  https://reviews.llvm.org/D85904?vs=285352&id=285618#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85904/new/

https://reviews.llvm.org/D85904

Files:
  lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
  lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
  lldb/test/API/functionalities/limit-debug-info/main.cpp
  lldb/test/API/functionalities/limit-debug-info/one.cpp
  lldb/test/API/functionalities/limit-debug-info/onetwo.h

Index: lldb/test/API/functionalities/limit-debug-info/onetwo.h
===
--- lldb/test/API/functionalities/limit-debug-info/onetwo.h
+++ lldb/test/API/functionalities/limit-debug-info/onetwo.h
@@ -54,3 +54,13 @@
   virtual ~Two();
 };
 } // namespace result
+
+namespace func_shadow {
+void One(int);
+struct One {
+  int one = 142;
+  constexpr One() = default;
+  virtual ~One();
+};
+void One(float);
+} // namespace func_shadow
Index: lldb/test/API/functionalities/limit-debug-info/one.cpp
===
--- lldb/test/API/functionalities/limit-debug-info/one.cpp
+++ lldb/test/API/functionalities/limit-debug-info/one.cpp
@@ -6,3 +6,7 @@
 
 result::One::One(int member) : member(member) {}
 result::One::~One() = default;
+
+void func_shadow::One(int) {}
+func_shadow::One::~One() = default;
+void func_shadow::One(float) {}
Index: lldb/test/API/functionalities/limit-debug-info/main.cpp
===
--- lldb/test/API/functionalities/limit-debug-info/main.cpp
+++ lldb/test/API/functionalities/limit-debug-info/main.cpp
@@ -1,23 +1,19 @@
 #include "onetwo.h"
 
 struct InheritsFromOne : One {
-  constexpr InheritsFromOne() = default;
   int member = 47;
 } inherits_from_one;
 
 struct InheritsFromTwo : Two {
-  constexpr InheritsFromTwo() = default;
   int member = 47;
 } inherits_from_two;
 
 struct OneAsMember {
-  constexpr OneAsMember() = default;
   member::One one;
   int member = 47;
 } one_as_member;
 
 struct TwoAsMember {
-  constexpr TwoAsMember() = default;
   member::Two two;
   int member = 47;
 } two_as_member;
@@ -28,4 +24,9 @@
 result::One get_one() { return result::One(124); }
 result::Two get_two() { return result::Two(224); }
 
+// Note that there's also a function with the name func_shadow::One.
+struct ShadowedOne : func_shadow::One {
+  int member = 47;
+} shadowed_one;
+
 int main() { return get_one().member; }
Index: lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
===
--- lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
+++ lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
@@ -63,6 +63,9 @@
 self.expect_expr("get_two().one().member", result_value="124")
 self.expect_expr("get_two().member", result_value="224")
 
+self.expect_expr("shadowed_one.member", result_value="47")
+self.expect_expr("shadowed_one.one", result_value="142")
+
 @skipIf(bugnumber="pr46284", debug_info="gmodules")
 @skipIfWindows # Clang emits type info even with -flimit-debug-info
 def test_two_debug(self):
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
@@ -870,13 +870,14 @@
   return dn_or_err.takeError();
 DeclContext *dc = *dc_or_err;
 DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
-if (lr.size()) {
-  clang::Decl *lookup_found = lr.front();
-  RegisterImportedDecl(From, lookup_found);
-  m_decls_to_ignore.insert(lookup_found);
-  return lookup_found;
-} else
-  LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
+for (clang::Decl *candidate : lr) {
+  if (candidate->getKind() == From->getKind()) {
+RegisterImportedDecl(From, candidate);
+m_decls_to_ignore.insert(candidate);
+return candidate;
+  }
+}
+LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
   }
 
   return ASTImporter::ImportImpl(From);
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] fdc6aea - [lldb] Check Decl kind when completing -flimit-debug-info types

2020-08-14 Thread Pavel Labath via lldb-commits

Author: Pavel Labath
Date: 2020-08-14T12:31:37+02:00
New Revision: fdc6aea3fd822b639baaa5b666fdf7598d08c8de

URL: 
https://github.com/llvm/llvm-project/commit/fdc6aea3fd822b639baaa5b666fdf7598d08c8de
DIFF: 
https://github.com/llvm/llvm-project/commit/fdc6aea3fd822b639baaa5b666fdf7598d08c8de.diff

LOG: [lldb] Check Decl kind when completing -flimit-debug-info types

The search for the complete class definition can also produce entries
which are not of the expected type. This can happen for instance when
there is a function with the same name as the class we're looking up
(which means that the class needs to be disambiguated with the
struct/class tag in most contexts).

Previously we were just picking the first Decl that the lookup returned,
which later caused crashes or assertion failures if it was not of the
correct type. This patch changes that to search for an entry of the
correct type.

Differential Revision: https://reviews.llvm.org/D85904

Added: 


Modified: 
lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
lldb/test/API/functionalities/limit-debug-info/main.cpp
lldb/test/API/functionalities/limit-debug-info/one.cpp
lldb/test/API/functionalities/limit-debug-info/onetwo.h

Removed: 




diff  --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp 
b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
index 6d8773779a69..73042c205a5a 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
@@ -870,13 +870,14 @@ ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl 
*From) {
   return dn_or_err.takeError();
 DeclContext *dc = *dc_or_err;
 DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
-if (lr.size()) {
-  clang::Decl *lookup_found = lr.front();
-  RegisterImportedDecl(From, lookup_found);
-  m_decls_to_ignore.insert(lookup_found);
-  return lookup_found;
-} else
-  LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
+for (clang::Decl *candidate : lr) {
+  if (candidate->getKind() == From->getKind()) {
+RegisterImportedDecl(From, candidate);
+m_decls_to_ignore.insert(candidate);
+return candidate;
+  }
+}
+LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
   }
 
   return ASTImporter::ImportImpl(From);

diff  --git 
a/lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py 
b/lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
index aa383d0005e4..f9934df4eda4 100644
--- a/lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
+++ b/lldb/test/API/functionalities/limit-debug-info/TestLimitDebugInfo.py
@@ -63,6 +63,9 @@ def test_one_and_two_debug(self):
 self.expect_expr("get_two().one().member", result_value="124")
 self.expect_expr("get_two().member", result_value="224")
 
+self.expect_expr("shadowed_one.member", result_value="47")
+self.expect_expr("shadowed_one.one", result_value="142")
+
 @skipIf(bugnumber="pr46284", debug_info="gmodules")
 @skipIfWindows # Clang emits type info even with -flimit-debug-info
 def test_two_debug(self):

diff  --git a/lldb/test/API/functionalities/limit-debug-info/main.cpp 
b/lldb/test/API/functionalities/limit-debug-info/main.cpp
index 1aad7e6f1e61..1fe4feb33664 100644
--- a/lldb/test/API/functionalities/limit-debug-info/main.cpp
+++ b/lldb/test/API/functionalities/limit-debug-info/main.cpp
@@ -1,23 +1,19 @@
 #include "onetwo.h"
 
 struct InheritsFromOne : One {
-  constexpr InheritsFromOne() = default;
   int member = 47;
 } inherits_from_one;
 
 struct InheritsFromTwo : Two {
-  constexpr InheritsFromTwo() = default;
   int member = 47;
 } inherits_from_two;
 
 struct OneAsMember {
-  constexpr OneAsMember() = default;
   member::One one;
   int member = 47;
 } one_as_member;
 
 struct TwoAsMember {
-  constexpr TwoAsMember() = default;
   member::Two two;
   int member = 47;
 } two_as_member;
@@ -28,4 +24,9 @@ array::Two array_of_two[3];
 result::One get_one() { return result::One(124); }
 result::Two get_two() { return result::Two(224); }
 
+// Note that there's also a function with the name func_shadow::One.
+struct ShadowedOne : func_shadow::One {
+  int member = 47;
+} shadowed_one;
+
 int main() { return get_one().member; }

diff  --git a/lldb/test/API/functionalities/limit-debug-info/one.cpp 
b/lldb/test/API/functionalities/limit-debug-info/one.cpp
index 70353a084edc..ce1d5d14ca06 100644
--- a/lldb/test/API/functionalities/limit-debug-info/one.cpp
+++ b/lldb/test/API/functionalities/limit-debug-info/one.cpp
@@ -6,3 +6,7 @@ array::One::~One() = default;
 
 result::One::One(int member) : member(member) {}
 result::One::~One() = default;
+
+void fun

[Lldb-commits] [PATCH] D85904: [lldb] Check Decl kind when completing -flimit-debug-info types

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
labath marked 2 inline comments as done.
labath added a comment.

In D85904#2215700 , @teemperor wrote:

> Is it too late to claim that I did this on purpose to see if anyone noticed 
> the bug? It probably is :/

:P




Comment at: lldb/test/API/functionalities/limit-debug-info/main.cpp:32
+struct ShadowedOne : public func_shadow::One {
+  constexpr ShadowedOne() = default;
+  int member = 47;

teemperor wrote:
> I'm probably missing something obvious here, but why give every class in the 
> test a defaulted constexpr constructor?
I was trying to guarantee that these variables get constant-initialized because 
earlier versions of this test just inspected a static binary without running 
it. But then one of the cases actually required running code so it no longer 
serves any purpose. I'll just delete them...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85904/new/

https://reviews.llvm.org/D85904

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] e6b1b61 - [lldb] Fix py3 incompatibility in gdbremote_testcase.py

2020-08-14 Thread Pavel Labath via lldb-commits

Author: Pavel Labath
Date: 2020-08-14T12:15:25+02:00
New Revision: e6b1b61054c285efad7bf4ee0a4da53e56944d87

URL: 
https://github.com/llvm/llvm-project/commit/e6b1b61054c285efad7bf4ee0a4da53e56944d87
DIFF: 
https://github.com/llvm/llvm-project/commit/e6b1b61054c285efad7bf4ee0a4da53e56944d87.diff

LOG: [lldb] Fix py3 incompatibility in gdbremote_testcase.py

This didn't cause test failures since this variable is only used during
connection shutdown.

Added: 


Modified: 
lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py

Removed: 




diff  --git 
a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py 
b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
index cea0fee3aaaf..253fd35d461e 100644
--- 
a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
+++ 
b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
@@ -36,7 +36,7 @@ class GdbRemoteTestCaseBase(TestBase):
 # Default sleep time in seconds. The sleep time is doubled under Asan.
 DEFAULT_SLEEP   =  5  * (2  if ('ASAN_OPTIONS' in os.environ) else 1)
 
-_GDBREMOTE_KILL_PACKET = "$k#6b"
+_GDBREMOTE_KILL_PACKET = b"$k#6b"
 
 # Start the inferior separately, attach to the inferior on the stub
 # command line.



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D82537: [lldb] Deduplicate copy-pasted TypeSystemMap::GetTypeSystemForLanguage

2020-08-14 Thread Raphael Isemann via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf974d64b372c: [lldb] Deduplicate copy-pasted 
TypeSystemMap::GetTypeSystemForLanguage (authored by teemperor).
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D82537/new/

https://reviews.llvm.org/D82537

Files:
  lldb/include/lldb/Symbol/TypeSystem.h
  lldb/source/Symbol/TypeSystem.cpp

Index: lldb/source/Symbol/TypeSystem.cpp
===
--- lldb/source/Symbol/TypeSystem.cpp
+++ lldb/source/Symbol/TypeSystem.cpp
@@ -224,9 +224,9 @@
   }
 }
 
-llvm::Expected
-TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
-Module *module, bool can_create) {
+llvm::Expected TypeSystemMap::GetTypeSystemForLanguage(
+lldb::LanguageType language,
+llvm::Optional create_callback) {
   llvm::Error error = llvm::Error::success();
   assert(!error); // Check the success value when assertions are enabled
   std::lock_guard guard(m_mutex);
@@ -268,7 +268,7 @@
   }
 }
 
-if (!can_create) {
+if (!create_callback) {
   error = llvm::make_error(
   "Unable to find type system for language " +
   llvm::StringRef(Language::GetNameForLanguageType(language)),
@@ -276,7 +276,7 @@
 } else {
   // Cache even if we get a shared pointer that contains a null type system
   // back
-  auto type_system_sp = TypeSystem::CreateInstance(language, module);
+  TypeSystemSP type_system_sp = (*create_callback)();
   m_map[language] = type_system_sp;
   if (type_system_sp.get()) {
 llvm::consumeError(std::move(error));
@@ -295,69 +295,24 @@
 
 llvm::Expected
 TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
-Target *target, bool can_create) {
-  llvm::Error error = llvm::Error::success();
-  assert(!error); // Check the success value when assertions are enabled
-  std::lock_guard guard(m_mutex);
-  if (m_clear_in_progress) {
-error = llvm::make_error(
-"Unable to get TypeSystem because TypeSystemMap is being cleared",
-llvm::inconvertibleErrorCode());
-  } else {
-collection::iterator pos = m_map.find(language);
-if (pos != m_map.end()) {
-  auto *type_system = pos->second.get();
-  if (type_system) {
-llvm::consumeError(std::move(error));
-return *type_system;
-  }
-  error = llvm::make_error(
-  "TypeSystem for language " +
-  llvm::StringRef(Language::GetNameForLanguageType(language)) +
-  " doesn't exist",
-  llvm::inconvertibleErrorCode());
-  return std::move(error);
-}
-
-for (const auto &pair : m_map) {
-  if (pair.second && pair.second->SupportsLanguage(language)) {
-// Add a new mapping for "language" to point to an already existing
-// TypeSystem that supports this language
-m_map[language] = pair.second;
-if (pair.second.get()) {
-  llvm::consumeError(std::move(error));
-  return *pair.second.get();
-}
-error = llvm::make_error(
-"TypeSystem for language " +
-llvm::StringRef(Language::GetNameForLanguageType(language)) +
-" doesn't exist",
-llvm::inconvertibleErrorCode());
-return std::move(error);
-  }
-}
-
-if (!can_create) {
-  error = llvm::make_error(
-  "Unable to find type system for language " +
-  llvm::StringRef(Language::GetNameForLanguageType(language)),
-  llvm::inconvertibleErrorCode());
-} else {
-  // Cache even if we get a shared pointer that contains a null type system
-  // back
-  auto type_system_sp = TypeSystem::CreateInstance(language, target);
-  m_map[language] = type_system_sp;
-  if (type_system_sp.get()) {
-llvm::consumeError(std::move(error));
-return *type_system_sp.get();
-  }
-  error = llvm::make_error(
-  "TypeSystem for language " +
-  llvm::StringRef(Language::GetNameForLanguageType(language)) +
-  " doesn't exist",
-  llvm::inconvertibleErrorCode());
-}
+Module *module, bool can_create) {
+  if (can_create) {
+return GetTypeSystemForLanguage(
+language, llvm::Optional([language, module]() {
+  return TypeSystem::CreateInstance(language, module);
+}));
   }
+  return GetTypeSystemForLanguage(language);
+}
 
-  return std::move(error);
+llvm::Expected
+TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
+Target *target, bool can_create) {
+  if (can_create) {
+return GetTypeSystemForLanguage(
+language, llvm::Optional([language, target]() {

[Lldb-commits] [lldb] f974d64 - [lldb] Deduplicate copy-pasted TypeSystemMap::GetTypeSystemForLanguage

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Raphael Isemann
Date: 2020-08-14T11:58:54+02:00
New Revision: f974d64b372c5554783369bab901de8f4dee5e02

URL: 
https://github.com/llvm/llvm-project/commit/f974d64b372c5554783369bab901de8f4dee5e02
DIFF: 
https://github.com/llvm/llvm-project/commit/f974d64b372c5554783369bab901de8f4dee5e02.diff

LOG: [lldb] Deduplicate copy-pasted TypeSystemMap::GetTypeSystemForLanguage

There are two implementations for `TypeSystemMap::GetTypeSystemForLanguage`
which are both identical beside one taking a `Module` and one taking a `Target`
(and then passing that argument to the `TypeSystem::CreateInstance` function).

This merges both implementations into one function with a lambda that wraps the
different calls to `TypeSystem::CreateInstance`.

Reviewed By: #lldb, JDevlieghere

Differential Revision: https://reviews.llvm.org/D82537

Added: 


Modified: 
lldb/include/lldb/Symbol/TypeSystem.h
lldb/source/Symbol/TypeSystem.cpp

Removed: 




diff  --git a/lldb/include/lldb/Symbol/TypeSystem.h 
b/lldb/include/lldb/Symbol/TypeSystem.h
index c19909506349..4b851fea6e02 100644
--- a/lldb/include/lldb/Symbol/TypeSystem.h
+++ b/lldb/include/lldb/Symbol/TypeSystem.h
@@ -523,6 +523,22 @@ class TypeSystemMap {
   ///multi-threaded environments.
   collection m_map;
   bool m_clear_in_progress;
+
+private:
+  typedef llvm::function_ref CreateCallback;
+  /// Finds the type system for the given language. If no type system could be
+  /// found for a language and a CreateCallback was provided, the value 
returned
+  /// by the callback will be treated as the TypeSystem for the language.
+  ///
+  /// \param language The language for which the type system should be found.
+  /// \param create_callback A callback that will be called if no previously
+  ///created TypeSystem that fits the given language
+  ///could found. Can be omitted if a non-existent
+  ///type system should be treated as an error instead.
+  /// \return The found type system or an error.
+  llvm::Expected GetTypeSystemForLanguage(
+  lldb::LanguageType language,
+  llvm::Optional create_callback = llvm::None);
 };
 
 } // namespace lldb_private

diff  --git a/lldb/source/Symbol/TypeSystem.cpp 
b/lldb/source/Symbol/TypeSystem.cpp
index 5e57813c28bd..985065926fc4 100644
--- a/lldb/source/Symbol/TypeSystem.cpp
+++ b/lldb/source/Symbol/TypeSystem.cpp
@@ -224,9 +224,9 @@ void TypeSystemMap::ForEach(std::function const &callback) {
   }
 }
 
-llvm::Expected
-TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
-Module *module, bool can_create) {
+llvm::Expected TypeSystemMap::GetTypeSystemForLanguage(
+lldb::LanguageType language,
+llvm::Optional create_callback) {
   llvm::Error error = llvm::Error::success();
   assert(!error); // Check the success value when assertions are enabled
   std::lock_guard guard(m_mutex);
@@ -268,7 +268,7 @@ TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType 
language,
   }
 }
 
-if (!can_create) {
+if (!create_callback) {
   error = llvm::make_error(
   "Unable to find type system for language " +
   llvm::StringRef(Language::GetNameForLanguageType(language)),
@@ -276,7 +276,7 @@ TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType 
language,
 } else {
   // Cache even if we get a shared pointer that contains a null type system
   // back
-  auto type_system_sp = TypeSystem::CreateInstance(language, module);
+  TypeSystemSP type_system_sp = (*create_callback)();
   m_map[language] = type_system_sp;
   if (type_system_sp.get()) {
 llvm::consumeError(std::move(error));
@@ -295,69 +295,24 @@ 
TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
 
 llvm::Expected
 TypeSystemMap::GetTypeSystemForLanguage(lldb::LanguageType language,
-Target *target, bool can_create) {
-  llvm::Error error = llvm::Error::success();
-  assert(!error); // Check the success value when assertions are enabled
-  std::lock_guard guard(m_mutex);
-  if (m_clear_in_progress) {
-error = llvm::make_error(
-"Unable to get TypeSystem because TypeSystemMap is being cleared",
-llvm::inconvertibleErrorCode());
-  } else {
-collection::iterator pos = m_map.find(language);
-if (pos != m_map.end()) {
-  auto *type_system = pos->second.get();
-  if (type_system) {
-llvm::consumeError(std::move(error));
-return *type_system;
-  }
-  error = llvm::make_error(
-  "TypeSystem for language " +
-  llvm::StringRef(Language::GetNameForLanguageType(language)) +
-  " doesn't exist",
-  llvm::inconvertibleErrorCode());
-  return std::move(error);
-}
-
-for (const auto &pair :

[Lldb-commits] [lldb] de9e850 - [lldb] Display autosuggestion part in gray if there is one possible suggestion

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Shu Anzai
Date: 2020-08-14T11:37:49+02:00
New Revision: de9e85026fcb7c3e992f12a86594fd50bb101ad3

URL: 
https://github.com/llvm/llvm-project/commit/de9e85026fcb7c3e992f12a86594fd50bb101ad3
DIFF: 
https://github.com/llvm/llvm-project/commit/de9e85026fcb7c3e992f12a86594fd50bb101ad3.diff

LOG: [lldb] Display autosuggestion part in gray if there is one possible 
suggestion

This is relanding D81001. The patch originally failed as on newer editline
versions it seems CC_REFRESH will move the cursor to the start of the line via
\r and then back to the original position. On older editline versions like
the one used by default on macOS, CC_REFRESH doesn't move the cursor at all.
As the patch changed the way we handle tab completion (previously we did
REDISPLAY but now we're doing CC_REFRESH), this caused a few completion tests
to receive this unexpected cursor movement in the output stream.
This patch updates those tests to also accept output that contains the specific
cursor movement commands (\r and then \x1b[XC). lldbpexpect.py received an
utility method for generating the cursor movement escape sequence.

Original summary:

I implemented autosuggestion if there is one possible suggestion.
I set the keybinds for every character. When a character is typed, 
Editline::TypedCharacter is called.
Then, autosuggestion part is displayed in gray, and you can actually input by 
typing C-k.
Editline::Autosuggest is a function for finding completion, and it is like 
Editline::TabCommand now, but I will add more features to it.

Testing does not work well in my environment, so I can't confirm that it goes 
well, sorry. I am dealing with it now.

Reviewed By: teemperor, JDevlieghere, #lldb

Differential Revision: https://reviews.llvm.org/D81001

Added: 
lldb/test/API/iohandler/autosuggestion/TestAutosuggestion.py

Modified: 
lldb/include/lldb/Core/Debugger.h
lldb/include/lldb/Core/IOHandler.h
lldb/include/lldb/Host/Editline.h
lldb/include/lldb/Interpreter/CommandInterpreter.h
lldb/packages/Python/lldbsuite/test/lldbpexpect.py
lldb/source/Core/CoreProperties.td
lldb/source/Core/Debugger.cpp
lldb/source/Core/IOHandler.cpp
lldb/source/Host/common/Editline.cpp
lldb/source/Interpreter/CommandInterpreter.cpp

lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
lldb/test/API/iohandler/completion/TestIOHandlerCompletion.py

Removed: 




diff  --git a/lldb/include/lldb/Core/Debugger.h 
b/lldb/include/lldb/Core/Debugger.h
index 7bea0dbae0826..252380de27865 100644
--- a/lldb/include/lldb/Core/Debugger.h
+++ b/lldb/include/lldb/Core/Debugger.h
@@ -273,6 +273,8 @@ class Debugger : public 
std::enable_shared_from_this,
 
   bool SetUseColor(bool use_color);
 
+  bool GetUseAutosuggestion() const;
+
   bool GetUseSourceCache() const;
 
   bool SetUseSourceCache(bool use_source_cache);

diff  --git a/lldb/include/lldb/Core/IOHandler.h 
b/lldb/include/lldb/Core/IOHandler.h
index 51592afbbabe7..f29482c0c97a1 100644
--- a/lldb/include/lldb/Core/IOHandler.h
+++ b/lldb/include/lldb/Core/IOHandler.h
@@ -203,6 +203,9 @@ class IOHandlerDelegate {
 
   virtual void IOHandlerDeactivated(IOHandler &io_handler) {}
 
+  virtual llvm::Optional IOHandlerSuggestion(IOHandler 
&io_handler,
+  llvm::StringRef 
line);
+
   virtual void IOHandlerComplete(IOHandler &io_handler,
  CompletionRequest &request);
 
@@ -420,6 +423,9 @@ class IOHandlerEditline : public IOHandler {
   static int FixIndentationCallback(Editline *editline, const StringList 
&lines,
 int cursor_position, void *baton);
 
+  static llvm::Optional SuggestionCallback(llvm::StringRef line,
+void *baton);
+
   static void AutoCompleteCallback(CompletionRequest &request, void *baton);
 #endif
 

diff  --git a/lldb/include/lldb/Host/Editline.h 
b/lldb/include/lldb/Host/Editline.h
index 356e8f7347329..a37ad1b9d1068 100644
--- a/lldb/include/lldb/Host/Editline.h
+++ b/lldb/include/lldb/Host/Editline.h
@@ -98,6 +98,9 @@ typedef int (*FixIndentationCallbackType)(Editline *editline,
   const StringList &lines,
   int cursor_position, void *baton);
 
+typedef llvm::Optional (*SuggestionCallbackType)(
+llvm::StringRef line, void *baton);
+
 typedef void (*CompleteCallbackType)(CompletionRequest &request, void *baton);
 
 /// Status used to decide when and how to start editing another line in
@@ -184,6 +187,9 @@ class Editline {
   /// Cancel this edit and oblitarate all trace of it
   bool Cancel();
 
+  /// Register a callback for autosuggestion.
+  void SetSuggestionCallback(SuggestionCallbackType callback, void *baton);
+
   /// Register a callback for the tab key
   v

[Lldb-commits] [lldb] 40d7742 - [lldb/Utility] Simplify Scalar::PromoteToMaxType

2020-08-14 Thread Pavel Labath via lldb-commits

Author: Pavel Labath
Date: 2020-08-14T11:09:16+02:00
New Revision: 40d774265b08fbfd0f3e2ffa79ce7feddbd060bc

URL: 
https://github.com/llvm/llvm-project/commit/40d774265b08fbfd0f3e2ffa79ce7feddbd060bc
DIFF: 
https://github.com/llvm/llvm-project/commit/40d774265b08fbfd0f3e2ffa79ce7feddbd060bc.diff

LOG: [lldb/Utility] Simplify Scalar::PromoteToMaxType

The function had very complicated signature, because it was trying to
avoid making unnecessary copies of the Scalar object. However, this
class is not hot enough to worry about these kinds of optimizations. My
making copies unconditionally, we can simplify the function and all of
its call sites.

Differential Revision: https://reviews.llvm.org/D85906

Added: 


Modified: 
lldb/include/lldb/Utility/Scalar.h
lldb/source/Utility/Scalar.cpp

Removed: 




diff  --git a/lldb/include/lldb/Utility/Scalar.h 
b/lldb/include/lldb/Utility/Scalar.h
index 45ba7c012229..7e416c04f3ca 100644
--- a/lldb/include/lldb/Utility/Scalar.h
+++ b/lldb/include/lldb/Utility/Scalar.h
@@ -151,7 +151,7 @@ class Scalar {
   // automagically by the compiler, so no temporary objects will need to be
   // created. As a result, we currently don't need a variety of overloaded set
   // value accessors.
-  Scalar &operator+=(const Scalar &rhs);
+  Scalar &operator+=(Scalar rhs);
   Scalar &operator<<=(const Scalar &rhs); // Shift left
   Scalar &operator>>=(const Scalar &rhs); // Shift right (arithmetic)
   Scalar &operator&=(const Scalar &rhs);
@@ -266,18 +266,18 @@ class Scalar {
 
 private:
   friend const Scalar operator+(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator-(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator/(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator*(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator&(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator|(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator%(const Scalar &lhs, const Scalar &rhs);
-  friend const Scalar operator^(const Scalar &lhs, const Scalar &rhs);
+  friend const Scalar operator-(Scalar lhs, Scalar rhs);
+  friend const Scalar operator/(Scalar lhs, Scalar rhs);
+  friend const Scalar operator*(Scalar lhs, Scalar rhs);
+  friend const Scalar operator&(Scalar lhs, Scalar rhs);
+  friend const Scalar operator|(Scalar lhs, Scalar rhs);
+  friend const Scalar operator%(Scalar lhs, Scalar rhs);
+  friend const Scalar operator^(Scalar lhs, Scalar rhs);
   friend const Scalar operator<<(const Scalar &lhs, const Scalar &rhs);
   friend const Scalar operator>>(const Scalar &lhs, const Scalar &rhs);
-  friend bool operator==(const Scalar &lhs, const Scalar &rhs);
+  friend bool operator==(Scalar lhs, Scalar rhs);
   friend bool operator!=(const Scalar &lhs, const Scalar &rhs);
-  friend bool operator<(const Scalar &lhs, const Scalar &rhs);
+  friend bool operator<(Scalar lhs, Scalar rhs);
   friend bool operator<=(const Scalar &lhs, const Scalar &rhs);
   friend bool operator>(const Scalar &lhs, const Scalar &rhs);
   friend bool operator>=(const Scalar &lhs, const Scalar &rhs);
@@ -297,18 +297,18 @@ class Scalar {
 //  Differentiate among members functions, non-member functions, and
 //  friend functions
 const Scalar operator+(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator-(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator/(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator*(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator&(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator|(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator%(const Scalar &lhs, const Scalar &rhs);
-const Scalar operator^(const Scalar &lhs, const Scalar &rhs);
+const Scalar operator-(Scalar lhs, Scalar rhs);
+const Scalar operator/(Scalar lhs, Scalar rhs);
+const Scalar operator*(Scalar lhs, Scalar rhs);
+const Scalar operator&(Scalar lhs, Scalar rhs);
+const Scalar operator|(Scalar lhs, Scalar rhs);
+const Scalar operator%(Scalar lhs, Scalar rhs);
+const Scalar operator^(Scalar lhs, Scalar rhs);
 const Scalar operator<<(const Scalar &lhs, const Scalar &rhs);
 const Scalar operator>>(const Scalar &lhs, const Scalar &rhs);
-bool operator==(const Scalar &lhs, const Scalar &rhs);
+bool operator==(Scalar lhs, Scalar rhs);
 bool operator!=(const Scalar &lhs, const Scalar &rhs);
-bool operator<(const Scalar &lhs, const Scalar &rhs);
+bool operator<(Scalar lhs, Scalar rhs);
 bool operator<=(const Scalar &lhs, const Scalar &rhs);
 bool operator>(const Scalar &lhs, const Scalar &rhs);
 bool operator>=(const Scalar &lhs, const Scalar &rhs);

diff  --git a/lldb/source/Utility/Scalar.cpp b/lldb/source/Utility/Scalar.cpp
index 9309f8d662da..2ea1dafcf145 100644
--- a/lldb/source/Utility/Scalar.cpp
+++ b/lldb/source/Utility/Scalar.cpp
@@ -82,45 +82,19 @@ static bool IsSigned(S

[Lldb-commits] [PATCH] D85906: [lldb/Utility] Simplify Scalar::PromoteToMaxType

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG40d774265b08: [lldb/Utility] Simplify 
Scalar::PromoteToMaxType (authored by labath).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85906/new/

https://reviews.llvm.org/D85906

Files:
  lldb/include/lldb/Utility/Scalar.h
  lldb/source/Utility/Scalar.cpp

Index: lldb/source/Utility/Scalar.cpp
===
--- lldb/source/Utility/Scalar.cpp
+++ lldb/source/Utility/Scalar.cpp
@@ -82,45 +82,19 @@
 
 // Promote to max type currently follows the ANSI C rule for type promotion in
 // expressions.
-static Scalar::Type PromoteToMaxType(
-const Scalar &lhs,  // The const left hand side object
-const Scalar &rhs,  // The const right hand side object
-Scalar &temp_value, // A modifiable temp value than can be used to hold
-// either the promoted lhs or rhs object
-const Scalar *&promoted_lhs_ptr, // Pointer to the resulting possibly
- // promoted value of lhs (at most one of
- // lhs/rhs will get promoted)
-const Scalar *&promoted_rhs_ptr  // Pointer to the resulting possibly
- // promoted value of rhs (at most one of
- // lhs/rhs will get promoted)
-) {
-  Scalar result;
-  // Initialize the promoted values for both the right and left hand side
-  // values to be the objects themselves. If no promotion is needed (both right
-  // and left have the same type), then the temp_value will not get used.
-  promoted_lhs_ptr = &lhs;
-  promoted_rhs_ptr = &rhs;
+static Scalar::Type PromoteToMaxType(Scalar &lhs, Scalar &rhs) {
   // Extract the types of both the right and left hand side values
   Scalar::Type lhs_type = lhs.GetType();
   Scalar::Type rhs_type = rhs.GetType();
 
-  if (lhs_type > rhs_type) {
-// Right hand side need to be promoted
-temp_value = rhs; // Copy right hand side into the temp value
-if (temp_value.Promote(lhs_type)) // Promote it
-  promoted_rhs_ptr =
-  &temp_value; // Update the pointer for the promoted right hand side
-  } else if (lhs_type < rhs_type) {
-// Left hand side need to be promoted
-temp_value = lhs; // Copy left hand side value into the temp value
-if (temp_value.Promote(rhs_type)) // Promote it
-  promoted_lhs_ptr =
-  &temp_value; // Update the pointer for the promoted left hand side
-  }
+  if (lhs_type > rhs_type)
+rhs.Promote(lhs_type);
+  else if (lhs_type < rhs_type)
+lhs.Promote(rhs_type);
 
   // Make sure our type promotion worked as expected
-  if (promoted_lhs_ptr->GetType() == promoted_rhs_ptr->GetType())
-return promoted_lhs_ptr->GetType(); // Return the resulting max type
+  if (lhs.GetType() == rhs.GetType())
+return lhs.GetType(); // Return the resulting max type
 
   // Return the void type (zero) if we fail to promote either of the values.
   return Scalar::e_void;
@@ -684,21 +658,18 @@
   return static_cast(Double(fail_value));
 }
 
-Scalar &Scalar::operator+=(const Scalar &rhs) {
-  Scalar temp_value;
-  const Scalar *a;
-  const Scalar *b;
-  if ((m_type = PromoteToMaxType(*this, rhs, temp_value, a, b)) !=
-  Scalar::e_void) {
+Scalar &Scalar::operator+=(Scalar rhs) {
+  Scalar copy = *this;
+  if ((m_type = PromoteToMaxType(copy, rhs)) != Scalar::e_void) {
 switch (GetCategory(m_type)) {
 case Category::Void:
   break;
 case Category::Integral:
-  m_integer = a->m_integer + b->m_integer;
+  m_integer = copy.m_integer + rhs.m_integer;
   break;
 
 case Category::Float:
-  m_float = a->m_float + b->m_float;
+  m_float = copy.m_float + rhs.m_float;
   break;
 }
   }
@@ -841,46 +812,38 @@
   return result;
 }
 
-const Scalar lldb_private::operator-(const Scalar &lhs, const Scalar &rhs) {
+const Scalar lldb_private::operator-(Scalar lhs, Scalar rhs) {
   Scalar result;
-  Scalar temp_value;
-  const Scalar *a;
-  const Scalar *b;
-  if ((result.m_type = PromoteToMaxType(lhs, rhs, temp_value, a, b)) !=
-  Scalar::e_void) {
+  if ((result.m_type = PromoteToMaxType(lhs, rhs)) != Scalar::e_void) {
 switch (GetCategory(result.m_type)) {
 case Category::Void:
   break;
 case Category::Integral:
-  result.m_integer = a->m_integer - b->m_integer;
+  result.m_integer = lhs.m_integer - rhs.m_integer;
   break;
 case Category::Float:
-  result.m_float = a->m_float - b->m_float;
+  result.m_float = lhs.m_float - rhs.m_float;
   break;
 }
   }
   return result;
 }
 
-const Scalar lldb_private::operator/(const Scalar &lhs, const Scalar &rhs) {
+const Scalar lldb_private::operator/(Scalar lhs, Scalar rhs) {
   Scalar result;
-  Scalar temp_value;
-  const Scalar *a;
-  const Scalar *b;

[Lldb-commits] [PATCH] D79699: Add ptrace register access for AArch64 SVE registers

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
labath added a comment.

In D79699#2215216 , @omjavaid wrote:

> @labath Any further action needed on this change? I have updated test main.c 
> for doing asm write to SVE regs and then reading them back during testing. 
> Also i have removed NativeProcessLinux_arm64 dependence on 
> LinuxPTraceDefines_arm64sve.h.  We are using sys root's ptrace.h as SVE 
> marcros are back ported in most versions of ptrace.h.

Almost. I have two more questions/requests inline.




Comment at: 
lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py:100-106
+has_sve = False
+for registerSet in currentFrame.GetRegisters():
+if 'Scalable Vector Extension Registers' in registerSet.GetName():
+has_sve = True
+
+if not has_sve:
+self.skipTest('SVE registers must be supported.')

Are you sure this will work if the system does not support SVE? I would expect 
the test application to die from SIGILL (or something) long before we reach 
this part.

Even if it does work, it will mean that the test will be skipped (instead of 
failing) if the lldb-server stops reporting the sve registers (or even if it 
just slightly changes the register set name). That's why I was originally 
suggesting to check for SVE support from within the inferior process.

Is there a simple way to do that? I'm assuming there must be, otherwise the 
application could not detect whether it can use sve...



Comment at: 
lldb/test/API/commands/register/register/aarch64_sve_registers/rw_access_static_config/TestSVERegisters.py:134
+for i in range(16):
+self.expect("register read " + 'p%i' % (i), substrs=[p_regs_value])
+

So, the program sets all p registers to the same value (0x..) right? Would 
it be possible to introduce some variance there (like you did for the z 
registers), to ensure that the registers are actually read from the right place?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D79699/new/

https://reviews.llvm.org/D79699

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85539: [lldb] Extend builder to pass the TRIPLE spec to Make

2020-08-14 Thread Pavel Labath via Phabricator via lldb-commits
labath added a comment.

In D85539#2216197 , @JDevlieghere 
wrote:

> Even though this file is called "base", there's no inheritance going on here, 
> it's just methods and `lldbtest.py` will import the appropriate module. I 
> considered this too, but didn't feel like rewriting those files as a classes 
> for this small change. But if we're going to pass the `TRIPLE`, `OS` and 
> `VERSION` separately, we might as well.

I'd just send the final ARCH_CFLAGS value. Then the Android.rules makefile 
could be ported to python as well.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85539/new/

https://reviews.llvm.org/D85539

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D85903: [lldb] Fix a crash when tab-completion an empty line in a function with only one local variable

2020-08-14 Thread Raphael Isemann via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbbe3c479a6ad: [lldb] Fix a crash when tab-completion an 
empty line in a function with only… (authored by teemperor).
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85903/new/

https://reviews.llvm.org/D85903

Files:
  lldb/source/Host/common/Editline.cpp
  
lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
  lldb/test/API/commands/expression/multiline-completion/main.c


Index: lldb/test/API/commands/expression/multiline-completion/main.c
===
--- lldb/test/API/commands/expression/multiline-completion/main.c
+++ lldb/test/API/commands/expression/multiline-completion/main.c
@@ -1,4 +1,11 @@
+int single_local_func() {
+  // This function should always only have a single local variable and no
+  // parameters.
+  int only_local = 3;
+  return only_local; // break in single_local_func
+}
+
 int main(int argc, char **argv) {
   int to_complete = 0;
-  return to_complete;
+  return to_complete + single_local_func();
 }
Index: 
lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
===
--- 
lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
+++ 
lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
@@ -11,6 +11,21 @@
 
 mydir = TestBase.compute_mydir(__file__)
 
+def start_expression_editor(self):
+""" Starts the multiline expression editor. """
+self.child.send("expression\n")
+self.child.expect_exact("terminate with an empty line to evaluate")
+
+def exit_expression_editor(self):
+""" Exits the multiline expression editor. """
+# Send a newline to finish the current line. The second newline will
+# finish the new empty line which will exit the editor. The space at 
the
+# start prevents that the first newline already exits the editor (in
+# case the current line of the editor is already empty when this
+# function is called).
+self.child.send(" \n\n")
+self.expect_prompt()
+
 # PExpect uses many timeouts internally and doesn't play well
 # under ASAN on a loaded machine..
 @skipIfAsan
@@ -21,14 +36,23 @@
 
 self.launch(executable=self.getBuildArtifact("a.out"), 
dimensions=(100,500))
 self.expect("b main", substrs=["Breakpoint 1", "address ="])
-self.expect("run", substrs=["stop reason ="])
+self.expect("run", substrs=["stop reason = breakpoint 1"])
 
-self.child.sendline("expr")
-self.child.expect_exact("terminate with an empty line to evaluate")
+self.start_expression_editor()
 self.child.send("to_\t")
 self.child.expect_exact("to_complete")
-
-self.child.send("\n\n")
-self.expect_prompt()
+self.exit_expression_editor()
+
+# Check that completion empty input in a function with only one
+# local variable works.
+self.expect("breakpoint set -p 'break in single_local_func'",
+substrs=["Breakpoint 2"])
+self.expect("continue", substrs=["stop reason = breakpoint 2"])
+self.start_expression_editor()
+self.child.send("\t")
+# Only one local, so this will directly insert 'only_local' with a
+# trailing space to signal a final completion.
+self.child.expect_exact("only_local ")
+self.exit_expression_editor()
 
 self.quit()
Index: lldb/source/Host/common/Editline.cpp
===
--- lldb/source/Host/common/Editline.cpp
+++ lldb/source/Host/common/Editline.cpp
@@ -1004,7 +1004,8 @@
 case CompletionMode::Normal: {
   std::string to_add = completion.GetCompletion();
   to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
-  if (request.GetParsedArg().IsQuoted())
+  // Terminate the current argument with a quote if it started with a 
quote.
+  if (!request.GetParsedLine().empty() && 
request.GetParsedArg().IsQuoted())
 to_add.push_back(request.GetParsedArg().GetQuoteChar());
   to_add.push_back(' ');
   el_insertstr(m_editline, to_add.c_str());


Index: lldb/test/API/commands/expression/multiline-completion/main.c
===
--- lldb/test/API/commands/expression/multiline-completion/main.c
+++ lldb/test/API/commands/expression/multiline-completion/main.c
@@ -1,4 +1,11 @@
+int single_local_func() {
+  // This function should always only have a single local variable and no
+  // parameters.
+  int only_local = 3;
+  return only_local; // break in single_local_func
+}
+
 int main(int argc, char **argv) {

[Lldb-commits] [lldb] bbe3c47 - [lldb] Fix a crash when tab-completion an empty line in a function with only one local variable

2020-08-14 Thread Raphael Isemann via lldb-commits

Author: Raphael Isemann
Date: 2020-08-14T09:06:52+02:00
New Revision: bbe3c479a6adf0abfe5d111e9ba206daa5a1eb2b

URL: 
https://github.com/llvm/llvm-project/commit/bbe3c479a6adf0abfe5d111e9ba206daa5a1eb2b
DIFF: 
https://github.com/llvm/llvm-project/commit/bbe3c479a6adf0abfe5d111e9ba206daa5a1eb2b.diff

LOG: [lldb] Fix a crash when tab-completion an empty line in a function with 
only one local variable

When LLDB sees only one possible completion for an input, it will add a trailing
space to the completion to signal that to the user. If the current argument is
quoted, that also means LLDB needs to add the trailing quote to finish the
current argument first.

In case the user is in a function with only one local variable and is currently
editing an empty line in the multiline expression editor, then we are in the
unique situation where we can have a unique completion for an empty input line.
(In a normal LLDB session this would never occur as empty input would just list
all the possible commands).

In this special situation our check if the current argument needs to receive a
trailing quote will crash LLDB as there is no current argument and the
completion code just unconditionally tries to access the current argument. This
just adds the missing check if we even have a current argument before we check
if we need to add a terminating quote character.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D85903

Added: 


Modified: 
lldb/source/Host/common/Editline.cpp

lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
lldb/test/API/commands/expression/multiline-completion/main.c

Removed: 




diff  --git a/lldb/source/Host/common/Editline.cpp 
b/lldb/source/Host/common/Editline.cpp
index 49b7a38d8dae..1e1bcb0ac7c6 100644
--- a/lldb/source/Host/common/Editline.cpp
+++ b/lldb/source/Host/common/Editline.cpp
@@ -1004,7 +1004,8 @@ unsigned char Editline::TabCommand(int ch) {
 case CompletionMode::Normal: {
   std::string to_add = completion.GetCompletion();
   to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
-  if (request.GetParsedArg().IsQuoted())
+  // Terminate the current argument with a quote if it started with a 
quote.
+  if (!request.GetParsedLine().empty() && 
request.GetParsedArg().IsQuoted())
 to_add.push_back(request.GetParsedArg().GetQuoteChar());
   to_add.push_back(' ');
   el_insertstr(m_editline, to_add.c_str());

diff  --git 
a/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
 
b/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
index e4935d0e2b84..3e2663d9bdfe 100644
--- 
a/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
+++ 
b/lldb/test/API/commands/expression/multiline-completion/TestMultilineCompletion.py
@@ -11,6 +11,21 @@ class MultilineCompletionTest(PExpectTest):
 
 mydir = TestBase.compute_mydir(__file__)
 
+def start_expression_editor(self):
+""" Starts the multiline expression editor. """
+self.child.send("expression\n")
+self.child.expect_exact("terminate with an empty line to evaluate")
+
+def exit_expression_editor(self):
+""" Exits the multiline expression editor. """
+# Send a newline to finish the current line. The second newline will
+# finish the new empty line which will exit the editor. The space at 
the
+# start prevents that the first newline already exits the editor (in
+# case the current line of the editor is already empty when this
+# function is called).
+self.child.send(" \n\n")
+self.expect_prompt()
+
 # PExpect uses many timeouts internally and doesn't play well
 # under ASAN on a loaded machine..
 @skipIfAsan
@@ -21,14 +36,23 @@ def test_basic_completion(self):
 
 self.launch(executable=self.getBuildArtifact("a.out"), 
dimensions=(100,500))
 self.expect("b main", substrs=["Breakpoint 1", "address ="])
-self.expect("run", substrs=["stop reason ="])
+self.expect("run", substrs=["stop reason = breakpoint 1"])
 
-self.child.sendline("expr")
-self.child.expect_exact("terminate with an empty line to evaluate")
+self.start_expression_editor()
 self.child.send("to_\t")
 self.child.expect_exact("to_complete")
-
-self.child.send("\n\n")
-self.expect_prompt()
+self.exit_expression_editor()
+
+# Check that completion empty input in a function with only one
+# local variable works.
+self.expect("breakpoint set -p 'break in single_local_func'",
+substrs=["Breakpoint 2"])
+self.expect("continue", substrs=["stop reason = breakpoint 2"])
+self.start_expression_editor()
+self.child.send("\t")
+# Only one